Hints and tips on php

These are some helpful hints on various topics.


PHP's safe mode automatically applies escapeshellargs to the argument of exec()

When safe mode is on you may have problems with function exec(). As PHP applies automatcally escapeshellargs() this makes exec($cmd) work like exec(escapeshellargs($cmd)). If you application already escapes the command, you will get double escaped thus invalid command. For example:

exec('convert  -resize ">10x10"  img.jpg') - fails, because command that is executed is convert  -resize \">10x10\"  img.jpg
exec('convert  -resize >10x10 img.jpg') - normal execution of command convert  -resize \>10x10 img.jpg

Also you cannot redirect program's stdin, stdout, stderror, because ">" and "<" are escaped:

exec('who > file.txt') - fails, trying to execute who \> file.txt

PHP converts dots in request variables names into underscores

There is a specialty in HTTP variables handling in PHP. If variable name contains dot (.) then иt will be converted to underscore(_). For example if you type http://doamin.com/script.php?var.1=abc:

echo $_GET['var.1'] - does nothing
echo $_GET['var_1'] - prints "abc" on the screen

Dash in regular explession

There is something you should know if you want to use a dash in ereg() matching. For example if you want to check if a string contains only letters, digits, dots and dashes, you should put the dash at the end of the list. Also unlike the dot don't put a backslash before it:
ereg('^[a-zA-Z0-9\.-]+$', $string)

HTTP headers for disabling browser cache

    header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
    header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
    header( 'Cache-Control: no-store, no-cache, must-revalidate' );
    header( 'Cache-Control: post-check=0, pre-check=0', false );
    header( 'Pragma: no-cache' );

Regex for getting the content of given span by id or class

Here's a regex that extracts content of span with given id or class from an HTML text contained in $data variable:

$regex = '/\<span\s*class=[\'"]?classname[\'"]?\s*>([^\<]+)\<\/span\>/imu';
preg_match_all($regex, $data, $matches, PREG_PATTERN_ORDER);

$regex = '/\<span\s*id=[\'"]?spanid[\'"]?\s*>([^\<]+)\<\/span\>/imu';
preg_match_all($regex, $data, $matches, PREG_PATTERN_ORDER);


PHP fragment for getting file extension

To get the file extesion in one line using PHP use similar construct:

$ext = end(explode(".", $filename));

Here $filename can be just the file name, absolute or relative path.