PHP Tips & Tutorials

Write and Run PHP with HTML

Pure HTML is static text files with dead content that want everything but to change. However by the help of a service scripting language such as PHP, HTML can be dynamic and changes every time you make a different request to the server.

PHP is born with HTML rendering in mind. So it’s plain easy to write PHP from inside HTML. Just use:

<?php //php code goes here ?>

For example, we have a variable named $url to be the URL address of a web document, let’s run and present it inside with HTML so that the client browser gets the actual value dynamically:

<a href="<?php echo $url; ?>">pricing table</a>

There you go. To run PHP around HTML, just enclose the code with <?php … ?>.

.htaccess Tutorials & Tips PHP Tips & Tutorials


The last time I end up with hundreds of HTML files with PHP codes dispersed in them. Tried to rename them all to .php but failed. To use them and enable the php code within, I have to run the HTML files as PHP.

How Apache web server works in resolving .php requests

Apache gets HTTP requests from client browsers, trys to connect a special file extension of the script requested such as .php to a mime type, in turn affiliates the mime type to a installed module, filter or extension such as PHP and passes the request to it.

In case Apache failed to find the right processor to parse the requested document, it presents the raw content of the file to client which is why we have websites showing the whole bunch of server side code in the browser.

Therefore, now that:

  1. You requests in browser address bar.
  2. Apache detects that the mime type of .php is application/x-httpd-php.
  3. PHP engine is configured to run documents with that mime type.
  4. So it parses it and passes the results to Apache.
  5. Apache sends the results to client.

Pretty much.

Modify .html files as also application/x-httpd-php – the Solution to Run HTML as PHP!

To make PHP engine run .html and the php code in it, you only have to declare a different mime type than .html already is. Find or create a file of .htaccess (there’s a leading dot) in the directory in which you want all .html files to be parsed as .php and append or write the following text:

AddType application/x-httpd-php .htm .html
AddHandler x-httpd-php5 .htm .html

That’s it! Also you may use php5-script instead of x-httpd-php5 in some cases. And you may also try this with regular expressions to better match specific criteria:

<FilesMatch "\.(htm|html|php)$">
SetHandler application/x-httpd-php

Looking to run PHP in HTML code? You mean writing and running PHP code from HTML right?

SQL / MySQL Tips and Tutorials

Create SQL Auto Increment Column (ID: Primary Key) in Table

With database development, a perfect data structure paradigm is that data records should all be uniquely distinguishable from each other. Therefore when you are designing and creating data fields or columns for an entity, you must always have an identifying column or field for each and every of the records stored in a table, enabling the identification of any record upon finding the unique value.

We usually call it the ID column. And it’s made auto incremental so that whenever there’s a new record or data entry inserted (INSERT INTO), its value of this column is auto incremented by 1 after the max of the existing values.

Not only that, after it’s auto incremented upon every insertion, it’s also made the Primary Key of the table. In essence, a primary key column contains the unique ID for each record, facilitating data indexing.

Follow me with MySQL and a faked table ‘workers’ as example for how to create, modify or add auto incremented field in SQL.

SQL Auto Increment Creation

