Categories
PHP

Tips for a Speedy Zend Studio

I found a good article on how to speed up your Zend Studio (eclipse based) on Zend’s website. Hopefully everyone else will find it as helpful as I found it to be:

http://kb.zend.com/index.php?View=entry&EntryID=480

Categories
PHP

Zend Server and Zend Studio9

If you have Zend Server installed and you have an instance of MySQL that didn’t come with Zend Server, then Zend Studio will try to connect to the one that came with Zend Server. I discovered this the hard way when my PHPUnit tests kept failing in Zend Studio but ran perfectly from the command line (I had PHPUnit installed from PEAR and the one that came with Zend Studio).

So I decided to make Zend Server connect to my default MySQL instance instead of uninstalling Zend Server (because I want to play with it). For those with the same problem, you can do this:

# Rename Zend Studio's socket file to something else
# If you didn't choose the default, installation path then 
# use the path to that location instead
mv /usr/local/zend/mysql/tmp/mysql.sock /usr/local/zend/mysql/tmp/mysql_old.sock

# My MySQL installation's socket file is located in /tmp
# If your's is different, then you will have to modify the source path

ln -s /tmp/mysql.sock /usr/local/zend/mysql/tmp
Categories
PHP

Validating An Email Address in PHP 5

In PHP 5.2 Zend has added a function called filter_var(). It validates a lot of things for you without having to write any regular expressions or anything else. You do it like this:

if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL) !== false) {
    print 'valid email';
} else {
    print 'Invalid email';
}

filter_var()returns the value back if its valid or false if it is not. And, it doesn’t just validate email addresses. It can validate booleans, floats, etc and sanitize data too.

Here are some links that will be helpful:

http://us2.php.net/manual/en/filter.filters.validate.php
http://us2.php.net/manual/en/function.filter-var.php

Enjoy!

Categories
PHP

PHP – Get a visitor’s IP address

/**
 * This function tries to get the real IP of the visitor even if they 
 * are behind a proxy
 */
function getClientIp()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
Categories
PHP

PHP Inheritance – Calling parent’s functions in child object

Before I begin, let me just say that I have tested this in PHP 5.2. I don’t know if this will work for PHP 5.3. If anyone can confirm that it does, it will be great.

You can do it with parent::someFunctionName(). You can do this from within an overloaded function also. It was confusing for me at first, so I decided to test it out myself. Below is some same code that will help you understand it too.

class SomeParent {
	// we will initialize this variable right here
	private $greeting = 'hello world';

	// we will initialize this in the constructor
	private $bye ;

	public function __construct() 
	{
		$this->bye = 'Goodbye';     
	}

	public function sayHi()
	{
		print $this->$greeting;
	}

	public function sayBye()
	{
		print $this->bye;
	}
	public static function saySomething()
	{
		print 'How are you';
	}
}

class SomeChild extends SomeParent {
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Let's see what happens when we call a parent method
	 * from an overloaded method of its child
	 */
	public function sayHi()
	{
		parent::sayHi();
	}

	/**
	 * Let's call a parent method from an overloaded method of
	 * its child. But this time we will try to see if it will
	 * work for parent properties that were initialized in the 
	 * parent's constructor
	 */
	public function sayBye()
	{
		parent::sayBye();
	}
	/**
	 * Let's see if calling static methods on the parent works
	 * from an overloaded static method of its child.
	 */
	public static function saySomething()
	{
		parent::saySomething();
	}
}
$obj = new SomeChild();
$obj->sayHi(); // prints hello
$obj->sayBye(); // prints Goodbye
SomeChild::saySomething(); // prints How are you
Categories
PHP

PHP and Sabre

What is Sabre?

Sabre is a company that has data of all flight schedules, etc. And, using their system, you can book flights, hotels, rent cars, etc.

Getting PHP to talk with Sabre

I tried PHP Soap and nuSoap. They both didn’t work for me because of their limitations. So I ended up writing a small script of my own that talks with Sabre for me after I realized that the headers being sent by all the SOAP libraries I tried, were not compatible with Sabre’s web services.

Sabre checks the “Content-Type” header in your request. If that is not “text/xml”, you will always get an error, even if your xml is correct.

Here’s a little piece of code that should help with the transport part.  I will leave the generation of XML to you.

/**
 * Sabre class (for connecting to Sabre web services)
 * @author Moazzam Khan 
 * @version $Id$
 */
class Sabre {
	public $host;
	public $port;
	public $timeout;

	public function Sabre()
	{
		$this->timeout = 30;
	}
		
