php

How to print all HTTP headers with PHP

Tagged php, http, headers, request  Languages php
<ul>
 <?php
   foreach($_SERVER as $h=>$v)
     if(ereg('HTTP_(.+)',$h,$hp))
       echo "<li>$h = $v</li>\n";
   header('Content-type: text/html');
  ?>
</ul>

How to format number of seconds as duration with PHP

Tagged php, duration, format, time, seconds  Languages php

A very sophisticated algorithm that will display the length of, for example, a video as 12:01:30.

function duration($seconds_count)
    {
        $delimiter  = ':';
        $seconds = $seconds_count % 60;
        $minutes = floor($seconds_count/60);
        $hours   = floor($seconds_count/3600);

        $seconds = str_pad($seconds, 2, "0", STR_PAD_LEFT);
        $minutes = str_pad($minutes, 2, "0", STR_PAD_LEFT).$delimiter;

        if($hours > 0)
        {
            $hours = str_pad($hours, 2, "0", STR_PAD_LEFT).$delimiter;
        }
        else
        {
            $hours = '';
        }

        return "$hours$minutes$seconds";
    }

How to generate a pronouncable password with PHP

Tagged password, generate, random, php  Languages php

This is a slight modification of a script I found at PHPFAQ:

class Password
{
    static function generate($length)
    {
        srand((double)microtime()*1000000);

        $vowels = array("a", "e", "i", "o", "u");
        $cons = array("b", "c", "d", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "u", "v", "w", "tr",
        "cr", "br", "fr", "th", "dr", "ch", "ph", "wr", "st", "sp", "sw", "pr", "sl", "cl"); 

        $num_vowels = count($vowels);
        $num_cons = count($cons);

        $password = '';
        
        for($i = 0; $i < $length; $i++)
        {
            $password .= $cons[rand(0, $num_cons - 1)] . $vowels[rand(0, $num_vowels - 1)];
        }

        return substr($password, 0, $length);
    }
}

To use it try this code:

require 'password.php'

echo Password.generate(10);

It will spit out passwords that are semi-pronouncable.

How to execute a CakePHP controller's action from a cron job

Tagged cakephp, cron, job  Languages php

First copy webroot/index.php to webroot/cron_scheduler.php. Replace everything below require CORE_PATH . 'cake' . DS . 'bootstrap.php'; with the following code:

#
# BEGIN
#
# This was added to webroot/cron_scheduler.php
#

# Check that URI was specified and that we're called from the command line (not the web)
if($argc == 2 && php_sapi_name() === "cli") 
{
    # Set request URI
    $_SERVER['REQUEST_URI'] = $argv[1];
    # Set user-agent, so we can do custom processing
    $_SERVER['HTTP_USER_AGENT'] = 'cron';
    
    $Dispatcher= new Dispatcher();
    $Dispatcher->dispatch($argv[1]);
} 

#
# END
#
# 
#

Now you can execute CakePHP from the command line with the following command:

$ php cron_scheduler.php /controller/action

If you get the following error, remove the lines containing line feeds in bootstrap.php:

Warning: Cannot modify header information - headers already sent by (output started at .../app/config/b
ootstrap.php:48) in .../app/app_controller.php on line 46

PHP file upload gotchas

Tagged gotcha, php, file, upload  Languages php

PHP file upload works in mysterious ways:

http://us3.php.net/manual/en/ini.core.php#ini.post-max-size
http://fi.php.net/manual/en/features.file-upload.php#73762
http://de3.php.net/manual/en/features.file-upload.errors.php

A simple and easy to use PHP XML parser

Tagged php, xml, parser, simple  Languages php

The PHP XML parser:

class XML
{
    static function parse($data, $handler, $encoding = "UTF-8")
    {
        $parser = xml_parser_create($encoding);

        xml_set_object($parser, $handler);
        
        xml_set_element_handler($parser,
            array(&$handler, 'start'),
            array(&$handler, 'end')
        );
            
        xml_set_character_data_handler(
            $parser,
            array($handler, 'content')
        );
            
        $result = xml_parse($parser, $data);

        if(!$result)
        {
            $error_string = xml_error_string(xml_get_error_code($parser));
            $error_line   = xml_get_current_line_number($parser);
            $error_column = xml_get_current_column_number($parser);
            
            $message = sprintf("XML error '%s' at line %d column %d", $error_string, $error_line, $error_column);
            
            throw new Exception($message);
        }

        xml_parser_free($parser);
    }
}

A result handler:

class ResultHandler
{
    var $tag;

    function start ($parser, $tagName, $attributes = null)
    {
        echo "start";
        $this->tag .= $tagName; # Use .= to work around bug...
    }

    function end ($parser, $tagName)
    {
        echo "end";
        $this->tag = null;

    }

    function content ($parser, $content)
    {
        echo "$this->tag: $content" ;
    }
}

Then in your code:

$xml = "<a>bah</a>";
XML::parse($xml, new ResultHandler());

Note that HTML/XML entities are considered to be tags by PHP's XML parser, so your start tag handler will be called three times for this tag, once for "really", once for "&" and once for " bad parser":

<data>really &amp;  bad parser</data>

I guess this is a bug... You can

PHP exception and error handling with register_shutdown_function and set_exception_handler

Tagged php, exception, 500, blank, page  Languages php

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".

$no_errors_detected = false;

class DispatchErrors 
{
    static function handleException($exception) 
    {
      Logging::error($message);

        header( 'Location: /error500.html' );
    }
    
    static function handleShutdown()
    {
        global $no_errors_detected;
        
        if (!$no_errors_detected)
        {
            header( 'Location: /error500.html' );
        }       
    }
}

register_shutdown_function(array('DispatchErrors', 'handleShutdown'));
set_exception_handler(array('DispatchErrors', 'handleException'));

# handleShutdown will be called
#range(0, 10000000000000000000);

# handleException will be called
#throw new Exception("abcd");

# Insert your buggy code here

$no_errors_detected = true;

How to set a cookie, remove a cookie and get the value of a cookie in PHP

Tagged php, cookie, management, set, remove, get  Languages 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:

$value = 0;
$expires = 0;
setcookie('cookie_name', $value, $expires, '/');

Remove cookie

setcookie ('cookie_name', FALSE, time()-10000);

Get cookie value

$_COOKIE['cookie_name']

How to use file_get_contents with a proxy

Tagged file_get_contents, proxy  Languages php
$url = 'http://www';

$proxy = 'tcp://xxx:8080';

$context = array(
    'http' => array(
        'proxy' => $proxy,
        'request_fulluri' => True,
        ),
    );
    
$context = stream_context_create($context);

$body = file_get_contents($url, False, $context);

The code was found here. Note that it doesn't seem to work with HTTPS.