Tag Archives: PHP

Method Chaining in PHP

Have you ever come across a PHP class that connects methods together in a single line to achieve some goal? (If you haven’t, Guzzle and SwiftMail are a couple of examples.)

//Example from http://guzzlephp.org/
$client = new Client($url);
$request = $client->get('/user')->setAuth('user', 'pass');
$response = $request->send();

jQuery also operates in a similar manner, using the same principle. The technique is called method chaining, and is quite useful in cases where a class has many public methods that could be called upon with each others’ output.

If you wanted, the above example could conceivably be rewritten like this:

$client = new Client($url);
$path = $client->get('/user');
$request = $path->setAuth('user', 'pass');
$response = $request->send();

This works because of the way chainable methods are set up. The secret to making it work is that every method must return the entire object. What you’re doing when you chain Method A with Method B ($object->methodA()->methodB) is calling Method B from the object returned by Method A, which it returned from the object that called it to begin with.

Here’s an example class that permits chaining, since there’s no way that code could be more syntactically awkward than that sentence:

class MyClass {

	function __construct() {
		$this->thing = "a";
	}

	function addB() {
		$this->thing .= "b";
		return $this;
	}

	function addC() {
		$this->thing .= "c";
		return $this;
	}

	function __tostring() {
		return $this->thing;
	}

}

$obj = new MyClass();
echo $obj->addB()->addC(); //outputs "abc"
echo $obj->addB(); //outputs "ab"
echo $obj->addC(); //outputs "ac"
echo $obj; //outputs "a"

When you initialize the object, the constructor sets the thing property to be a. Each one of the methods returns $this, which of course is the entire object. So if you call addB(), it adds b to the string and then returns $this. So you can chain the addC() method, which is basically calling it on the $this that addB() returned.

I hope this helps you understand method chaining. It took me a little while to figure it out, and explaining it clearly is about as easy as reading this probably is. :)

Generating a Software License Key String with PHP

I was working on a project recently that required unique API keys to be generated for clients connecting to the server. For various reasons, I settled on the style of license key you commonly see for software packages. You know, the kind you always had to read off the back of a CD case and type in when installing the application. Like H8OV7-HNTB5-JLLOH-W8FG2.

It’s fairly easy to write such a function. The basic idea is to loop around four times—once for each segment—and have a nested loop that runs five times, picking a random character each time. Here’s what I came up with:

function generate_key_string() {

	$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$segment_chars = 5;
	$num_segments = 4;
	$key_string = '';

	for ($i = 0; $i < $num_segments; $i++) {

		$segment = '';

		for ($j = 0; $j < $segment_chars; $j++) {
    			$segment .= $tokens[rand(0, 35)];
		}

		$key_string .= $segment;

		if ($i < ($num_segments - 1)) {
    			$key_string .= '-';
		}

	}

	return $key_string;

}

The $tokens string contains the characters that are valid in the key, so the loop can pick from it. The $segment_chars and $num_segments variables are the number of characters in a segment and the number of segments in the key, respectively. $key_string is an empty string that the loop will add the characters into.

The first for loop runs four times, assuming the desired result is four segments in the key. The inner loop picks a character out of $tokens at random each time it goes around. (PHP strings are also arrays, with the each character having its own numerical offset.) The characters are tacked onto the $segment string.

Then the segment is joined with the $key_string, and a dash character is applied if the loop isn’t on the final segment yet. End result: something like H8OV7-HNTB5-JLLOH-W8FG2.

Now how can you make sure the key is unique when it’s generated?

do {
	$key_string = generate_key_string();
	$result = $db->query("SELECT license_key FROM my_license_key_table WHERE license_key = '$key_string'");
	//$db is a PDO object. If you're not familiar with PDO, check out http://www.webmaster-source.com/2011/08/05/getting-your-feet-wet-with-pdo-and-migrating-old-mysql-code/
} while ($result != false);

You generate a new key string with the function, check to see if it exists in your database, and lather/rinse/repeat until that is no longer the case. Usually you won’t have collisions too often, so it will only need to run once. I’m too lazy to figure out the probability, but considering there are 52,521,875 possible combinations for one 5-character segment…you’re probably not going to run into performance issues anytime soon. And if you do, just add another segment onto your key strings.

Using the WordPress 3.5 Media Uploader in Your Plugin or Theme

Back in 2010, I wrote a post on Using the WordPress Uploader in Your Plugin or Theme that went on to be one of my most popular tutorials of all time. Then the WordPress team went and added a much cooler media uploader in version 3.5 and make that post outdated. Since most of you probably want to add the new uploader in a theme or plugin you’re working on right now, I figured it was time for an updated post.

WordPress 3.5 Media Uploader

The process required to add the new uploader is a bit different, but not too much more difficult. I was able to adapt the old tutorial a little, so it shouldn’t be too hard to replace some code in an existing project and get the new uploader instead of the old.

Continue reading →

PHP: The Right Way

There’s a lot of outdated information on the Web that leads new PHP users astray, propagating bad practices and bad code. This must stop. PHP: The Right Way is an easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative tutorials around the Web.

PHP: The Right Way is a useful guide to how to write PHP that won’t make other developers cringe in horror. It starts off with some tips on how to manage your development environment and then gets to the good part: what not to do. Advice is featured on matters such as database access, password hashing, and other security issues.

The site is an excellent central resource that gives a good overview of things that every beginning PHP developer should be aware of.

Manipulating Color Data with phpColors

phpColors is an interesting library that makes it easy to work with colors in PHP. It can determine whether a color is dark or light, as well as darken or lighten a color incrementally, as well as generate complementary colors. It has functions that output hexadecimal or HSL representations of the color, or a gradient array.

It makes it super easy to do something like this:

