Tag Archives: php
I’ve just released PHPShortener, a PHP class that makes it very easy to encode/decode URLs with services such as tr.im, is.gd, and others.
Encoding and decoding is a simple as this:
$s = new PHPShortener();
// encode a long url
$shorturl = $s->encode('http://devthought.com/projects/php/phpshortener/', 'is.gd');
// decode a short url (autodetects the service)
$longurl = $s->decode('http://tr.im/jBBp');
Head to the project page for downloads and documentation. Fork me on GitHub if you want to contribute!
if ( comments_open() ) { ?>First of all, we make our file start like this.
#!/usr/bin/env php
This allows us to run the script without prefixing it with the “php” command, and instead we can run it like this:
chmod +x myscript # This gives execution permissions to the script, do it only once
./myscript --first=option --second --third=option
If we want our script to take options like in the example above, we can use this snippet:
$options = array();
foreach ($argv as $arg){
preg_match('/\-\-(\w*)\=?(.+)?/', $arg, $value);
if ($value && isset($value[1]) && $value[1])
$options[$value[1]] = isset($value[2]) ? $value[2] : null;
}
The $options array will hold the supplied options. You can then use them like this:
if (!isset($options['somevalue']))
// show an error
if (isset($options['dosomething']))
// do something
There’s a very useful PHP function called filemtime, that returns the timestamp of the modification time of the file. This is similar to how the HTTP 1.1 ETag header is generated. The strategy is basically to append the modification date to the script or CSS URI in order to refresh the user’s cache when you’ve modified them.
This is an extract from Devthought header.php WordPress template file:
All you have to do is change the routes to match your files. If you’re not using wordpress, you’ll have to remove the get_stylesheet_directory* and get_template_directory* function calls and replace with your paths.
PHP provides two very useful functions to create temporary files. Instead of creating unnecessary tmp directories in your applications, it’s better to rely on the global directory assigned for that matter.
To create a unique file with the right permissions use the tempnam function:
$filename = tempnam('/tmp_directory', 'filePrefix');
You can test this from the command line like this:
php -R 'tempnam("/tmp", "hello");'
The output file looks something like this:
guillermo-rauchs-macbook-pro-15:tmp willy$ ls -la hello*
-rw------- 1 willy staff 0 Mar 11 03:26 helloyvEzzb
Couple this function with sys_get_temp_dir and you’ve solved the dilemma:
$filename = tempnam(sys_get_temp_dir(), 'filePrefix');