	public function makeRequest($body)
	{
		$header = "POST /websvc HTTP/1.1\r\n"
					. "Host: {$this->host}:{$this->port}
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Content-Type: text/xml
Content-Length: ".strlen($body)."
Pragma: no-cache
Cache-Control: no-cache";
		
		$fp = fsockopen("ssl://".$this->host, $this->port, $errno, $errstr, $this->timeout);
		if(!$fp){
			print "SOCKET ERROR $errstr ($errno)\n";
		} else {
				//send the request
				fputs($fp, $header."\r\n\r\n".$body, strlen($header."\r\n\r\n".$body));
				stream_set_timeout($fp, 30);
				stream_set_blocking ($fp, 1);
				while (!feof($fp)) {
					$line = fread($fp, 2048);
					if (trim(strlen($line)) < 10) continue;
					$output .= $line;
				}
				fclose($fp);
		}
		$ret = explode("\r\n\r\n", $output);
		$ret = explode("\r\n", $ret[1]);
		for ($i=0; $i

		
Categories
PHP

Processing forms in PHP

For this article, I will assume that you (the reader) know what a form is and have a general idea of what needs to be done on the HTML side to submit a form. I will cover a bit about what needs to be done but I will not go into details (it will be enough for you to get through form submissions :))

Among all the languages I have come across processing a form in PHP is the easiest. PHP was made with web development in mind and it shows in its ease of use.  PHP provides you with 3 variables that can be used to access the information sent through a web page. They are :

  • $_POST
  • $_GET
  • $_REQUEST

These variables are already present when PHP’s code is run. You don’t have to do anything special. $_POST contains all variables sent through a post request. $_GET contains all the variables sent through a GET request (in a query string). $_REQUEST contains the information sent through both post and get(query string).

Let’s take a look at an example shall we. Here is an HTML page with a form :

Name:
Email:
Message :

All the form elements are enclosed in between <form> and </form> tags. The attribute action=“index.php” lets the browser know where the form is to be submitted. In this case, it is submitted to index.php. And, method=”post” lets the browser know that the method being used to submit the form is post (and not get). In every form you need one “button” or image that will submit the form. In the above code, it is a button. Now that we know the form we will use to submit the information. Let’s take a look at the PHP page which will process it.


The code is very simple and straight forward. It takes all the information sent through the HTML form and emails it to [email protected] In the HTML form, we had an input field with the name of message :


You can access the value of this field in PHP through the variable : $_REQUEST[‘message’]. If you used the method post (like I did in the code above), you can also access the value of the message field through the variable $_POST[‘message’]. However, $_GET[‘message’] will not contain anything as the method we used in our form was post and not get.

Categories
PHP Uncategorized

Design Patterns – Singletons in PHP 5.x

Design Patterns (and anti-patterns) are techniques of programming. There are a lot of design patterns. It is upto the programmer to pick and choose which patterns to use based on their needs. Singleton is also a design pattern. A singleton is a type of class which can have only 1 object of its kind through the lifecycle of an application. It is very suitable for database, caching, etc. I will use a database class as an example as it is probably the most-widely used class in web development.

Why use a singleton you ask? A popular practice among PHP4’s developers is to make a database object global then use that variable anything a query needs to be run. It works in small applications and even in not-so-big applications. In enterprise applications where you use hundreds (if not thousands) of variables, there is a very good chance that you database object will get mutated or overridden. You also don’t want to have multiple instance of a database class (unless you are running a multi-threaded application).

A database class should be able to connect to a database, run queries, return results and close the connection to the database when it’s done. Keeping that in mind, let’s start writing our database class.

/**
 * Database wrapper
 */
class Database {
	private $_host;
	private $_user;
	private $_pass;
	private $_name;
	private $_conn;
	private $_err;

	/**
	 * Setting the constructor as private will make sure
	 * that the class cannot be instantiated using the
	 * "new" keyword. You can to instantiate it like this :
	 * $db = Database::getInstance();
	 * getInstance() is implemented right after the constructor
	 */
	private function __construct($host, $user, $pass, $name)
	{
		$this->_host = $host;
		$this->_user = $user;
		$this->_pass = $pass;
		$this->_name = $name;
	}

	/**
	 * This function is what makes this whole class a singleton.
	 * It will make sure only one instance of this class is available
	 */
	function getInstance($host='', $user='', $pass='', $name='')
	{
		static $obj;
		if (null == $obj) {
			$obj = new Database($host, $user, $pass, $name);
			$obj->connect();
		}
		return obj;
	}
	/**
	 * Connects to the database
	 */
	function connect()
	{
		$this->_err = null;
		if (!mysql_connect($this->_host, $this->_user, $this->_pass)) {
			$this->_err = mysql_error();
			return false;
		}
		if (!mysql_select_db($this->_name)) {
			$this->_err = mysql_error();
			return false;
		}
		return true;
	}

	function error()
	{
		return $this->_err;
	}

	function user($val=null)
	{
		if (null == $val) return $this->_user;
		$this->_user = $val;
	}
	function host($val=null)
	{
		if (null == $val) return $this->_host;
		$this->_host = $val;
	}
	function pass($val=null)
	{
		if (null == $val) return $this->_pass;
		$this->_pass = $val;
	}
	function name($val=null)
	{
		if (null == $val) return $this->_name;
		$this->_name = $val;
	}
}

So, we wrote a class called database and made its constructor private so you can’t instantiate it using the “new” keyword. We also wrote a method/function for this class called getInstance() which will return a database object. getInstance() has a local static variable called $obj. It checks if this variable is null. If it’s null then that means there is no object of the type “Database”. So, it creates an object and assigns it to $obj. It also returns the object to the code that called it. Setting permissions of private, protected and public could not have been done in PHP 4, which frustrated a lot of OOP enthusiasts. PHP 5, however, has the capability of doing it and thus fulfilling one of OOP’s main goals – encapsulation.

The first time  an object of the class Database is instantiated, it will have to pass all the variables required to make a database connection. Its subsequent calls need not do that.

// First call
$db = Database::getInstance('localhost', 'root', '', 'myDB');

function hello()
{
	// Second call
	$database = Database::getInstance();
}

Both $db and $database point to the same object. Any changes made to $database will be reflected in $db also. This eliminates the use of global variables for quite a few things (especially our database class).