Archive for the ‘php’ Category

Ultra Simple PHP Profiling – Hack it #8

Tuesday, November 9th, 2010

We wanted to profile a few PHP scripts, so we tried xdebug, but there were a few issues:

  • Not suitable for a production server
  • Difficult to turn on/off for specific scripts and requests
  • Difficult to profile MySQL queries, without also attracting a mass of other data

xdebug is better for offline application profiling.

If you just want to track down a bottleneck, or see what your script is spending all its time doing, here’s a simple alternative.

To profile your SQL, replace mysql_query with mysql_queryx.

This generates a CSV file at /tmp/profile.1 for easy analysis.

Now create the file profile.php:

Too easy!

To stop profiling a page, set $profile = false.

If you’re concerned about performance, do something like $profile = rand(0, 100) > 99.

Remember me with PHP – hack it #6

Monday, March 15th, 2010

PHP persistent sessions
“Remember me” functionality was recently implemented on the Supernifty login screens. The PHP documentation is surprisingly non-obvious so here’s how to do it.

If you’re already using the $_SESSION variable, the default is for this variable to live only for as long as the browser. Once the user closes the browser, the cookie will be deleted, and they’ll be logged out.

To remember a user across browser sessions, here’s what needs to be done.

Tell the browser to remember the session

You do this with the line:

setcookie( session_name(), session_id(), time() + 86400*30 );

This overwrites the default session cookie, with a cookie that will persist on the user’s browser for one month.

Note that since cookies are set in the headers sent to the browser, this needs to be done before writing any content to the browser.

With HTML like

<input type="checkbox" name="remember" value="remember"/>

You could have a handler like:

$remember = $_POST['remember'];
if ( isset( $remember ) && $remember == 'remember' ) {
setcookie( session_name(), session_id(), time() + 86400*30 );
}

Tell the server to remember the session

Bizarrely, PHP’s default session time is something ridiculous like 24 minutes.

To tell the server to remember the session for longer, you need to set some PHP environment variables, like so:

ini_set("session.gc_maxlifetime","2592000"); // 24*30 hours
session_set_cookie_params( 86400*30 );
session_start();

More details about PHP’s session lifetime

With these two pieces in place, you can now implement a “remember me” checkbox on your login screen with PHP, while continuing to use the $_SESSION variable.