Posts tagged "PHP"

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


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']);


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;
}


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!");
 
?>


Working with session variables in PHP

Let’s say you are creating a website where users need to login. How do you track a user’s id from page to page, or even verify that a user is logged in when they should be? You can use the global $_SESSION variable!

The $_SESSION is an array where you can store your variable and objects. Try the following example where we store a simple integer called user_id.

Create a file on your web server called write_session.php.

<?php
 
// Start the session.  This function call is required for us to work with the global $_SESSION variable
session_start();
 
// Assign a new key of 'user_id' to the value 5
$_SESSION['user_id'] = 5;
 
?>
<a href="read_session.php">Read Session</a>

Now we can access the user_id on other pages in our site! Make another page called read_session.php with the following code in it.

<?php
 
// Start the session.  This function call is required for us to work with the global $_SESSION variable
session_start();
 
// Output the user_id value
echo ("My user id is ".$_SESSION['user_id']."!");
 
?>

Execute the write_session.php page and you should see

My user id is 5!

If you are using your session to store a logged in user’s information it is a good idea to give them a log out option.

Create another file called logout.php

<?php
 
// Required to use the global $_SESSION variable
session_start();
 
// Destroy this session
session_destroy();
 
echo ("Your session has been destroyed!");
?>

In a later tutorial I will walk you through a complete user authentication process, from login to logout.


Next Page »