using phpColors\Color;
$color = new Color("#eeeeee");

if ( $color-&gt;isLight() ) {
	$gradient = $color->makeGradient();
	// array( "light" => "the_light_color_hex", "dark" => "the_dark_color_hex" )
}

phpColors [GitHub]

Proposed Secure Password Hashing API in PHP 5.5

PHP 5.5 will be gaining a simpler and more newbie-friendly way to securely hash passwords. As those who are active in the PHP community are all to well aware of, it is quite a trial to educate everyone on properly securing passwords in their applications. Even large web companies are routinely outed for their lax measures. Sometimes they’re stored in plain text and sometimes they might as well be, like when weak MD5 or SHA1 hashes are used. Remember the big scandal when Gawker Media’s database of user passwords was leaked, and the weak hashes were solved within days? Or more recently, when it was discovered that Pandora not only stored your password in cleartext, but transmitted it that way as well? It seems that at least two well-known websites have a similar “facepalm” moment every year.

The PHP contributors want to help combat this problem—at least among companies using PHP, obviously the issue is by no means limited to PHP developers—with the new API. A couple of simple functions that even the most novice of developers can use will automatically take care of the hashing using bcrypt with a reasonable work factor.

The proposed syntax is something like this:

//hashing a new password
$hash = password_hash($password_entered);

//Checking a password
if (password_verify($password_entered, $hash_from_database)) {
    //password is valid if password_verify() returns true
}

For compatibility with versions of PHP prior to 5.5, you can even download a PHP implementation that will automatically be disabled in a PHP 5.5 environment.

The new Secure Password Hashing API in PHP 5.5 [GitHub]

GitList: View Your Git Repositories on the Web

Wouldn’t it be cool if you could host your own private GitHub, for browsing your local repositories or remote ones you host on your own server? Well, there’s a new PHP application in town that lets you do exactly that. GitList, the self-described “elegant and modern git repository viewer” adds a simple web interface for your repositories, allowing you to browse commits and code. It’s still in its infancy, but it has the basics.

Setup was a little bit of a hassle at first, due to some dependency issues with the development version I was trying to install. I would definitely recommend downloading the stable version from GitList.org. The installation instructions are simple enough, though the script seems to prefer having its own domain or subdomain. (GitList doesn’t use absolute URLs, and there is no documented configuration option to set a base directory other than the domain root.)

Once you get it up and running, it’s a convenient way to view commits. I’d probably be using it regularly if I wasn’t already hosting my private repositories on BitBucket.

WordPress’s…Interesting Way of Dealing with Magic Quotes

If you’ve been working with PHP for awhile, you’re probably familiar with one of the worst ideas the language’s developers ever came up with: Magic Quotes.

If not, here’s a brief history lesson. In order to help newbies write functioning MySQL queries, they thought it would be a great idea to automatically escape input data with slashes, overwriting the $_POST, $_GET and $_REQUEST globals. So if someone submitted hello, I'm Steve through a form, it would be immediately converted to hello, I\'m Steve so the apostrophe wouldn’t cause issue if a naive user tried inserting it into a database.

But what if you weren’t going to dump the data into a MySQL database? Too bad, it’s now full of slashes and you have to use stripslashes() on the variable. Also, you could conceivably end up with something like hello, I\\\'m Steve if you try escaping the data yourself before inserting the data into a database. It was a massive headache, and the normal practice ended up being “check to see if magic quotes are enabled at the top of your script, and strip the slashes out if the feature is activated. Then handle database queries with prepared statements or by properly escaping the data.”

Continue reading →

Handling File Uploads with PHP

So you want to add a file uploader to your site. It’s quite easy to do with PHP, but first you must understand the inherent risks. You’re going to allow just anyone to take a file and put it on your server. That file could be anything. It could be an image like you may intend, or someone could get clever and try to upload a malicious PHP script, which could then be run when called by the appropriate URL. Or a user could upload larger files than you intended and waste your server’s storage space. (This is assuming you intend to have a public-facing uploader, of course. It’s less of an issue if its a back-end feature.)

Let’s start with the basics of setting up the form, and handling the uploaded file. Then we can tackle some of the security issues.

For the upload to work, you must add enctype="multipart/form-data" to your form tag. This signals that the POST request will contain upload data as well as the form field values.

Among fields you’ll need are a hidden field named MAX_FILE_SIZE, which tells the client not to accept a file over a certain number of bytes (300000, or 300 kilobytes, in this example) as well as the file upload field itself.

Continue reading →

Find an Image’s Dimensions and MIME Type with PHP

What’s the easiest way to figure out the width and height of an image, as well as the format of the file, in PHP? Given that the existence of a core function for practically everything is one of the language’s strengths, it’s unsurprising that it’s pretty easy.

The getimagesize() function returns an array containing the width and height and the content type.

//Basic usage
$info = getimagesize($filename);
$width = $info[0];
$height = $info[1];
$format = $info['mime'];

//Alternate one-liner suggested by the manual
list($width, $height, $type, $attr) = getimagesize($filename);

This function is really useful for handling image uploads, since you can’t necessarily trust the MIME type that $_FILES reports. The function actually inspects the file to ascertain the type, rather than relying on what the client reports. Also, you may want to make sure that the uploaded images match the dimensions you have in mind.

Here’s how I like to handle it:

$imgdata = getimagesize($_FILES['image_upload']['tmp_name']);

if ($imgdata[0] > 640 || $imgdata[1] > 480) {
	$errors[] = "Your image is too big!";
}

if (!in_array($imgdata['mime'], array( 'image/gif', 'image/png', 'image/jpeg', 'image/pjpeg' ))) {
	$errors[] = "Your file should be a PNG, JPG or GIF!";
}
Page 1 of 12123456Last »