UltraMega Blog
15Dec/092

PHP in the Shell

PHP may be most commonly used within a web server to produce web pages, but it is a powerful scripting engine by itself. PHP is an amazingly useful multipurpose tool when used from the command line. This post will show you how to use the PHP Command Line Interface (CLI). Some of the information here is Linux specific, but there are equivalents for Windows.

Accessing the PHP CLI

Obviously the first thing you need to know is how to run PHP from the command line. There are a number of ways to do this, and one way that I prefer.

The method I find easiest is to write your script as a shell script. This basically means taking a regular PHP script and adding a line to the beginning declaring the php binary to interpret the script. Here's an example:

#!/usr/bin/php
< ?php
echo 'Hello World';
?>

Assuming the file name 'test.php' you would make it executable with chmod +x test.php and run it simply with ./test.php. Note that the file does not need to end with .php to function.

Other options for accessing the PHP CLI are to pass scripts or code to php as parameters, pass code to php through standard input, or enter code manually in interactive mode.

File as parameter:

$ php test.php

Code as parameter:

$ php -r "echo 'Hello World';"

Code through standard input (generate_php_code outputs code):

$ generate_php_code | php

Interactive mode:

$ php -a
Interactive shell
 
php > echo 'Hello World';
Hello World
php >
1Dec/091

Using cURL Within PHP

PHP includes an easy to use interface for the cURL library. This means you can easily communicate with other servers using a variety of protocols. It is commonly used to access web service APIs such as Twitter. This tutorial will explain the basics and show some usage examples.

There are 4 main functions you need to know to use cURL: curl_init, curl_setopt, curl_exec, and curl_close. The process generally goes like this:

  1. start a cURL session and get a handle (curl_init)
  2. set the options for the session (curl_setopt)
  3. execute the session (curl_exec)
  4. close the session (curl_close).

The handle returned by curl_init is used as the first parameter in the other functions.

All the available options are listed on the curl_setopt manual page with detailed descriptions.

Tagged as: , Continue reading
10Nov/090

10 Common PHP Mistakes to Avoid

These are some very common mistakes that are made in PHP. Some of these can be tricky to catch and can lead to all sorts of strange behavior. So here are 10 common PHP coding mistakes to avoid.

1 '=' Vs. '=='

Using a single '=' in a comparison will cause an assignment and return true, so this mistake can have some pretty unexpected results. It can be hard to catch since it looks perfectly valid to the interpreter if you are comparing something with a variable.

An easy way to avoid this is to swap the subject and variable like this:

<?php
if(true = $something) { // Parse error!
   // do stuff
}
?>

The above will result in a parse error since you can't assign a literal to something, making it easy to catch and fix.

2 '==' Vs. '==='

There is a big difference between the '==' (equal) and '===' (identical) comparison operators. '==' will convert types to match before making the comparison, while '===' will compare directly without converting. So in situations where the difference between '0' and 'false' matters, you must use '==='. Here's some examples:

<?php
var_dump(false == 0); // true
var_dump(false === 0); // false
var_dump(false === false); // true
var_dump('0' == 0); // true
var_dump('0' === 0); // false
?>
3Nov/090

PHP: Process Array Items With array_map

Let's say you want to run a function on each item in an array. For example, you want to run strip_tags() on all $_POST data. One way to accomplish that is to use a foreach loop and reassign each array element manually, but there's a function for that. The array_map function accepts the name of a function and an array or arrays to run the function on.

So to accomplish our simple example, this is all it takes:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('strip_tags', $original);
 
// $new is now array('Paragraph', 'Bold');

You can supply any function, including any you define for more advanced use:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('clean_input', $original);
 
function clean_input($value)
{
    return strip_tags($value, '<p>'); // allow p tags
}
 
// $new is now array('<p>Paragraph</p>', 'Bold');

The array_map function is a powerful utility when it comes to working with arrays. You can do things in one line that would otherwise require loops and other complex structures. The examples here are just very basic, but are handy for many everyday tasks. Check the examples in the PHP documentation for other tricks array_map can do.

22Oct/090

The ‘War’ on IE6

Recently I've been noticing a trend among Web developers to "take action" against MS Internet Explorer 6. From putting badges on their Twitter avatars to designing websites to detect and block IE6, many designers and developers are coming up with their own ideas to help end the browser's reign of terror. My question is, are some of these methods appropriate or even in their best interests?

15Oct/093

Default Form Values with jQuery

Here's a useful jQuery snippet that clears the default values of form fields on focus and refills them if no text is entered. It uses the attribute called defaultValue which stores the original value of a form field.

$(document).ready(function() {
   $('input[type=text]').focus(function() {
      if($(this).val() == $(this).attr('defaultValue')) {
         $(this).val('');
      }
   })
   .blur(function() {
      if($(this).val().length == 0) {
         $(this).val($(this).attr('defaultValue'));
      }
   });
});

For example, assume you have a field like this:

<input type="text" value="Search..." />

When the page loads, the text field will have "Search..." filled in. When you focus on it, this text will disappear (assuming it hasn't already been edited by you). When you leave focus without typing anything, the text will reappear.