PHP URL Shortening Class released

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!

This post has 9 responses

Posted in Server side 2 months ago

Writing a PHP command line script that takes options

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

This post has 4 responses

Prevent caching of modified Javascript & CSS assets

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:

<link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri() . '/style.css?' . filemtime(get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="screen" title="Stylesheet" charset="utf-8" />
 
<script type="text/javascript" charset="utf-8" src="<?php echo get_template_directory_uri() . '/js/scripts.js?' . filemtime(get_template_directory() . '/js/scripts.js'); ?>" ></script>

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.

This post has 3 responses

Posted in Server side 4 months ago

Tip: Create temporary files in PHP

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');

This post has 1 response

Tip: adjust php.ini settings for a single CLI command

The PHP command accepts some interesting parameters which add flexibility to how scripts that you run from your shell or cron jobs are executed.

One of them is -d, which alters a php.ini value for the duration of the command. An example is as follows:

php5 -d memory_limit=128M symfony propel:data-load

This was a real time saver considering the server was not setup with a CLI-specific php.ini, like some are.

This post has 2 responses

Custom fields in edit/new admin generator views in Symfony

Let’s say we want to create a field to set the password in plain text from the admin panel, then convert it to sha1 before saving it. Our hypothetical module will be located in backend/modules/admins/, which is a Symfony admin generator module for an AdminUser model.

First we define the getters and setters for the plaintext password in the AdminUser model:

  public function setPasswordPlain($plain)
  {
    if(! empty($plain))
        $this->setPassword(sha1($plain));
  }
 
  public function getPasswordPlain()
  {
    return "";
  }

Then, in generator.yml we add this field to form sections, using the display parameter:

      form:    
        display:              [login, password_plain, email]

If we try the generator now, we’ll get an error message telling us that password_plain widget does not exist, which is true. The new admin generator uses the great Symfony 1.2 forms system, which treats a form as a set of widgets and validators.

If we inspect the lib directory of our generated module we’ll notice the file called adminsGeneratorConfiguration.class.php. This file extends BaseAdminsGeneratorConfiguration which, if we look closely, configures what form is related to this generated module:

  public function getFormClass()
  {
    return 'AdminUserForm';
  }

What we have to do is obvious. We extend AdminUserForm, and we override that method to return the name of our new class. In the same lib directory we create the form:

class myAdminUserForm extends BaseAdminUserForm
{
 
  public function configure()
  {
    parent::configure();
 
    $this->setWidget('password_plain', new sfWidgetFormInput());
    $this->setValidator('password_plain', new sfValidatorString(array('max_length' => 255, 'required' => false)));
  }
 
}

and finally we alter the adminsGeneratorConfiguration accordingly:

class adminsGeneratorConfiguration extends BaseAdminsGeneratorConfiguration
{
 
  public function getFormClass()
  {
    return 'myAdminUserForm';
  }
 
}

This post has 4 responses

Posted in Blog, Server side 5 months ago

Append your blog description to the window title in Wordpress

I wanted my homepage title to reveal my writing goals and interests. The importance of the title, to me, is obvious:

  • It’s one of the first things people notice.
  • It’s visible in the window chrome, the tabs, the bookmarks
  • It’s something search engines pay attention to

Wordpress settings allow you to set the blog title and description. With this modification, the description will be appended whenever a post title is not displayed, to avoid making it extremely long.

Edit the functions.php file of your template and append:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
add_filter('wp_title', 'dv_wp_title', 100, 3);
 
$dv_append_subtitle = false;
 
function dv_wp_title($title)
{
  global $dv_append_subtitle;
 
  if($title === '') 
    $dv_append_subtitle = true;
 
  return $title;
}
 
function dv_the_subtitle($sep = '&mdash;')
{
  global $dv_append_subtitle;
 
  if($dv_append_subtitle)
  {
    echo $sep ? $sep . ' ' : '';
    bloginfo('description');  
  }
}

Then go to header.php and make your title tag look like this (notice that I added the dv_the_subtitle call)

<title><?php wp_title('&laquo;', true, 'right'); ?> <?php bloginfo('name'); ?> <?php dv_the_subtitle(); ?></title>

And that’s it! If you want to customize the separator, which defaults to — pass it as an argument to dv_the_subtitle.

This post has 7 responses

WP-o-Matic 1.0RC4 released

Some important and some not-as-important bug fixes in this version. Hopefully this will be the last release candidate before the grand 1.0 release:

  • Tables not deleted anymore upon installation
  • Fixed SimplePie error report.
  • Fixed small post content bug (not hidden by default)
  • Fixed cron url
  • Removed inverted quotes from queries
  • Fixed notices in debug mode
  • No error showing for campaigns w/o feeds fixed

Click here to download

As usual, head to Lighthouse for bug reports

This post has 5 responses

Posted in Projects 12 months ago

WP-o-Matic 1.0RC3 beta shipping.

Here is the upcoming RC3 release!

Remember that, just like any release prior to 1.0, upgrading will erase your previous campaigns, feeds, logs, etc.

  • Now compatible with Wordpress 2.5
  • Categories shown with indentation (parent > children now separated)
  • SimplePie updated to 1.1.1, and SimplePie Core now supported.
  • Fixed broken cron command
  • Fixed broken export on some systems
  • Fixed broken redirect when resetting a campaign
  • Everything now stored in GMT to avoid time issues. Gotten rid of NOW() functions in favor of WP time functions
  • Fixed bug with validation upon deletion of feeds in existing campaigns
  • Fixed bug with ‘allow comments’ setting.
  • Fixed bug with logs dates
  • Fixed bug with double quote escaping (fixes campaign templates / rewrite html bugs)
  • Username in options tab changed to a more handy select box.
  • Interface now looks better on IE (d’oh)
  • Added many help files
  • Fixed annoying duplicates bug
  • Fixed small bug in import with labels

I need feedback on:

  • All sorts of errors, warnings, notices, blank screens
  • Styling problems, indicating Browser, OS, URL and a screenshot.
  • Behavioral problems: bad dates, bad content, duplicates, etc
  • Performance problems
  • Unexpected behavior

Always include instructions on how to reproduce the issues please!

Go ahead and download it

Updates

  • 1 - Fixed bugs with categories in edit mode and posts tools (thanks Mike)
  • 2 - Fixed empty rewrite bug (thanks Mike) and replacements now case insensitive
  • 3 - Fixed bugs with ‘use feed date’ option, footer copyright, bad dates in ‘view all’ logs, log message field made text, timestamps converted to datetime, ‘Clean logs’ function fixed (big changes, please test)
  • 4 - Fixed bugs with older WP releases (now WP-o-Matic works with any version starting from 2.2). Now rewrite works with PHP4.
  • 5 - str_ireplace bug fixed, allow comments bug fixed, now user can choose comments state.
  • 6 - {content} not getting rewritten fixed, titles and other settings not being stored fixed.

This post has 87 responses

Posted in Projects about 1 year ago

WP-o-Matic 1.0RC3 on its way

Update: here it is

Just writing to let you know that the upcoming release candidate of WP-o-Matic is being cooked and betatested!

This is a list of all the exciting changes, which include new features you’ve been requesting and lots of bugfixes

  • Categories shown with indentation (parent > children now separated)
  • Fixed broken cron command
  • SimplePie updated to 1.1
  • Fixed broken export on some systems
  • Fixed broken redirect when resetting a campaign
  • Everything now stored in GMT to avoid time issues. Gotten rid of NOW() functions in favor of WP time functions
  • Fixed bug with validation upon deletion of feeds in existing campaigns
  • Fixed bug with ‘allow comments’ setting.
  • Fixed bug with logs dates
  • Fixed bug with double quote escaping (fixes campaign templates / rewrite html bugs)
  • Username in options tab changed to a more handy select box.
  • Interface now looks better on IE (d’oh)
  • New option added to select max number of items to process
  • New option added to decide whether the permalink should point to the created blog post or to the source permalink
  • New general option to get logs feedback while the campaign is being processed.

As usual, stay tuned. Sorry for not being able to respond and release with more frequency, but I’ve been really busy.

This post has 42 responses

Posted in Projects about 1 year ago