Closing PHP tags are optional

Sometimes leaving out the closing PHP tags ( ?> ) are better because it prevents errors due to unwanted whitespace at the end of your script. This is especially useful if you’re including various PHP files.

Downloading PDF files

If you’ve done the Thirty Day Challenge, you’ll know how tedious it can be to download all the PDF files. Norio created a cool downloading script that saved me a lot of time. I was just too lazy to sit and write something like it, so I’m stealing his!

<?php
// make sure our download doesn't time out or get interrupted by closing the browser
set_time_limit(0);
ignore_user_abort(1);
// destination to download to
$file_dir = "sites/default/files/30dc";
// create the destination directory if it doesn't exist
if (!is_dir($file_dir)) mkdir($file_dir);
// go through each day of training (1-31)
for ($i = 1; $i <= 31; $i++) {
  // download the HTML contents of the training page for that day
  if ($page = file_get_contents("http://www.thirtydaychallenge.com/training/2009day".sprintf("%02d", $i).".php")) {
    // provide some feedback on where we are
    echo "<b>Day $i:</b><br />";
    // flush output to browser - see php.net/flush
    flush();
    // directory to download the current day's PDFs to
    $daydir = $file_dir."/day$i";
    // create the directory if it doesn't exist
    if (!is_dir($daydir)) mkdir($daydir);
    // grab all the URLs to the PDFs (regular expressions are awesome!)
    preg_match_all('~(http://media.thirtydaychallenge.com.s3.amazonaws.com/training09/([0-9A-Za-z_]+.pdf))~', $page, $matches);
    // go through each url we grabbed above
    foreach ($matches[1] as $key => $filename) {
      // check if the file already exists (no use in re-downloading PDFs we have)
      if (!file_exists($matches[2][$key])) {
        // provide some feedback on where we are
        echo "Downloading {$matches[2][$key]}.<br />";
        // flush output to browser
        flush();
        // download the pdf and store it locally
        file_put_contents("{$daydir}/{$matches[2][$key]}", file_get_contents($matches[1][$key]));
      }
    }
  }
}
?>

Check out the full post at Boff.co.za

Date and Strtotime Coolness

Two very useful functions in PHP is strtotime and date. It can be cumbersome to make use of these 2 though, so I got a little function that makes it so much easier.

function odate($format, $criteria){
  return (date($format), strtotime($criteria, strtotime($format)));
}

Now all you do is call it like :

echo odate("Y-m-d H:i:s", "+1 days"); // 1 day ahead of today
echo odate("Y-m-d H:i:s", "-7 days"); //  7 days ago
echo odate("Y-m-d H:i:s", "+1 hours"); // 1 hours from now

Getting information from a URL

Very often you need to be able to pull out parts of the information that is contained within a URL. Like the port, the protocol, etc.

This is where the parse_url function is so handy.

Let’s look at the following code:

  $url_info = parse_url('http://username:password@www.phpdeveloping.co.za:80/directory/?arg=value#anchor');  
  print_r($url_info);

The output will be something like:

Array  
(  
  [scheme] => http  
  [host] => www.phpdeveloping.co.za 
  [user] => username  
  [pass] => password  
  [path] => /directory  
  [port] => /80  
  [query] => arg=value  
  [fragment] => anchor  
)

Posting a Tweet to Twitter using PHP

I found this PHP Twitter Class after having recently started developing my own class. I’d recommend downloading this if you’re looking to do anything with PHP and Twitter because it takes care of most of the work for you.

If you want to post a Tweet to Twitter, it’s as simple as the following lines of code:

include "twitter.php";
$t = new Twitter("username","password");
$t->updateStatus('This is a Tweet');

Now doesn’t that make life a lot easier?

How long does your script run?

A while back I launched WebSpeedTest.co.za which is just a little script to check how long it takes to load your website. It doesn’t take into account loading of all objects on the website, just the HTML.

Some of the code can be used in your PHP script to see how long it takes to load.

First what you do is add this at the very top of your script.

$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;

That will have recorded your start time in the variable $start.

Now, at the very end of your script add this in:

$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);

$total_time now contains the amount of seconds it took to run your script. This can be useful for debugging to check where you might have bottlenecks.

Smarty quick and dirty

Smarty is an excellent template system used for PHP. It’s definitely the best and most versatile one I’ve seen.

Let’s say you have an index.tpl (the default template file extension in Smarty) with the following in it:

<html>
<head>
<title>Information</title>
</head>
<body>
Number 1: {$num1}<br>
Number 2: {$num2}<br>
</body>
</html>

Now, to actually use the template you would have code like the following:

$smarty = new Smarty;
$smarty->assign('num1', '111');
$smarty->assign('num2', '222');
$smarty->display('index.tpl');

As simple as that!

The output would be:

<html>
<head>
<title>Information</title>
</head>
<body>
Number 1: 111<br>
Number 2: 222<br>
</body>
</html>

That is just a simple example, and there are a lot more advanced things you can do with it. Check out the Smarty Crash Course for some ideas.

Using Eval

I use this function very rarely. For some reason I just never need to use it. I know in Drupal it is used quite often, especially if you use the PHP input field for a node. This allows you to enter PHP code that will be evaluated (or run) and then the output is shown as the node’s content.

I suppose this is mostly used when you want a user to be able to enter PHP code into a text field and then run it. Not always too secure I would think, so be careful where and how you use this.

  $s = "<?php phpinfo(); ?>";
  eval($s);

Decimal to Roman numbers

I needed a function to translate from decimal numbers to their Roman number equivalent. Here’s a handy little function I found.

private function numberToRoman($num)
{
     $n = intval($num);
     $result = '';
 
     $lookup = array('M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,
     'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,
     'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1);
 
     foreach ($lookup as $roman => $value) {
       $matches = intval($n / $value);
       $result .= str_repeat($roman, $matches);
       $n = $n % $value;
     }
     return $result;
}

Following my post on getting links on a website, I thought I’ll also show you how to use those functions to get all the images on a website.

  $url = "http://www.phpdeveloping.co.za/";
  $html = file_get_html($url);
  if ($images = $html->find('img'))
  {
    foreach($images as $image)
    {
      echo $image->src."\r\n";
    }
  }

You can see how this makes your life a little bit easier when you compare it to the function I always use.