Skip to content

Instantly share code, notes, and snippets.

@r-sal
Created December 18, 2012 02:06
Show Gist options
  • Save r-sal/4324371 to your computer and use it in GitHub Desktop.
Save r-sal/4324371 to your computer and use it in GitHub Desktop.

PHP Snippets

Switching between \n and

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
echo date('H:i:s') , " Load from Excel5 template" , EOL;

###Download a file from the command-line

php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

###Preventing files being run from the command line

if (PHP_SAPI == 'cli')
  die('This example should only be run from a Web Browser');

###How to get last key in an array
end() advances array 's internal pointer to the last element, and returns its value.
key() returns the index element of the current array position.

$array = array(
    'first' => 123, 'second' => 456, 'last' => 789, );

end($array);         // move the internal pointer to the end of the array
$key = key($array);  // fetches the key of the element pointed to by the internal pointer

Will output: string 'last' (length=4)


###Pow to post data in PHP using file_get_contents

$postdata = http_build_query(array('var1' => 'some content', 'var2' => 'doh'));

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);

Print PHP Call Stack

If you want to generate a backtrace, you are looking for debug_backtrace and/or debug_print_backtrace.


rtrim($string, ",") would cut trailing commas. trim($string, ",") would cut trailing and prefixing commas.


isset() / empty() / NULL

The Definitive Guide To PHP's isset And empty

The following two expressions are equivalent:

$foo = (unset)$bar;
$foo = null;

Using the (unset) cast neither changes the value of $bar nor does it unset $bar. The only effect it has is the assignment of the value null to foo. $foo is not unset in any way either, it continues to exist with the value null. To actually remove a variable, the function unset() needs to be used:

unset($foo);

Array Keys

$array = array('key' => null);

var_dump(isset($array['key']));              -> false
var_dump(array_key_exists('key', $array));   -> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment