Category Archives: PHP

Validating email with PHP 5.2 or higher

For years, we’ve all used variations on various methods to validate email, usually, some complicated regular expression (regex) that checked the format for us.

Since php 5.2, we’ve had a much simpler built in filter.

10
11
12
13
14
15
16
17
18
function checkemail($femail) {
	if (filter_var($femail, FILTER_VALIDATE_EMAIL)) {
  		// The email address is valid
  		return true; 
	} else {
  		// The email address is not valid
  		return false; 
	}
}

It’s much easier, cleaner and above all, faster.

PHP Wrappers, Reading XML with php://input

Most of us are used to utilizing the request object in PHP to access the associative array created by form posts. Most traditionally, $_GET, $_POST or if you are really lazy like me, $_REQUEST.

Newer versions of PHP (5.1+) also allow direct access to input streams. It’s a little less memory intensive than traditional ways, though you should be aware that it cannot be used when forms are submitted with enctype=”multipart/form-data” because of their reliance on writing submitted resources to disk.

More impressively, it allows access to ANY data input to PHP

I recently wrote a server API that had to accept XML objects and parse them for data.

10
11
12
$xml_object	= file_get_contents('php://input');	# read submitted xml
$xml		= simplexml_load_string($xml_object);	# extract contents into useable form
$id 		= $xml->id;

Once the php input data is stored as an object, you can parse it with the built in PHP function simplexml_load_string which immediately makes individual node values accessible by their name.