You have at least 2 approaches for creating an auto increment column:

  1. With phpMyAdmin which most hosting providers come with, just make sure you have selected auto_increment for the column. Preferably you would also check it as a Primary Key column.
    auto_increment & primary key
  2. With manual SQL table creation, append ‘AUTO_INCREMENT PRIMARY KEY‘ in the column description:
    CREATE TABLE `workers` (
    	`name` VARCHAR( 255 ) NOT NULL ,

Alter a column to be auto increment

To modify an existing integer column to be auto incremented in an existing table:

  1. Either edit the column via table Structure panel in phpMyAdmin,
  2. Or run the following SQL query:

    One note thought, that it’s a must to include all previous attributes (such as SMALLINT(5), UNSIGNED and NOT NULL) of the column if you do not want to annul them after the alteration.

    Very probably, if you are making an ID column that can be indexed as primary key, you would want to append one more attribute: PRIMARY KEY.

Create a new column to be auto increment

Any table without an auto incremental column that is the primary key is just not healthy. It’s data butcher. You’ve got to have one for all of them, buddy.

  1. Either adding a new column and specify auto_increment for Extra in table Structure panel in phpMyAdmin,
  2. Or run the following SQL query for an existing table faked as ‘workers’:

    PRIMARY KEY at the end of the query is not essential if you also want to make the new column to be an ID column.

Free PHP Classes & Library PHP Tips & Tutorials

PHP: File Upload Script (HTML Form + PHP Handler Class)

It’s sometimes cumbersome to handle uploaded files – checking if it is really uploaded, moving and renaming. Why not writing all these chores into a class and make our own file upload script?

First we are going to create a simple class to handle uploaded files and move them to some place we designate for convenient access.

The PHP Class (PHP5, Uploaded.class.php)
class Uploaded {
	private $field_name = '';
	// $field_name is the name of the input in uploading form
	public function __construct($field_name) {
		$this -> field_name = $field_name;
	// $path is the path to the directory where
	// the uploaded file you want stored.
	// $primary_name is the primary part of the
	// file name you want the new name of the uploaded file to be
	// such as 'song' with 'song.mp3'. The extensions part of the
	// new name will be determined from that of the uploaded one.
	public function getFileName($path, $primary_name = '') {
		if (empty($path)) {
			return false;
		if (empty($primary_name)) {
			// Use microtime() as temporary file name if no $primary_name is given
			$primary_name = microtime();
		if (is_uploaded_file($_FILES[$this -> field_name]['tmp_name'])) {
			$client_name = basename($_FILES[$this -> field_name]['name']);
			$ext = substr($client_name, strrpos($client_name, '.'));
			$server_name = $primary_name.$ext;
			if (file_exists($path.$server_name)) {
				// deleting any existing files with the same name here
				// so that the old file can be updated this way.
			if (move_uploaded_file($_FILES[$this -> field_name]['tmp_name'], $path.$server_name)) {
				// The new name of the uploaded file will be returned
				// for access and retrieval of it.
				return $server_name;
		return false;

To adapt this class to PHP4, read this.

<form enctype="multipart/form-data" method="post" action="upload.php">
	<input type="file" name="photo" />
	<button type="submit" name="submit">Submit</button>

Fair enough, now we know browsers are going to send upload.php a file accessible in $_FILES via ‘photo’.

The PHP (upload.php)

Now we will use the Uploaded class (Uploaded.class.php) to handle the file sent from the HTML uploading form above.

if (isset($_POST['submit'])) {
	$myPhoto = new Uploaded('photo');
	$photoFileName = $myPhoto -> getFileName('uploaded/photos/', 'new_name');

The uploaded file will now be all ready and accessible in uploaded/photos/new_name.ext (ext is whatever file extension the original file has) with $photoFileName containing its new name.

Free PHP Classes & Library PHP Tips & Tutorials

PHP: Resize Image and Store to File

While there are a lot of methods for you to resize images with php, we will be using extension gd this time. Make sure you or your hosting company has installed it in the php distribution by running

if (extension_loaded('gd')) { // return true if the extension’s loaded.
	echo 'Installed.';
} else {
	if (dl('')) { // dl() loads php extensions on the fly.
		echo 'Installed.';
	} else {
		echo 'Not installed.';

If the output is ‘Installed.’, let’s proceed to resize some images in php.

This image resize script is meant for shot photos because it works better with bitmap images such as .jpg and .bmp. If you need to keep transparency in the output, the code below will not help you.

PHP Resize Image Class

Basically, this class is created with the source image ($originalFile, the full path to the image) to be resized. When you initiate method resize() which takes in 2 parameters, new width ($newWidth) and the target file ($targetFile, full path to the destination image file) that would be storing the resized image, it goes like this:

  1. Get the original width and height of the image.
  2. Calculate the new height given the new width – you could easily tweak the code yourself to resize the image by a new height.
  3. Resize the image by the help of gd.
  4. Store the resized image in $targetFile, optionally erasing the old file before dumping the data because chances are you just want to resize the image and don’t need the old version anymore. However, if it’s just a temporary resize, make $targetFile different from $originalFile.
Class (PHP5):
class ImgResizer {
	private $originalFile = '';
	public function __construct($originalFile = '') {
		$this -> originalFile = $originalFile;
	public function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		$src = imagecreatefromjpeg($this -> originalFile);
		list($width, $height) = getimagesize($this -> originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
		imagejpeg($tmp, $targetFile, 85); // 85 is my choice, make it between 0 – 100 for output image quality with 100 being the most luxurious
Class (PHP4):
class ImgResizer {
	var $originalFile = '';
	function ImgResizer($originalFile = '') {
		$this -> originalFile = $originalFile;
	function resize($newWidth, $targetFile) {
		if (empty($newWidth) || empty($targetFile)) {
			return false;
		$src = imagecreatefromjpeg($this -> originalFile);
		list($width, $height) = getimagesize($this -> originalFile);
		$newHeight = ($height / $width) * $newWidth;
		$tmp = imagecreatetruecolor($newWidth, $newHeight);
		imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		if (file_exists($targetFile)) {
		imagejpeg($tmp, $targetFile, 85);
Class usage

$work = new ImgResizer('img/me.jpg'); // me.jpg (800x600) is in directory ‘img’ in the same path as this php script.
$work -> resize(400, 'img/me.jpg'); // the old me.jpg (800x600) is now replaced and overwritten with a smaller me.jpg (400x300).

// To store resized image to a new file thus retaining the 800x600 version of me.jpg, go with this instead:
// $work -> resize(400, 'img/me_smaller.jpg');


As I have said, you might want to resize the image by a new height and calculate the width instead of going the other way around as I’ve done thus far, and it’s easy to make your tweak in the class above because height and width are fundamentally the same in dimensions, and no one’s more privileged over the other.

WordPress How To

Update your theme to WordPress 2.7 with Comments Threading and Paging

Well dismiss me if I’m a little too late for this but just now I encountered this client who needs to update a wordpress theme, the comments section or comments.php to be precise, to accommodate some of the new features introduced in WordPress 2.7, comments threading and comments paging.

The easy way – for new themes

Just go download a distribution of wordpress 2.7, and unzip the package (install it, probably), click your way into wp-content/themes/default (the Default theme) and open comments.php with your favorite dev editor.

There’s the code you need to implement comments threading and comments paging in wordpress 2.7 in case you need to create new themes dedicated for version 2.7. Also, you have to explicitly enable threaded comments in wordpress administration panel: Settings –> Discussion –> Other comment settings –> Enable threaded (nested) comments. It’s disabled by default.

Update old themes to accommodate the threading feature

For old wordpress themes, if yours or your client’s blog has already updated to wordpress 2.7 (has to, because this change may make your theme backward-incompatible), to integrate the comments threading and paging, you need to follow these steps by Will to edit 2 files in your theme, header.php and comments.php.

This tiny tutorial is written and human friendly, you won’t be bitten. 😉


HTML Form doesn’t upload the file?

You had the <input type=”file” /> in place, however it just doesn’t seem to be uploading at all at the client side. After choosing a rather big file, the form submission and page reload finish in seconds, what’s wrong?

Well, it’s almost certain that you have forgotten something. Try adding property enctype to <form>:

<form enctype="multipart/form-data" method="post"> ... </form>

Should be working now. Try it again!

PHP Tips & Tutorials

PHP4 Class – differences from PHP5

Creating a rather simple custom CMS on my client’s server, everything seems ok until I start testing out some of my ready made proprietary PHP classes. The problem is that I make things in PHP5 and all the classes are in PHP5 format.

Quickly searched and scanned through some old tutorials for PHP4 about creating classes. It’s some radical changes indeed. Just to soothe your possible frustrations when migrating PHP5 classes into a PHP4 platform:

  1. PHP4 classes don’t have scope operators such as private, public or protected.
  2. PHP4 constructional function should be the same name with that of the class. __construction won’t work.
  3. Class variables in PHP4 classes are declared with the keyword ‘var’ rather than private or public.

I thought I might write this down for those who are rewriting PHP5 classes for obsolete implementations of PHP such as PHP4.

PHP Tips & Tutorials SQL / MySQL Tips and Tutorials

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax …

Scratching your head for a mystic error in your SQL query? No matter how you look into it, it just seems right and should by the God’s name work as you have wished. But it doesn’t and keeps pumping out annoying SQL syntax errors.

Don’t panic, I have a few tips on this that might make your life easier:

  1. Search on Google by your primary query syntax such as ‘SELECT FROM’ or ‘INSERT INTO’ to see how correct queries are written by others.
  2. Make sure you don’t have any typo of those table names and field names.
  3. Try quoting (or bracketing) table names and field names with
    ` `

    And values (user provided, changeable data) with

    ' '
  4. Try tidying and indenting your query in manners such as:
    $results = mysql_query(
    	"INSERT INTO `offers` (
    	) VALUES (

    So that you could more easily spot the bugs.

  5. Make sure you don’t have a comma at the end of the last item. This happened to me quite a few times.
  6. Escape or prepare the string before committing the query.

If instead the querying script (possibly in php) giving zero results without any mysql errors at all, you have to remove any error suppression tokens such as ‘@’ and explicitly print out the error message with:

$error = mysql_error(); // PHP4
$error = $mysqli -> error; // PHP5

So that you can debug the query.

PayPal & Ecommerce

PayPal Policy Update, 2009/01

PayPal is by far the most popular international merchant service. The newest update of their policies is carried out through the end of last year, 2008, and a lot of provisions are effective ever since. Some of the key points include:

  1. You may not use PayPal service for prohibited activities involving gambling, gaming and/or any other activity with an entry fee and a prize such as casino games, sports betting, horse or greyhound racing, lottery tickets. You get the idea. However, there might be some who can use PayPal service in such activities because they have the prior approval by PayPal.
  2. More countries including Italy, Ireland, Belgium, Austria, Denmark, Greece, Portugal, Poland, Finland, Hungary, Czech Republic, Luxembourg, Singapore, Hong Kong and Mexico are listed so that users from these countries now can add funds to their PayPal account via bank transfer, with the same name of the bank account as that of the PayPal account. (Topping Up)
  3. With those who use PayPal on eBay listings as a checkout are obligated to: 1) unconditionally accept PayPal payments if the customer chooses to pay via PayPal, 2) accept all payments methods customers choose that PayPal can handle, 3) must have a premier account or business account, 4) must not charge the seller additional fees for paying via PayPal.

Above are just my personal interpretation of this update and doesn’t constitute any formal advice. For precise update description and official texts please log into your paypal account and click to the statements via What’s new.