There was some discussion yesterday about a PHP trick (for want of a better word) for having HTML form fields automatically converted to arrays. From my understanding so far, this seems pretty typical of general PHP philosophy – specific little tools and techniques are dropped in all over the place to make those common procedures that you perform a hundred times in every web app just that little bit easier. I think it’s great – it makes rapid web app development very easy for beginners and enables seasoned developers to focus on the logic rather than the nuts and bolts. PHP really is a tool built for the job.
So, my question is this. What is your favourite PHP trick? What’s the one little tip you’ve picked up along the way that has saved you time or made development easier?



Comments
Happy New Year!
Not so much a PHP trick, but something that seems more prevalent in the PHP / Perl communities than any other, is the predominance of the ’free code’. This has saved me so much time. Especially when someone wants a ’standard’ site that something like Smarty templates or PHP-nuke and all the other variants will cover very quickly.
This has saved me no end of time...
Cheers!
Paul
I also quite like parse_url($REQUEST_URI).
When form checking, iterate thru your $_POST/$_GET arrays with a foreach loop, checking against an array you built earlier (!!) of un-required fields.
If you hit one of those array elements use the ”continue” keyword within the loop and go to the next $_POST element..
My 2p’s worth..
There is so much useful and (mostly) throughout code there, so you don’t have to reinvent the wheel a thousand times. Packages I use a lot: HTML_Table, HTML_QuickForm and Log. There are really a lot of useful packages there, and I have a feeling that far from all PHP developers know how useful it is/can be.
There may, of course, be something like this in PEAR, but I’ve never been able to wade through the godawful ”documentation” (always a weak spot with PHP) to find out.
Mike
The use of ’@’ to hide error messages. When combined with the error handling functions, it becomes sooooooo powerful!
Consider:
function errorHandler($errno, $errstr, $errfile, $errline) {
switch($errno){
case E_USER_ERROR:
// Send email to admin regarding failing site.
error_log($errstr, 1, ’admin@foobar.com’);
break;
case E_USER_WARNING:
// Log to custom log file for interrogation.
error_log($errstr, 3, ’../logs/warnings.log’);
break;
case E_USER_WARNING:
// Log to PHP’s system logger.
error_log($errstr, 0);
break;
}
}
$errors = set_error_handler(’errorHandler’);
$connect = @mysql_connect(HOST, UN, PW) or trigger_error(’Database connection unavailable.’, E_USER_ERROR);
Wonderful! Now, if my db server decides to visit the great rubbish tip in the sky i’ll get an email letting me know what happened. Otherwise, it gets logged somewhere.
parse_ini_file() has made my life so much easier, because I can now package an application, email it to a client, and they can configure it themselves! ini files are extreamily easy to manipulate, and for simple this=that lists is an easy winner over XML which can scare some clients.
Then there’s another quick tip: use a comma rather than a dot to concatenate echo’d strings. Echo acts like a function, in that it will accept multiple parameters. Passing multiple parameters is faster than joining strings together before outputting them as a whole. So:
echo ’This’, $is, ’a’, TEST; // String, Variable, String, Constant;
... is faster (and less work) than:
echo ’This’ . $is . ’a’ . TEST;
The built-in directory class is also a wonderful piece of kit. Lets get my current directory, shall we?
$d = dir(’.’);
while ( ( $entry = $d->read() ) !== false ) {
switch ( filetype( $entry ) ) {
case ’dir’:
$filesys[’directories’][] = $entry;
break;
case ’file’:
$filesys[’files’][] = $entry;
break;
}
}
$d->close();
print_r($filesys);
I’m finding more all the time. Keep looking, and you will to!
TURN OFF register globals and magic quotes. They encourage sloppy programming and cause more problems than they solve.
I use this a lot:
extract( mysql_fetch_assoc( $result ) );Or, using PEAR_DB,
extract( $result->fetchRow( DB_FETCHMODE_ASSOC ) );When taking in data from a form, remember that you can set the name of an input to something similar to: arrayname[assoc_index]; This allows you to pass in arrays which can be much easier to deal with in certain situations.
In PHP4, use PEAR as a base for building your own classes. The PEAR error framework is about as good as error handling gets in PHP4. When using PHP5 use exceptions.
register_shutdown_function is NOT a substitude for a class deconstructor. If you think it exists for class deconstruction, you are wrong. In PHP4 there are no desconstructors for a class.
Use classes for your libraries. By making static calls to class methods, you can keep your function namespace cleaner.
Understand the difference between include, require, include_once, and require_once. Use accordingly.
When you need to sort something, don’t write your own sort algorithm. Using usort with a supplied function is plenty fast enough since the actual sorting doesn’t have to be interpreted, just the comparison function.
HEREDOC notation is a good middle-ground between raw HTML and echo when outputting HTML with variables intermixed; It is often much easier than sprinkling open and close tags throughout raw HTML, echoing double-quited strings but escaping all the double-quotes inside HTML tags, or doing lots of string concatination.
If you use echo and/or print statements for output, using single quotes plus concatenation will be faster than double quotes. It makes little difference for small scripts, but when doing very large amounts of output there will be a small but noticable boost in speed.
If you have control over your PHP build ( ie, you own your web server ), recompile your PHP build to remove all the junk you won’t ever need. It will use less resources and you will be protected from exploits in those extras that you removed.
Consider this:
$test = $_POST(‘username’);
trim($test);
stripslashes($test);
could be used like this:
$test = trim(stripslashes($_POST(‘username’)));
I certianly do not know all of the functions, constants, syntax and general commands that you can do this with but I’ve not encountered a situation that I could not “stack” in. Be sure to be mindful of your parenthese though!
ini_set(‘session.cache_limiter’, ‘private’);
I like the Dynamic Variable Variable:
${“variable_name”} = “”;
for forms it saves a load of time
Evaluate shorthand:
$something = (isTrueFalse) ? "This is true" : "This is false";so
$myName = ($_SESSION['name']) ? "Jaci" : "Unknown!";When listing files:
instead of
IF match ".png" OR match ".jpg" OR...etc.$files = glob ("$directory/{ *.jpg, *.png, *.gif }", GLOB_BRACE);$files will be an array of everything in $directory with the given extensions. Ahem…asterisk.asterisk will return all files. I’m not good with textile, sorry.
regex:
I hate it and love it.
preg_match_all('/(#[0-9A-Fa-f]{6})|(#[0-9A-Fa-f]{3})/', $file, $colors);Does, I think, match all the #RRGGBB or #RGB values in $file and return the matches in $colors.
Header function:
The above is being used to replace colours with variables in a php file that acts like a css file, using the
header()function. I also use this with GD Image – a wonderful timesaver for me. It basically lets you code images. You could use a blank button image and overlay text with something like this:img src=gdfile.php?text=home page...I haven’t done header or button graphics with a regular graphic program much since I discovered this.
Thanks to all the other authors for their tips.