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


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


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


Next Page »