Serializing and unserializing variables

Serialization in PHP is the act of converting a variable into a storable value. When I say storable, I mean being able to store the result in say, a database or a flat file. This is commonly applied to arrays and objects as they are not simply text strings. Under the hood, PHP uses serialize() for session data as it is just an array....

Read Full Article →

Calculate the length of a string

Calculating the length of a string is a useful feature of any language, in fact it’s one of the few pieces of functionality that has a consistently simple syntax across modern languages. You can calculate the length of a string as part of some server side user input validation or do so to determine if you should truncate a string and add ellipses to...

Read Full Article →

How to get a server’s hostname

The hostname of your server or local system is an easy way to determine which environment you are working with, either local or production. Prior to PHP 5.3 you would need to utilize the php_uname() function and with 5.3+ there is a built-in function for getting the hostname: pre-5.3 $hostname = php_uname('n'); 5.3+ $hostname = gethostname(); Once you have the hostname, you can do...

Read Full Article →

How to save a remote file to disk

You may already be familiar with file_get_contents() for reading the contents of a local file but did you know that you can use it to read the contents of a remote file or site? You can then use file_put_contents() to write the file’s contents back to disk: file_put_contents('./some/local/file', file_get_contents('http://phpave.com')); Both functions are binary safe so you should be fine to work with files that...

Read Full Article →

Basic HTTP Authentication with PHP

Basic HTTP Authentication is easily accomplished at the web server level (by way of .htaccess with Apache or inside your nginx configuration file) but did you know you could pull it off inside of a PHP script? You bet your butt you can! First, you will need to interrogate the _SERVER variables that contain the username and password. If they are set (and are...

Read Full Article →