How to convert a string to a timestamp and then back to a string with PHP
1 $r = date_parse("8:16:12 01.02.2008"); 2 $d = mktime($r['hour'], $r['minute'], $r['second'], $r['month'], $r['day'], $r['year']); 3 echo date("H:i:s d.m.Y", $d);
Prints out the following:
1 8:16:12 01.02.2008
How to set a cookie, remove a cookie and get the value of a cookie in PHP
PHP cookie management is a good example of how incredibly badly designed PHP is:
Set a cookie that expires when browser is closed
Note that you most probably want to set the path, which we do here:
1 $value = 0; 2 $expires = 0; 3 setcookie('cookie_name', $value, $expires, '/');
Remove cookie
1 setcookie ('cookie_name', FALSE, time()-10000);
Get cookie value
1 $_COOKIE['cookie_name']
How to debug memory allocation problems in PHP with Xdebug
Xdebug is a good tool for finding the root cause of memory allocation problems such as the one shown here:
1 Fatal error: Allowed memory size of X bytes exhausted (tried to allocate X bytes)
First install Xdebug by following the Xdebug installation instructions.
Next surround the code you suspect is causing the problem with the following function calls:
1 xdebug_start_trace('/tmp/mytrace'); 2 ... 3 Bad bad PHP code 4 ... 5 xdebug_stop_trace();
Combining CSS and JavaScript files with PHP to reduce page load time
This is a very simple utility class that I created which combines multiple files into one—in contrast to all other PHP scripts I’ve found elsewhere, which all work badly and are a million lines long, this one is simple to understand and maintain:
1 <?php 2 class Files 3 { 4 private static function process($files, $output, $base_dir = '') 5 { 6 $contents = ''; 7 8 # If this is a string then it's a search pattern 9 if(is_string($files)) 10 { 11 $files = glob($files); 12 } 13 14 foreach ($files as $file) 15 { 16 $contents .= file_get_contents($base_dir.$file) . "\n\n"; 17 } 18 19 # TODO locking 20 if ($fp = fopen($output, 'wb')) 21 { 22 fwrite($fp, $contents); 23 fclose($fp); 24 } 25 26 return $contents; 27 } 28 29 # 30 # Combine all CSS files in the css directory: 31 # 32 # echo Files::combine("css/*.css", "css/all.css"); 33 # 34 # Combine only specified files in the given order: 35 # 36 # echo Files::combine(array("css/core.css", "css/default.css"), "css/all.css"); 37 # 38 # 39 static function combine($files, $output_filename, $base_dir = '') 40 { 41 # Combine the files 42 if(!file_exists($output_filename)) 43 { 44 self::process($files, $output_filename, $base_dir); 45 } 46 } 47 } 48 ?>
The call to Files::combine should go in a file that is called on each request. On the first request to this file, the files are combined into one, on subsequent requests nothing is done, the only overhead is a call to file_exists.
Ideally the name of the output filename should contain a version number, so that an updated CSS file is not taken from the browser cache. This can easily be supported by reading the build number from somewhere and appending it to the output filename:
1 Files::combine("css/*.css", "css/all-v$version.css");
Now all you have to do is add this to your HTML :
1 <link rel="stylesheet" type="text/css" href="/css/all-v<?php echo $version ?>.css" media="screen" />
This also works for JavaScript files. Note that I don’t make an effort to minify anything as GZIP usually does a great job at minimizing bandwidth costs.
PHP exception and error handling with register_shutdown_function and set_exception_handler
PHP has the crappiest error handling I’ve ever seen. The default behavior is to show all error messages to the user. If you disable this then you get a blank screen instead. The trick is to register an error handler with register_shutdown_function, which is then called if for example memory is exhausted. You could perhaps also use an ErrorDocument 500, but that didn’t work for me.
Here’s the code I’ve used to handle both application exceptions and errors, such as memory limit exceeded. The trick is to have a global variable that indicates whether the script was run successfully or not. Add your code here: “Insert your buggy code here”.
1 $no_errors_detected = false; 2 3 class DispatchErrors 4 { 5 static function handleException($exception) 6 { 7 Logging::error($message); 8 9 header( 'Location: /error500.html' ); 10 } 11 12 static function handleShutdown() 13 { 14 global $no_errors_detected; 15 16 if (!$no_errors_detected) 17 { 18 header( 'Location: /error500.html' ); 19 } 20 } 21 } 22 23 register_shutdown_function(array('DispatchErrors', 'handleShutdown')); 24 set_exception_handler(array('DispatchErrors', 'handleException')); 25 26 # handleShutdown will be called 27 #range(0, 10000000000000000000); 28 29 # handleException will be called 30 #throw new Exception("abcd"); 31 32 # Insert your buggy code here 33 34 $no_errors_detected = true;