All in the <head>

– Ponderings & code by Drew McLellan –

– Live from The Internets since 2003 –

About

Favourite PHP Tricks

2 January 2004

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?

- Drew McLellan

Comments

  1. § Paul: Hey Drew,
    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
  2. § Harold Bakker: Switch statements have got to be one of the best features for me. Of course they’re not unique to PHP but they save loads of time.

    I also quite like parse_url($REQUEST_URI).
  3. § Russ: Hey there:

    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..
  4. § Eivind Lie Nitter: I think the discovery of PEAR has meant the most to me PHP-wise.

    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.
  5. § Eric TF Bat: My favourite trick came from an idea on Joel Spolsky’s website, about simple database table objects in Visual Basic. I wrote a PHP class that actually generates a class definition and then eval()s it. So I can basically say ”EntityType([class-name], [sql-table-name], array([field-name] => new [fieldtype](...), ...))” and voila, I have a type definition for ”class-name” that has properties, Edit(), Insert(), Exists() and so on. Really easy to use, has debug code built in, and makes SQL database usage a breeze.

    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.
  6. § Mike Ridyard: I’m looking for a trick, not sure if it’s been done with output buffering - build your page header, add content from database, add footer - easy. but how to skim keywords out of the content and add them back into the page header without a) using large arrays or b) reading the database content twice. It MUST be fairly simple, but I’d welcome ideas/tips.

    Mike
  7. § Dysfunksional.Monkey: Ooh... PHP tricks! Let me think...

    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!
  8. § KermodeBear: None of these really fall into the catagory of ‘trick’, since PHP is not supposed to be a trick language, but still, some words of advice:

    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.
  9. § Ryan: This isn’t so much a trick as it is “tidy” codeing. While it isn’t a format proprietary to PHP, being able to “stack” syntax is most useful for easy reading of source code.

    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!
  10. § Ivan Sommers: I just found this site. It’s a free-content wiki for open-source code, including PHP. Wow – why didn’t I think of that?
  11. § Ivan Sommers: Sorry. The URL is http://wikicode.frihost.net or just click my name.
  12. § TheGroover: You know those annoying IE pages, usually when you hit the back button, that tell you your page can’t be displayed unless you hit refresh to repost data??? Put this line before you send your header and WHAMO no more annoying IE refresh page. WARNING: this is only good for things like “paged” search results or pages without sessions started.

    ini_set(‘session.cache_limiter’, ‘private’);
  13. § shihab: mail me 4 new php websites
  14. § Lance Snyder:

    I like the Dynamic Variable Variable:

    ${“variable_name”} = “”;

    for forms it saves a load of time

  15. § Jaci:

    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.

Photographs

Work With Me

edgeofmyseat.com logo

At edgeofmyseat.com we build custom content management systems, ecommerce solutions and develop web apps.

Recent Links

Affiliation

  • Web Standards Project
  • Britpack
  • 24 ways

About Drew McLellan

Photo of Drew McLellan

Drew McLellan has been hacking on the web since around 1996 following an unfortunate incident with a margarine tub. Since then he’s spread himself between both front- and back-end development projects, and now is Director and Senior Web Developer at edgeofmyseat.com in Maidenhead, UK (GEO: 51.5217, -0.7177). Prior to this, Drew was a Web Developer for Yahoo!, and before that primarily worked as a technical lead within design and branding agencies for clients such as Nissan, Goodyear Dunlop, Siemens/Bosch, Cadburys, ICI Dulux and Virgin.net. Somewhere along the way, Drew managed to get himself embroiled with Dreamweaver and was made an early Macromedia Evangelist for that product. This lead to book deals, public appearances, fame, glory, and his eventual downfall.

Picking himself up again, Drew is now a strong advocate for best practises, and stood as Group Lead for The Web Standards Project 2006-08. He has had articles published by A List Apart, Adobe, and O’Reilly Media’s XML.com, mostly due to mistaken identity. Drew is a proponent of the lower-case semantic web, and is currently expending energies in the direction of the microformats movement, with particular interests in making parsers an off-the-shelf commodity and developing simple UI conventions. He writes here at all in the head and, with a little help from his friends, at 24 ways.