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

Posted in PHP by Moazzam. No Comments

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

Virtual hosts look up taking too long in OSX Lion

If your mac (OSX Lion) is taking too long to get pages with your local web server and you have virtual hosts setup, then it’s probably because it is checking the DNS servers before it checks for it in your /etc/hosts.

The way to resolve this is to have a ::1 entry in your hosts file for every 127.0.0.1 entry. Here’s an example:

127.0.0.1         example.com
::1               example.com

You will notice I have 2 entries for example.com. One is IPv4 and the other is IPv6. My requests to the local web server take almost no time at after I did that. I think Lion tries to use IPv6 before it uses IPv4 and since it doesn’t find any entries for that in your hosts file, it goes to the internet searching for that domain.

Posted in Uncategorized by Moazzam. No Comments

Some information on booking flights with Sabre

A lot of people contacted me asking about how Sabre works, etc. So, I decided to post this here. The way it works is:

  1. You sign up with Sabre for a web services account and you they will give you an IPCC, username and passwrord that you use for communicating with their web services.You will send over the username and password for only authentication request. However, you will use your IPCC in all the requests you make.
  2. Your initial request should be a SessionCreate request. You will provide your username and password in it. Upon success, you will receive a binary token. You will use this token in all the subsequent requests you make.
  3. Your subsequent requests will depend on what you want to do and the services you have access to. Sabre has multiple flight services that you can communicate with. You will need to contact them, explain your needs and ask what service will be best for you. LowFareSearch and BargainFinder are probably the ones that are most used.
  4. After you are done selecting the flight, etc. You will send a request to AirBook (if I remember the name correctly) to book a flight. And, there’s other services you might want to use to pass passenger information, etc.
  5. After you are done, you end the session with a call to SessionCloseRQ.

When you get an account with Sabre, you will be able to look at request and response formats for  the for the web services over here: https://drc.sabre.com/oer/


 

Nexus S and TMobile data connection

Here’s an interesting tidbit. If you go out of the country and come back. Nexus S won’t automatically connect to TMobile’s 3G or edge network. You have to switch it off and start it again for it to connect to the data network. It will, however, let you make phone calls, and send and receive SMS without restarting it.

Writing good Javascript code

Here’s a link someone I know found on how to write good Javascript code. It talks about how to make your javascript run faster and with a small footprint. It also talks about how to avoid memory leaks.

http://code.google.com/speed/articles/optimizing-javascript.html

Posted in Uncategorized by Moazzam. No Comments

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:

1
2
3
4
5
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!

PHP – Get a visitor’s IP address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * 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_sFORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

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

PHP and MySQL

Someone recently sent me a message asking me to explain how to use a database with PHP. So, here it is as an article so everyone can take advantage of it.

The following 5 things will be enough for a lot of PHP programmers (and get you started).

  • Connect to MySQL
  • Select the database you want to work with
  • Read information from it
  • Insert, update or delete information in it
  • Close the connection

Connecting To MySQL And Selecting The Database

<?php
/** 
* This function will attempt to make a persistent connection to MySQL or die() with a message
* It takes 3 parameters 
*  - hostname or IP to connect to
*  - username 
*  - password (assuming a password is required)
*
* The values I used are the ones that will work by default (unless your installation was different)
* You MUST make sure that the database server is running and you have the right username and 
* password for this to work (but that's obvious)
*/
mysql_pconnect('localhost', 'root', '') or die('Could not connect to the database server');
 
/**
* Now that we are connected and logged in, we select the database we want to use
* And, we kill the script if there is a problem selecting the database.
*
* If this function call fails, that generally means you dont have access to the database.
* Go back to MySQL administration and make sure your username has proper permissions
*/
mysql_select_db('database_name') or die('Could not select the DB');

Regardless of what you want to do (insert, select, update or delete) you will always need to first connect to the MySQL server and select the database you want to work with.

Let’s say we want to maintain a list of contacts. We want to store their first name, last name and their email. For this, we will need to create a table. Then, we can insert our contacts in it and get them when we need to

Creating A Table

<?php
 
// ... connect to the MySQL server and select the DB ....
 
/**
* You will need to learn SQL to communicate with MySQL. I won't get into SQL here because that's a whole another tutorial
* I put this query in a variable in case I need to print it out later when debugging. I find it easier to debug with this even  
* in IDEs when stepping through the code
*/ 
$sql = ' 
  CREATE TABLE contacts (
    id int AUTO_INCREMENT,
    first_name varchar(255),
    last_name varchar(255),
    email varchar(255),
    primary key (id)
  )
';
 
/**
* mysql_query() is the function you pass your queries to, so they can be run on MySQL server.
* 
* If  your query contains an error, then mysql_error() will get you that error.
*/
mysql_query($sql) or die('Error occurred:'.mysql_error());

Now that we have the table, let’s insert a contact in there.

Inserting Into The Database

<?php
// ... connect to the MySQL server and select the DB ....
 
/**
* This is what insert statements look like for MySQL
*/
 
 
$sql ="INSERT INTO contacts(
    first_name, 
    last_name, 
    email
  ) VALUES(
      '".mysql_real_escape_string('John')."', 
      '".mysql_real_escape_string('Lango')."', 
      '".mysql_real_escape_string('john@example.com')."'
  )";
 
/**
* As you may have realized, the function you will be using the most is mysql_query()
* You perform all your database operations with it. 
*
* You will perform update and delete this way too. If you need help with the queries for those
* let me know. If enough people request it, I will write another article for it or modify this one 
* to include it. 
* 
* You will also notice I used mysql_real_escape_string() above in the SQL query.
* This function escapes certain special characters in the values you want to insert so
* people don't hijack your database :). And, your script won't break when someone
* uses a single quote in their first name.
*/
mysql_query($sql) or die('insert failed');

Now that we have a table and we have some data in it. Let’s try reading that data.

<?php
/** Write query */
$sql = 'select * from contacts';
/** Run it */
$result = mysql_query($sql) or die('Select query failed');
/** 
* Fetch the results 
* When you fetch the results, you will see that here $row has your table field names as keys 
*/
while ($row = mysql_fetch_assoc($result)) {
   print "First Name: {$row['first_name']} <BR>\nLast Name:{$row['last_name']} <br>\n Email: {$row['email']} <p>\n\n";
}

When you open a persistent connection, it stays open. When you fresh the page or when you need to connect to the DB again, the same connection is used instead of creating a new one, which is good because you don’t want to exhaust all your available connections. So, you will usually not have to close the connection. However, if for some unforeseen reason you need to close a connection to MySQL, here’s how to do it.

Closing The Connection

<?php
 
/**
* You will need to save the resource returned by mysql_pconnect() to a variable
*/
$conn = mysql_pconnect('localhost', 'root', '');
// ... select the DB .. run some queries, etc ...
/** 
* And, this is the function call to close the connection. It takes the resource $conn 
* as a parameter (so it knows which connection it's closing)
*/
mysql_close($conn);
Posted in Uncategorized by Moazzam. No Comments