PHP Web Programming


Bit Operations in PHP (& C)

number |= 1 << x;          // set bit x
number &= ~(1 << x);       // clear bit x
number ^= 1 << x;          // toggle bit x
bit = number & (1 << x);   // put the value of bit x into the variable bit.

Where Am I

Find path of where script is being executed. This works whether script is run from PHP or PHP-CLI. Some other methods do not work in both cases.

// returns current path and path of parent directory
function whereami(&$path,&$pathup)
{
    $exploded = explode('/',$_SERVER['SCRIPT_FILENAME']);   
    $count = count($exploded);
    $path = "";       // path to file currently executing
    $pathup = "";     // path to see one directory up from where I'm at now 
    for ($i=0;$i < $count;$i++)
    {
        if ($i< $count-1)
        $path .= $exploded[$i] . "/";

    if ($i< $count-2)
        $pathup .= $exploded[$i] . "/";             
    }   
    return 1;
}

Path to root

Find path to webroot. This is useful when you include a function in multiple files throughout your site, and you need relative path information so you can reference other files.

if (!$root)
{
  $dir_depth = count(split("/", $_SERVER['PHP_SELF']))-2;
  for ($i=0;$i < $dir_depth;$i++)
    $root .= '../';
}

Get Client IP Address

In case of a clustered setup, or some webservers such as Lighttpd, you need to work a little harder to get the client IP address as standard methods don't work.

/**
* Returns the client IP address. In case of a clustered (load balancer)
* setup, this returns the real client IP by looking at the
* X-Cluster-Client-IP header.
*/
public function getClientIp() {
    $headers = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_CLUSTER_CLIENT_IP',
                     'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED',
                     'HTTP_FORWARDED', 'HTTP_VIA', 'HTTP_X_COMING_FROM',
                     'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM',
                     'REMOTE_ADDR');
    foreach ($headers as $header) {
        if (isset($_SERVER[$header])) {
            return $_SERVER[$header];
        }
    }
}

Compress CSS files into your HTML document

Reinhold Weber method. Also uses regular expression to strip out CSS comments

<?php
  header('Content-type: text/css');
  ob_start("compress");
  function compress($buffer) {
    /* remove comments */
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    /* remove tabs, spaces, newlines, etc. */
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
  }

  /* your css files */
  include('master.css');
  include('typography.css');
  include('grid.css');
  include('print.css');
  include('handheld.css');

  ob_end_flush();
?>

Write Error Log File

Error handler function. Writes to an error log file, associated with php script that called it

function customError($error_level,$error_message,$error_file,$error_line,$error_context) 
{
  // to use, 
  // set_error_handler("customError"); 

  $whoami = $_SERVER['PHP_SELF'];
  if (!$whoami)
    $whoami = __FILE__;


  // get name of php script that generated error, with .php and path stripped off
  $error_script =  basename($whoami, ".php");

  echo "<b>Error:</b> $error_message";
  $myFile = $error_script . "_error.txt";
  $fh = fopen($myFile, 'a') or die("can't open file");
  fwrite($fh, date("F j H:i:s",time()) . ': [' . $error_script . '.php   Line-' . $error_line . '] ' . ' ' . $error_message . "\n" );
  fclose($fh);
  die();  // stop the script.
}

Write Debug Info to File

Dump debug info to text file

function debug_info_to_text($debug_info)
{ 
  // to use, 
  // debug_info_to_text('Here I am!');

  $whoami = $_SERVER['PHP_SELF'];
  if (!$whoami)
    $whoami = __FILE__;

  // get name of php script that generated dump request, with .php and path stripped off
  $dump_script =  basename($whoami, ".php");

  // write debugging text file
  $myFile = $dump_script . "_debug.txt";
  $fh = fopen($myFile, 'a') or die("can't open file");
  fwrite($fh, "\n" . date("F j H:i:s",time()) . "  " .  getClientIp() . "  " . $debug_info);
  fclose($fh);
}

Write Parameters to file

Dump parameters to text file. Useful when debugging or even just logging Paypal scripts.

function dump_params_to_text()
{

  $whoami = $_SERVER['PHP_SELF'];
  if (!$whoami)
    $whoami = __FILE__;

  // get name of php script that generated dump request, with .php and path stripped off
  $dump_script =  basename($whoami, ".php");

  // dump it all
  $myFile = $dump_script . "_params.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");
  if ($_GET)
    fwrite($fh, '$_GET ' . print_r($_GET, true) . "\n");     

  if ($_POST)
    fwrite($fh, '$_POST ' . print_r($_POST, true) . "\n");

  if ($_FILES)
    fwrite($fh, '$_FILES ' . print_r($_FILES, true) . "\n");

  fclose($fh);
}