php

Output debug information to file

Snippet

Use file_put_contents to dump debug information to a file.

file_put_contents('/tmp/xxx.txt', print_r($match, TRUE) . "\n", FILE_APPEND);
file_put_contents('/tmp/xxx.txt', "wysiwyg is ${wysiwyg}\n", FILE_APPEND);
 
/* 
tail -f /tmp/xxx.txt # watch the results
*/

Print month given integer

Snippet

Sometimes you want to print a month without knowing the complete date (say, given 7 from the URL, you want July).

<?php 
 
print date('F', mktime(0, 0, 0, $month, 1));
 
// mktime(hour, minute, second, month, day, year)
// you don't care about the year.
 
$month = 6;
print date('F', mktime(0, 0, 0, $month, 1));
/*
 * outputs
 * June
 * for 6/1 at 12:00:00 am midnight
*/

YYYY-MM-DD hh:mm:ss to unixtime

Snippet

Convert a MYSQL datetime string of the format "YYYY-MM-DD hh:mm:ss" into a unixtime integer in PHP (if epoch, that is: date > 1970-01-01).

$birthday = '1980-06-01 00:00:00';
$birthdayunx = mktime(0, 0, 0, substr($birthday, 5, 2), substr($birthday, 8, 2), substr($birthday, 0, 4));
 
// the next day
$nextdayunx = mktime(0, 0, 0, substr($birthday, 5, 2), (substr($birthday, 8, 2) + 1), substr($birthday, 0, 4));
$nextdaystr = strftime("Y-m-d H:i:s", $nextdayunx);
 
/* 
 
FROM:
 
int mktime  ([ int $hour = date("H")  [, int $minute = date("i")  [, int $second = date("s")  [, int $month = date("n")  [, int $day = date("j")  [, int $year = date("Y")  [, int $is_dst = -1  ]]]]]]] )
 
If you can, use mysql date functions:
 
SELECT duedate, DATE_ADD(FROM_TIMESTAMP(duedate), INTERVAL 1 DAY) AS nextday FROM ...;
 
*/

PHP server name from the command line

Snippet

Can't use $_SERVER['SERVER_NAME'] in command line scripts for the host name. Use php_uname()

echo php_uname("n");

Print evaluated query string using ADODB/PHP

Snippet

After a parameterized querystring has been evaluated, but before the query has been run, print out the query string, using ADODB PHP library.

<?php
 
/*
 * include the ADODB library
 */
include('adodb.inc.php');
 
/*
 * Make a new connection to DB
 */
$mydb = &ADONewConnection('access');     
$mydb->PConnect('northwind');  
 
/*
 * filter input
 */
$shipto = $conn->qstr("John's Old Shoppe");
 
/*
 * generate SQL
 */
$sql = "insert into orders (customerID,EmployeeID,OrderDate,ShipName) ";
$sql .= "values ('ANATR',2,".$mydb->FormatDate(time()).",?)";
 
/*
 *
 *
 * PRINT THE SQL BEFORE EXECUTING THE QUERY
 *
 *
 */
$mydb->debug = true;
 
if ($mydb->Execute($sql, $shipto) === false) print 'error inserting';
 
?>

PHP empty in javascript

Snippet

Equivalent of PHP's empty in javascript

function empty (mixed_var) {
 // version: 909.322
 // discuss at: http://phpjs.org/functions/empty
 var key;
 if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || mixed_var === undefined ) {
  return true;
 }
 if (typeof mixed_var == 'object') {
  for (key in mixed_var) {
   return false;
  }
  return true;
 }
 return false;
}

Run PHP script only on command line

Snippet

In case a PHP script should be run only on the command line, and not in a browser

if (php_sapi_name() != 'cli') {
  /* do any clean up or logging here */
  exit();
}

simplexml to array

Snippet

Convert a SimpleXML object into a nested array

/**                                                                                                                                                                                  
 * @see http://theserverpages.com/php/manual/en/ref.simplexml.php                                                                                                                    
 */
function simplexml_to_array($xml) {
  if (get_class($xml) == 'SimpleXMLElement') {
    $attributes = $xml->attributes();
    foreach($attributes as $k=>$v) {
      if ($v) $a[$k] = (string) $v;
    }
    $x = $xml;
    $xml = get_object_vars($xml);
  }
  if (is_array($xml)) {
    if (count($xml) == 0) return (string) $x; // for CDATA                                                                                                                           
    foreach($xml as $key=>$value) {
      $r[$key] = simplexml_to_array($value);
    }
    if (isset($a)) $r['@'] = $a;    // Attributes                                                                                                                                    
    return $r;
  }
  return (string) $xml;
}

Enable PHP ADODB handling

Snippet

By default, PHP's ADODB library will not give full error messages on pconnect, or route to an error handler. The error handler has to be enabled.

<?php
 
// pass any error messages triggered to error handler
error_reporting(E_ALL); 
 
include('adodb-errorhandler.inc.php');
include('adodb.inc.php');
 
// suppress error messages for the connection
ini_set("display_errors", "0");
try {
  $mydb = &ADONewConnection('mysql');
  $mydb->PConnect('dbhost','dbuser','dbpass','dbname');
} catch (exception $e) {
  // unable to connect to the DB (usually too many connections), redirect away                                                                                            
  header('Location: /error.html');
  exit();
}

Canadian provinces as PHP array

Snippet

List of Canadian provinces / states as a PHP array.

$states["CA"] = array(
  "BC" => "British Columbia",
  "ON" => "Ontario",
  "NF" => "Newfoundland",
  "NS" => "Nova Scotia",
  "PE" => "Prince Edward Island",
  "NB" => "New Brunswick",
  "QC" => "Quebec",
  "MB" => "Manitoba",
  "SK" => "Saskatchewan",
  "AB" => "Alberta",
  "NT" => "Northwest Territories",
  "NU" => "Nunavut",
  "YT" => "Yukon Territory"
); 

Pages