Syntax Error PHP Parse
PHP syntax errors are easy to make, and if unchecked can popup from the rarely used corners of a complicated application. If you short on time finding a debugger of some sort, don’t want to mess with installing software on the server, or just plain lazy, try this out at the command line:
find . -type f -name *.php -exec php -l {} ;
This would check all files with a “php” extension from the current directory (.) and down into the sub directories. I’m not claiming this is 100% accurate, but it sure is quick to type… or copy and paste.
If you wanted to fancy it up a bit, you might wrap it in PHP and do something like this (you could even run it against itself!):
<?php $search_dir = "./"; $verbose = false; if(count($argv) >= 2){ if(is_dir($argv[1])) $search_dir = $argv[1]; } if(count($argv) >= 3){ if((bool)$argv[2] === true) $verbose = (bool)$argv[2]; } echo("Testing $search_dirn"); exec('find '.$search_dir.' -type f -name *.php -exec php -l {} ;'); echo("Donen");
This allows you to execute from command line and pass in optional search directory and whether it will only show errors or everything. Here is an example for searching the sub directory “inc” and showing all files tested:
php check_syntax.php "inc/" true
Finishing up the user login in PHP
In a previous article I covered an example of how to log a user in using an HTML form and PHP. In another article I talked some about the global SESSION variable. Now I will show you an example of how to validate the login against a MySQL database.
In the following code it is assumed that a user has posted a username and password to this web page for validation. Let’s take a look at the code:
<?php // Check for username and password values in our POST variable if (isset($_POST['username']) && isset($_POST['password']) && ! empty($_POST['username']) && ! empty($_POST['password'])) { // Sanitize the username. We don't want to mess up our db query or inject anything hazardous $safe_username = mysql_real_escape_string($_POST['username']); // Hash the password, resulting in a 32 byte string. A hash doesn't need to be escaped. $safe_password = md5($_POST['password']); // Run the query. It will return a result if we have a match $sql = "SELECT * FROM users WHERE username = '$safe_username' AND password = '$safe_password'"; $res = mysql_query($sql); // Check for a returned row if ($row = mysql_fetch_assoc($res)) { // A match was found and a row returned. Get the user ID and store it in a session $user_id = $row['id']; // Start our session session_start(); // Assign the user ID to the session $_SESSION['user_id'] = $user_id; // Now our user is logged in and can roam freely about the cabin (secure pages) // Redirect to the user's profile page header("location:profile.php"); // Halt execution of code. We're done here. exit; } // Login failed. Let the user know. echo("Login attempt failed. Please try again."); } ?>
What does this do? The script takes the posted username and password and queries the database for a match. If a match is found the user’s ID is stored in the SESSION variable, and the user is redirected to their profile page. The purpose for storing the user id is so that other pages can know if the visitor is logged in, or in other words, has a session.
The profile.php page might do something like the following to be sure the visitor can see the page.
<?php // The first thing we should do is make sure that the visitor has successfully logged in. // Otherwise we don't want to show this page. // Start a session session_start(); // Check for the "user_id" variable if (isset($_SESSION['user_id'])) { // The user has a valid session. We can then use the ID for various things in our web // application. } else { // A visitor is trying to access this page without a valid session. Bad user, bad! // Redirect them to the login page header("location:login.php"); // We're done here so get out exit; } echo("Welcome to your profile!"); ?>
And that’s it! I hope this has given you some ideas of how you might implement a user login and track that user across pages on your own site. Enjoy!
Adding an element to the beginning of an array in PHP
// Create an array $a = new array("apple", "orange"); // Prepend an element to the array array_unshift($a, "raspberry"); // Prepend a couple more elements to the array array_unshift($a, "pineapple", "watermelon");
Adding an element to the end of an array in PHP
There are two ways to add an element to the end of an array.
// Create an array $a = new array("apple", "orange"); // Add an element to the end of the array using the array_push() function array_push($a, "banana") // Alternative way of adding an element to the end of an array $a[] = "pineapple"; // Adding an element with a key $a['fruit'] = "watermelon";
How to remove elements from an array in PHP
// Create an array $a = new array("orange", "apple", "pineapple"); // Remove the apple from the middle of the array unset($a[1]); // Create an associative array $a = new array("dogs" => 4, "cats" => 9, "birds" =>2); // Remove the birds from the array unset($a['birds']);
An XPath quick reference
This is a very brief quick reference for those of you who know what XPath is, but don’t use it often enough to have it ingrained in your heads, like myself.
XPath Examples
| //person | Returns a NodeSet containing ALL XML tags in the document with the name ‘person’, no matter where they are in the document. |
| //person[@firstname='patrick'] | Returns a NodeSet containing ALL XML tags in the document with the name ‘person’ and an attribute ‘firstname’ with a value of ‘patrick’, no matter where they are in the document. |
| /person/@firstname | Returns the value of the attribute ‘firstname’ for all direct children with a name of ‘person’. |
| /animal[contains(string(),'rabbit')] | Returns all ‘animal’ tags that have a string value containing the string ‘rabbit’. |
I highly recommend a site out there that allows you to test your XPath’s right on the site: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
Another method for checking whether a URL exists
In a previous article we demonstrated a simple method for discovering whether or not a URL exists. The following code accomplishes the same thing, but offers a little more control.
/* Brendan Warkentin */ /* urlexists($url, $port = 80, $codes = array(200), $ssl = false) * * @Description: * Determine whether a url really exists. * * @Parameters: * $url:string - The fully-qualified url to check. * $port:int - The port to connect to. * $codes:array - The return codes to look for. * $ssl:bool - Whether we should use an encrypted connection. * * @Return: * Bool. True if the url exists, false otherwise. * * @Misc * By default this only checks for a return code of 200(OK). Some sites * do redirecting, and usually return 302. If you would like it to check * that you will have to manually specify the codes to check. */ function urlexists($url, $port = 80, $codes = array(200), $ssl = false) { $host = parse_url($url, PHP_URL_HOST); $path = parse_url($url, PHP_URL_PATH); $path = (strstr($path, "/") === 0 ? $path : "/"); $req = sprintf("GET %s HTTP/1.0rnHost: %srnrn", $path, $host); $sock = false; $found = false; if ($ssl) $sock = fsockopen("ssl://".$host, $port); else $sock = fsockopen($host, $port); if ($sock != false) { fputs($sock, $req); $ret = fgets($sock); fclose($sock); foreach ($codes as $i) if (strstr($ret, (string) $i) !== false) $found = true; return $found; } return false; }
Allowing users to login using HTML and PHP
A form is an area of a web page where your website’s visitors can enter information and submit it. They might fill out a contact form, or use a small form to login to your system. They come in handy and in many cases are a necessity. In this tutorial we will kill two birds with one stone and show you how to make a login form (I promised a login tutorial in a previous tutorial).
First, the basics. There are several different types of fields or tags that are commonly used in a form. One type, which we won’t cover here, is the input tag with a type of file. But you can learn about it here.
- <input>
- <textarea>
- <select>
An input tag can have different types, such as:
- text
- password
- hidden
- file
- submit
- checkbox
- radio
Every form opens and closes with a form tag.
<form> <!-- the form elements go here --> </form>
We won’t go into detail on each type of form element. Rather we will focus on three types of inputs that we will use in our login example: text, password, and submit.
Start by creating a new file called login.php. Copy and paste the following code inside.
<form action="login.php" method="post"> <label>Username</label> <input type="text" name="username" value="" /> <br /> <label>Password</label> <input type="password" name="password" value="" /> <br /> <input type="submit" name="submit" value="Login" /> </form>
This is our form. It contains a text field a password field and a submit button that, when clicked, sends the data off to be validated. The form tag has two parts: action and method. Our action is the page we want to send the form data to, and the method is our method of sending the information. Sending via the post method “hides” the information, whereas sending via get will pass the data as a querystring, visible in the URL. In this example we use post because we don’t want to show the user’s credentials in the URL.
The next part is to capture the data that has been posted, and then we’ll validate it. Copy and paste the following PHP code above your HTML form. Your file should now look like this:
<?php // Check for user login if(isset($_POST['submit'])){ // User is attempting login // Verify the credentials are correct if($_POST['username'] == "apple" && $_POST['password'] == "dumpling"){ // The username and password provided are correct! echo ("You have logged in successfully!"); exit; } else { echo ("Woops! You entered the wrong username and password."); } } ?> <form action="login.php" method="post"> <label>Username</label> <input type="text" name="username" value="" /> <br /> <label>Password</label> <input type="password" name="password" value="" /> <br /> <input type="submit" name="submit" value="Login" /> </form>
Run the page and try it out! Entering anything but a combination of “apple” and “dumpling” will result in failure. But entering that combination correctly will give you a thumbs up.
At this point you might want to store the user’s id in a session, and as the user moves from page to page you can check for the id. If it exists then you know they have logged in and can access secure parts of your site. You can learn about sessions here.
Sending emails with PHP
Sending an email is easy using PHP. Create a new file, copy and paste this code, and give it a spin!
<?php // Prepare the data $to = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com'."rn". 'Reply-To: webmaster@example.com'."rn". 'X-Mailer: PHP/'.phpversion(); // Send the email mail($to, $subject, $message, $headers); ?>
Checking whether a URL exists in PHP
There is no built in function to check if a particular URL exists, but you can easily write one. The following is a simple method, or you can try this one which takes more code, but allows more control.
Copy and paste the following code into a new file and try it out!
<?php function doesUrlExist($url) { if (!empty($url) && @fopen($url, "r")) { // The URL is not empty and we can read it, so return true return true; } // The URL was either empty, or not found, so return false. return false; } // Test a bad URL $url = "http://www.somedomain.com/index.html"; echo (doesUrlExist($url) ? "The URL at $url exists!" : "The URL at $url could not be found!"); echo ("<br />"); // Test a good URL $url = "http://www.aratide.com"; echo (doesUrlExist($url) ? "The URL at $url exists!" : "The URL at $url could not be found!"); ?>