You Are Here Home > PHP

PHP

Learning PHP – best PHP books

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here is one…

Learning PHP – best PHP books

PHP and MySQL Web Development (4th Edition) (Developer’s Library) (Hardcover)
by, Luke Welling and Laura Thomson

This book is one of the best books on PHP and MySQL. It starts with introductions to PHP and MySQL and then shows you how to write common applications from scratch using these technologies. You will learn how to write a shopping cart, a content management system (CMS), a web based email service, a mailing list manager, a forum application, and more.
Some other useful topics covered in this book are:
How to run an E-Commerce site, Session management, user login and registration, generating images and PDF documents on the fly with PHP, using network protocols with PHP, Object Oriented Programming (OOP), regular expressions, etc.
_________________________________________________

Advanced PHP Programming
by, George Schlossnagle

This book will teach you advanced techniques required to make a large scale web application (web site), there are many advanced topics covered in this book such as:
Various caching techniques using PHP, unit testing, good API design, interacting with remote services, Object Oriented Programming (OOP) through design patterns, Session handling, and more.
_________________________________________________

PHP|Architect’s Guide to PHP Design Patterns
by, Jason E. Sweat

This book covers many of the Design Patterns that are common in developing websites and is one of the first PHP Design Patterns books. Code samples are in PHP4 and PHP5.
The book covers 16 different design patterns including:
The ValueObject Pattern, The Factory Pattern, The Singleton Pattern, The Registry Pattern, The MockObject Pattern, The Strategy Pattern, The Model-View-Controller Pattern, and many more.
_________________________________________________

PHP|Architect’s Guide to PHP Security
by, Ilia Alshanetsky

This book will teach you how to make secure and reliable web applications, the author is one of the contributors to PHP programming language core.
Topics covered are: Input validation, Cross-Site Scripting (XSS) attacks prevention, Command Injection attacks prevention, SQL Injection attacks prevention, Code injection attacks prevention, and more.
This is a MUST read book for PHP developers.
_________________________________________________

Mastering Regular Expressions (3rd Edition)
by, Jeffrey E F Friedl

This book is the best book on Regular Expressions. If you’re having trouble learning Regular Expressions,this book will help you grasp the concept and master them.
Plus, the 3rd edition has an entire chapter dedicated to PHP.

Learning PHP – best PHP books
Comments (0)   Filed under: PHP,Programming,Web Development   Posted by: Codehead

PHP Date/Time Handling Made Easy; a beginner’s guide to PHP time and date handling

When I started with PHP, I was a bit confused about this subject so this will hopefully help a beginner a lot.

UNIX Timestamp

UNIX Timestamp (or Unix time or POSIX time) is the number of seconds since the midnight of January 1, 1970 UTC.

You can get the current timestamp with PHP’s time() function:

<?php
	echo time();
?>

This will show you the number of seconds since January 1, 1970 UTC.

Assume that you are creating a blogging application using PHP and you want to save the time/date of the posts
with them, in your database, you can create a table like this:

CREATE TABLE IF NOT EXISTS `post` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
  `title` varchar(250) NOT NULL DEFAULT '',
  `body` text NULL DEFAULT '',
  `ip_address` varchar(30) NOT NULL DEFAULT '',
  `date` int(11) DEFAULT NULL,
  `last_update` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY  (`id`),
  KEY `date` (`date`),
  KEY `last_update` (`last_update`)
);

Now, a query to insert a blog post will look something like this:

<?php
 
$query = '
	INSERT INTO post
		(
			user_id,
			title,
			body,
			ip_address,
			date,
			last_update
		)
	VALUES
		(
			' .$user_id .',
			' .mysql_real_escape_string($_POST['title']) .',
			' .mysql_real_escape_string($_POST['body']) .',
			' .mysql_real_escape_string($_SERVER['REMOTE_ADDR']) .',
			' .time() ',
			' .time() '
		)
';
?>

(I left our details about filtering $_POST array out of this, you might want to filter the $_POST array a bit)

This way the query to get all the posts, sorted by date would look like:

SELECT *
FROM post
ORDER BY date DESC

A query to get all the posts from last 24 hours would look like:

<?php
$start_date = time() - (24 * 60 * 60);
$query = "
   SELECT *
   FROM post
   WHERE date >= $start_date
   ORDER BY date DESC
";
$result = mysql_query($query);
/* ... */
?>

A Performance Tip

If you don’t pay attention, you will end up with 100s of calls to time() throughout your application and we
know that function calls have overhead so what do you do?

We can call time only ONCE and save the results in a constant which will be global also, just like the time()
function:

<?php
	define('TIME_NOW', time());
?>

Converting UNIX Time To Readable Time

How do we show what time it is? That is in a format like: Mon, 15 Aug 2005 15:12:46

There is another useful function in PHP for this purpose and that is the date() function.

First you must set a default system timezone, it’s very simple, way on top of your scripts, (in your main include
fine perhaps) call this:

<?php
	date_default_timezone_set('EST');
?>

Don’t worry if you don’t understand what’s happening, this might help clear out a bit of the confusion:
http://www.php.net/manual/en/function.date-default-timezone-set.php

Again, read on and just add the line above on top of your script…

Now back to business, here is a simple call to the date() function:

<?php
	echo date('D/M/Y', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

This will show you something like:

Sun/Jan/2010

You can see that the first argument is a format in which you want the date to be, shown and the second argument is the timestamp of the date, if you don’t provide the second argument, the current timestamp will be used.

Here is another example that shows the time also:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

Output:

Sun/Jan/2010 03:12:46 PM

These are some more examples: (taken from here)

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
 
 
// Prints something like: Monday
echo date("l");
 
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
?>

I suggest that you read this page:

http://php.net/manual/en/function.date.php

Tip For Using The date() Function

You shouldn’t have lines like:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

All over your code, why?

Because if you decide to change the way you show date, then you have to go around and edit all the lines containing:

<?php
	echo date('D/M/Y h:i:s A', TIME_NOW); /* TIME_NOW was explained earlier in this same post */
?>

To fix this, you could have a constant containing your date format string like:

<?php
	define('DATE_FORMAT', 'D/M/Y h:i:s A');
?>

Then in your code, you do this:

<?php
	echo date(DATE_FORMAT, TIME_NOW);
?>

Now if you want to change the format of the date throughout your PHP application, you can just edit the line with:

<?php
	define('DATE_FORMAT', 'D/M/Y h:i:s A');
?>

And it will magically change all of them!

Better yet, I would have a function like:

<?php
 
	function display_date($timestamp = NULL) {
		echo date('D/M/Y h:i:s A', $timestamp);
	}
 
?>

Or even better yet, you could have the function return the string as a value, so you have even greater control:

<?php
 
	function get_date_string($timestamp = NULL) {
		return date('D/M/Y h:i:s A', $timestamp);
	}
 
?>

Then call it like:

<?php
	echo get_date_string(TIME_NOW);
?>

The Pain Of Finding Out The Timestamp From A Formatted Date String

I made the pain part up, fortunately there is a function that does this very easily, it is strtotime()

<?php
	echo strtotime('9/25/2010 02:28:30 PM');
?>

And bam! magically, you will get the timestamp, it doesn’t end there, you can do things like this:

<?php
	echo strtotime('today'), "\n";
	echo strtotime('today + 1 day'), "\n";
	echo strtotime("now"), "\n";
	echo strtotime("10 September 2000"), "\n";
	echo strtotime("+1 day"), "\n";
	echo strtotime("+1 week"), "\n";
	echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
	echo strtotime("next Thursday"), "\n";
	echo strtotime("last Monday"), "\n";
?>

Read more about strtotime() here:

http://php.net/manual/en/function.strtotime.php

How To Display Dates Like ‘x days ago’?

I got this function form one of the comments on PHP documentation, it’s very nice and does just this:

<?php
	function date_range($timestamp) {
		if( $timestamp < 1 ) return '';
		$difference = time() - $timestamp;
		$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
		$lengths = array("60",     "60",     "24",   "7",   "4.35", "12",    "10");
		for($j = 0; $difference >= $lengths[$j]; $j++)
		$difference /= $lengths[$j];
		$difference = round($difference);
		if($difference != 1) $periods[$j].= "s";
		$text = "$difference $periods[$j] ago";
		return $text;
	}
?>

And call it like:

<?php
	echo date_range(strtotime('today - 1 day'));
?>

Back To The Blog Post Example

I will show you a quick example of displaying those blog posts we talked about in the beginning of this article with a nice formatted time:

<?php
$start_date = time() - (24 * 60 * 60);
$query = "
   SELECT *
   FROM post
   WHERE date >= $start_date
   ORDER BY date DESC
";
$result = mysql_query($query);
while ($post = mysql_fetch_assoc($result)) {
	echo "<strong>{$post['title']}</strong><br />";
	echo "{$post['body']}<br />";
	echo "Published: " .date_range($post['date']) ."<br /><br />";
}
?>

This is very simplistic but demonstrates the concept.

I hope this helps. If you liked it, help spread the word, it’s always appreciated.

Good Luck :)

PHP Date/Time Handling Made Easy; a beginner’s guide to PHP time and date handling
Comments (1)   Filed under: PHP,Server Performance,Web Development   Posted by: Codehead

AJAX – Beginner AJAX Tutorial – Creating a simple AJAX website with example

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

Beginner AJAX Tutorial – Creating a simple AJAX website with example

What you need to know before you read this tutorial:

You need to read the previous two tutorials, they are located at here:
Beginner Ajax Tutorial
Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

(It will only takes a few minutes and will catch you up to this point.)

We are going to make a simple AJAX website with 4 pages.

A few things to note:

1. We are going to make a website that works just fine for users without JavaScript.
2. The back-end will be PHP, it might not be the best way to implement but it’s simple and effective for the purpose of this tutorial.
3. You will be able to download the complete source code for this AJAX tutorial.
4. In this AJAX tutorial the browser back button is ‘broken’, and users can’t bookmark internal pages of this website; fixing these issue is the topic of the next tutorial.
5. In this tutorial I’m going to demonstrate what can be done with AJAX in a simple way using inline JavaScript; separating presentation and behavior will be the topic of later tutorials.
Inline JavaScript looks like this:

<a href="?page=about" onClick="return get_page('about');">About us</a>

Let’s start with the back-end

Here is the directory structure of this website:

/index.php
/templates/main.php
/templates/home.php
/templates/about.php
/templates/services.php
/templates/contact.php
/images/few images
/yui/our yui code libraries

Here is the index.php source code:

<?php
 
	$templates_folder = 'templates/';
 
	if( !isset($_GET['page']) ) {
		$_GET['page'] = 'home';
	}
 
	/**
	 * Because we are going to get the content of a file based on user input and display it
	 * to the user, we use basename function to make sure a sneaky user doesn't try
	 * something like ../../ to get a password file or something important.
	**/
	$page = trim(basename($_GET['page'])) .'.php';
 
	$page_file = $templates_folder .$page;
 
	/**
	 * Note: This assumes your templates are static, that is: there is no PHP code
	 * in them, I will write about how to handle that situation later but for now,
	 * let's keep it simple :)
	**/
	if( file_exists($page_file) ) {
		$page_content = file_get_contents($page_file);
	} else {
		$page_content = 'This page doesn\'t exist here.';
	}
 
	/**
	 * If the $_GET['AJAX'] is set, then the request is coming from our JavaScript
	 * get_page() function, so we just send the $page_content to the browser.
	**/
	if( isset($_GET['AJAX']) ) {
		echo $page_content;
	} else {
		include $templates_folder .'main.php';
	}
 
?>

What it does is straightforward and you can understand the code just by reading it.
But here is how it works:

1. It checks the contents of the $_GET['page'] variable for the name of the page a visitors wants to visit and assigns it to $page.

$page = trim(basename($_GET['page'])) .'.php';
 
$page_file = $templates_folder .$page;

$page_file now contains the exact path to our template.

Also note that, this part of the code:

if( !isset($_GET['page']) ) {
	$_GET['page'] = 'home';
}

Makes sure that the home page is the default page, and if $_GET['page'] is empty it assigns ‘home’ to it.

2. It checks if the page exists in the templates folder.

if( file_exists($page_file) ) {
	$page_content = file_get_contents($page_file);
} else {
	$page_content = 'This page doesn\'t exist here.';
}

If it exists then it assigns it’s content to $page_content variable if not an error message that this page does not exist.

3. It checks the content of $_GET['AJAX'] variable and if its set, the request is coming from our JavaScript code:

if( isset($_GET['AJAX']) ) {
	echo $page_content;
} else {
	include $templates_folder .'main.php';
}

If it is coming from our JavaScript code then it only prints out the content of the page, but if not, it prints the main.php template.

Main.php source code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Sample AJAX-XHR Website</title>
</head>
 
<body>
 
		<?php echo $page_content; ?>
 
</body>
</html>

This is the main.php in it’s simplest format, I omitted the JavaScript.
What it does is just printing the $page_content variable in the page.

Other templates:

They only contain plain HTML code, you will see everything together soon.

The front end

All the JavaScript code goes into main.php, here is the JavaScript code we had so far in the previous tutorial:

	<script type="text/javascript" src="yahoo.js"> </script>
	<script type="text/javascript" src="event.js"> </script>
	<script  type="text/javascript" src="connection.js"> </script>
 
	<script type="text/javascript">
		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death');
		}
 
		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}
 
		function show_progressbar(id) {
			replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
		}
 
		function send_request() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
		}
 
		function test_failure() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
		}
 
		var progress_bar = new Image();
		progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
	</script>

The code we use for this tutorial is similar, we will only replace send_request() and test_failure() with one function, get_page():

	<script type="text/javascript" src="yui/yahoo.js"> </script>
	<script type="text/javascript" src="yui/event.js"> </script>
	<script type="text/javascript" src="yui/connection.js"> </script>
 
	<script type="text/javascript">
 
		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}
 
		function show_progressbar(id) {
			replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
		}
 
		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death.');
		}
 
		function get_page(page) {
			if( page == '' ) {
				/* Do nothing if 'page' is empty, you might want to show some error message. */
				return false;
			}
			show_progressbar('content'); /* Show progress bar while waiting */
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);
			return false;
			/**
			 * return false!
			 * Because this will prevent the browser from navigating to page specified in
			 * the link's href attribute.
			**/
		}
 
		/* Let's preload our progress bar */
		var progress_bar = new Image();
		progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
 
	</script>

get_page() function is very simple, here is what it does:

1. It receives the page name as an argument.

function get_page(page) {
	// ...
}

2. It check if the page variable is empty.

if( page == '' ) {
	return false;
}

Here, this function does nothing if page variable is empty, you might want to show an error message.

3. It shows the progress bar before sending the request to the server, letting the user know that something is actually happening:

show_progressbar('content');

4. It sends the request to server and sets our success_handler and failure_handler as callbacks:

var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);

Note: We are sending a request to:

'index.php?AJAX=true&page=' + page

We set the AJAX variable to true and we set the page variable to the page variable that passed to the function. (It can be ‘about’, ‘services’, etc.)

5. It returns false. Return false will result in any link that uses this function to appear as not working, that is, the browser won’t try to navigate
to the page specified in the links href attribute. Instead of letting the browser navigate to that page we replace the content of the page with JavaScript.

main.php with the JavaScript and a menu:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Sample AJAX-XHR Website</title>
 
	<!-- Usual yui stuff -->
	<script type="text/javascript" src="yui/yahoo.js"> </script>
	<script type="text/javascript" src="yui/event.js"> </script>
	<script type="text/javascript" src="yui/connection.js"> </script>
 
	<script type="text/javascript">
 
		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}
 
		function show_progressbar(id) {
			replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
		}
 
		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death.');
		}
 
		function get_page(page) {
			if( page == '' ) {
				/* Do nothing if 'page' is empty, you might want to show some error message. */
				return false;
			}
			show_progressbar('content'); /* Show progress bar while waiting */
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'index.php?AJAX=true&page=' + page, callback);
			return false;
			/**
			 * return false?!
			 * Because this will prevent the browser to navigate to page specified in
			 * the link's href attribute.
			**/
		}
 
		/* Let's preload our progress bar */
		var progress_bar = new Image();
		progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
 
	</script>
 
</head>
 
<body>
<div id="main-wrapper">
<div id="main-padding">
 
	<h1>Sample AJAX-XHR Website</h1>
 
	<div id="menu">
		<a href="?page=about" onClick="return get_page('about');">About us</a>
		&nbsp; &nbsp;
		<a href="?page=services" onClick="return get_page('services');">Our services</a>
		&nbsp; &nbsp;
		<a href="?page=contact" onClick="return get_page('contact');">Contact us</a>
		&nbsp; &nbsp;
		<a href="?page=home" onClick="return get_page('home');">Home</a>
	</div>
 
	<div id="content">
 
		<?php echo $page_content; ?>
 
	</div>
 
</div>
</div>
</body>
</html>

2 notes:
1. Menu links are like:

<a href="?page=about" onClick="return get_page('about');">About us</a>

Their href attribute is actually pointing to the right page, so users without JavaScript will be able to navigate through these pages, and search engines will have
no problem indexing these pages as well.

2. On the other hand their onClick event is set to call get_page() function and passes the page name as the argument to the get_page().

Here is how it works all together:
http://images.code-head.com/tutorials/ajax/sample-AJAX-XHR-website/

Please note: Ignore the look of this example, the point is the functionality.
You can try turning off your JavaScript and see that the example site still works just fine without it.

Download the complete source code here if you want to take a closer look at everything:
http://images.code-head.com/tutorials/ajax/sample-AJAX-XHR-website/sample-AJAX-XHR-website.zip

If you have questions or suggestions, feel free to reply to this thread.
-Codehead

Update:

I should mention that it’s a long time that I moved on to use jQuery rather than yui and I think jQuery is much nicer and easier to use library. I will hopefully write some tutrials on jQuery.

If you don’t know jQuery yet, download it here and HAVE FUN FOREVER!
Download jQuery

AJAX – Beginner AJAX Tutorial – Creating a simple AJAX website with example
Comments (5)   Filed under: AJAX,JavaScript,jQuery,PHP,Web Development,yui   Posted by: Codehead

AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

In the last AJAX tutorial I wrote about how to send requests to the server and receive the response,
in this short AJAX tutorial I will show you how to show a progress bar to the user when your application is
waiting for the server’s response, so your users will see something is actually happening :)

If you haven’t read the first AJAX tutorial, you’ll find it here:
http://blog.code-head.com/ajax-beginner-ajax-tutorial
It won’t take that long.

Here is the code that we have so far:

<html>
<head>
<title>Beginner AJAX Tutorial - Progress Bar</title>
 
	<script type="text/javascript" src="yahoo.js"> </script>
	<script type="text/javascript" src="event.js"> </script>
	<script type="text/javascript" src="connection.js"> </script>
 
	<script type="text/javascript">
		function success_handler(o) {
			document.getElementById('content').innerHTML = o.responseText;
		}
 
		function failure_handler(o) {
			document.getElementById('content').innerHTML = 'Server or your connection is death';
		}
 
		function send_request() {
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
		}
 
		function test_failure() {
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
		}
	</script>
 
</head>
 
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
 
</div>
</body>
</html>

To show a loading progress bar you need to get a progress bar image, you can get one by searching.

I will use this one:
AJAX progress Bar

Let’s begin

First let’s make our code a little bit nicer and make a new function called, replace_html

		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}

The way it works is that it receives two arguments:
‘id’ is the ID of the container where you want to replace the content
‘content’ is the new content to replace the old content :)

Now let’s rewrite our success_handler and failure_handler to use this function:

		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death');
		}

In success_handler for example, we call replace_html(‘content’, o.responseText); instead of directly
replacing the content of our ‘content’ DIV like: document.getElementById(‘content’).innerHTML = o.responseText;

Why?

First, because we don’t need to write document.getElementById(‘content’).innerHTML = … all over the place and
we encapsulate this into replace_html function.

Second this will centralize our way of changing the content of a DIV, so if later for example we
find a better way to replace a DIV’s content, then we will just change one function and we don’t need
to go through and find all the lines like: document.getElementById(‘content’).innerHTML = … and
change them.

Third, suppose you find out that on one kind of browser innerHTML doesn’t work, then again you
only need to change one function.

So far, all together we have this:

<html>
<head>
<title>Beginner AJAX Tutorial - Progress Bar</title>
 
	<script type="text/javascript" src="yahoo.js"> </script>
	<script type="text/javascript" src="event.js"> </script>
	<script type="text/javascript" src="connection.js"> </script>
 
	<script type="text/javascript">
		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death');
		}
 
		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}
 
		function send_request() {
			var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
		}
 
		function test_failure() {
			var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
		}
	</script>
 
</head>
 
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
 
</div>
</body>
</html>

For our progress bar to show up fast, we have to preload it first, here is a simple way of preloading our progress bar:

		var progress_bar = new Image();
		progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';

This piece of JavaScript code will make an image instance and sets it’s source attribute to our progress bar, this is enough
to force the browser to preload the progress bar in it’s cache.

To display this progress bar when we are waiting for the server’s response, let’s write another function show_progressbar

		function show_progressbar(id) {
			replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
		}

This function receives the ID of the container which we want to show our progress bar in and uses our replace_html
function to display the progress bar.
It simply replaces the content of that particular container with this bit of HTML code:

	<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />

Now we will have to change our send_request and test_failure to use this function and show a progress bar when they are
starting to send a request:

		function send_request() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
		}
 
		function test_failure() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
		}

They simply call show_progressbar with the ID of our content DIV and then send their request to the server.

All together we have this code:

<html>
<head>
<title>Beginner AJAX Tutorial - Progress Bar</title>
 
	<script type="text/javascript" src="yahoo.js"> </script>
	<script type="text/javascript" src="event.js"> </script>
	<script type="text/javascript" src="connection.js"> </script>
 
	<script type="text/javascript">
		function success_handler(o) {
			replace_html('content', o.responseText);
		}
 
		function failure_handler(o) {
			replace_html('content', 'Server or your connection is death');
		}
 
		function replace_html(id, content) {
			document.getElementById(id).innerHTML = content;
		}
 
		function show_progressbar(id) {
			replace_html(id, '<img src="http://images.code-head.com/progress-bars/4.gif" border="0" alt="Loading, please wait..." />');
		}
 
		function send_request() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
		}
 
		function test_failure() {
			show_progressbar('content');
			var callback = { success:success_handler,	failure:failure_handler, timeout: 10000 };
			YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
		}
 
		var progress_bar = new Image();
		progress_bar.src = 'http://images.code-head.com/progress-bars/4.gif';
	</script>
 
</head>
 
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
 
</div>
</body>
</html>

Go ahead and try it here:
http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial-progress-bar.html

This is it for now, on the next AJAX tutorial we are going to make a little sample website with all of these:)
Thanks,
-Codehead

Next: AJAX – Beginner AJAX Tutorial – Creating a simple AJAX website with example

AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message
Comments (8)   Filed under: AJAX,JavaScript,PHP,Web Development,yui   Posted by: Codehead

AJAX – Beginner AJAX Tutorial

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

AJAX – Beginner AJAX Tutorial

What you need to know
A basic knowledge of HTML, JavaScript and a server side language.

What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.

XML?!
Don’t worry you don’t need to know XML, in fact we won’t even use XML to write web applications with AJAX.

What data type we will use you are going to see in later tutorials, but I assure you we will use
something 100 times simpler.

Overview
There are a few benefits you can gain by using this technique, one is than you won’t need to send the common parts of the page to the browser whenever a user views a page on your website.

Since this is a beginner AJAX tutorial let’s make a very simple ‘Hello World’ AJAX application.

Step 1:
We are going to use Yahoo! UI library or ‘yui’.
The benefit of using yui is that you don’t need to worry about browser compatibility and also many developers are working on it to make it even better every day.

So go ahead and download the latest version here:
http://developer.yahoo.com/yui/download/

Step 2:
Extract the files and in the ‘build’ folder you will see many folders containing different parts of yui.

For this tutorial we only need yahoo.js, event.js and connection.js
So go ahead and make an HTML file and call it ajax.html (or whatever you want).

Now paste this code into your HTML file:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="edit this path to yui/yahoo.js"> </script>
<script type="text/javascript" src="edit this path to yui/event.js"> </script>
<script type="text/javascript" src="edit this path to yui/connection.js"> </script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

2 notes:
1. You must edit the path to yui library and be sure the source attribute of your script tags point to the right files.
2. I also added a div to the page so we can display the server’s response in it.

Now we included the portions of yui that we need in our page so let’s write some code.

Step 3:
Now we need to write some code to use yui’s connection object to send requests to the server.

To do this we need to write 2 JavaScript functions to handle 2 situations.
1. Success.
2. Failure, most likely the server didn’t respond.

So lets write our functions, first success:

function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}

The only thing this function does is that it sets the innerHTML of our content container.

2 notes:
1. innerHTML is a non standard attribute that almost all the browsers support.
2. o is an object yui will pass to your functions.

Now lets make our failure handler:

function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}

Here again we change the innerHTML with an appropriate error message.

So all together we have:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is dead';
}
</script>
 
</head>
<body>
<div id="content">
</div>
</body>
</html>

Let’s go ahead and write two more functions, one for sending a request to the server and one for trying the failure situation.

Here we go:

function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}

This is a simple function that sends an asynchronous request to the server.

Let’s take a look at it in more detail:

1. We defined a callback object which sets our success_handler and failure_handler functions for success and failure situations respectively
and also we define a timeout for the connection. This timeout is in milliseconds, so we are setting it to 10 seconds.
This means if we receive a response within 10 seconds then yui calls our success_handler function, otherwise it calls failure_handler.

2. The second line is the actual request. asyncRequest method will handle everything and calls our callback functions.
We are passing 3 parameters.

First parameter is the type of request, which is GET here because we are not sending any form data to the server. (I will show you POST requests in later tutorials)

Second parameter is the URL which we want to send the request to.

Third parameter is our callback object.

Now let’s make another function to test the failure situation:

function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}

This function is the same except it sends a request to a non-existing file, so it’s going to fail.

So far we have this:

<html>
<head>
<title>Beginner AJAX Tutorial</title>
 
<script type="text/javascript" src="yahoo.js"> </script>
<script type="text/javascript" src="event.js"> </script>
<script type="text/javascript" src="connection.js"> </script>
 
<script type="text/javascript">
function success_handler(o) {
document.getElementById('content').innerHTML = o.responseText;
}
 
function failure_handler(o) {
document.getElementById('content').innerHTML = 'Server or your connection is death';
}
 
function send_request() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.php', callback);
}
 
function test_failure() {
var callback = { success:success_handler, failure:failure_handler, timeout: 10000 };
YAHOO.util.Connect.asyncRequest('GET', 'http://images.code-head.com/tutorials/ajax/some-file-that-doesnt-exists.php', callback);
}
</script>
 
</head>
<body>
<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>
<div id="content">
</div>
</body>
</html>

Note: I added the line:

<a href="javascript:send_request();">Send Request</a> | <a href="javascript:test_failure();">Fail a request</a>

To be able to test our little application.

Go ahead and try it here:

http://images.code-head.com/tutorials/ajax/beginner-ajax-tutorial.html

And the PHP file is only 3 lines:

<?php
echo 'Hello World!';
?>

That’s it for now.
Thanks and good luck!
-Codehead

Next: AJAX – Beginner AJAX Tutorial – Display a Progress Bar or a Loading Message

AJAX – Beginner AJAX Tutorial
Comments (12)   Filed under: AJAX,JavaScript,PHP,Web Development,yui   Posted by: Codehead

A Paypal IPN Script With Subscription Support

This is just a bare-bone script, you will have to adopt it for your own use, this is to demonstrate how it’s done:

<?php
 
	if (empty($_POST) || @count($_POST) < 1)
		exit;
 
	$query = array('cmd=_notify-validate');
	foreach ($_POST as $key => $val) {
		if (!empty($val))	{
			$query[] = $key .'=' .urlencode($val);
			$$key    = trim(strip_tags($val));
		}
	}
	$query = implode('&', $query);
 
	$has_curl = false;
	if (function_exists('curl_init') && $ch = curl_init()) {
		curl_setopt($ch, CURLOPT_URL, 'http://www.paypal.com/cgi-bin/webscr');
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Codehead + Curl');
		$result = curl_exec($ch);
		curl_close($ch);
		$has_curl = true;
	}
	if (!$has_curl) {
		$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Host: www.paypal.com\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($query) . "\r\n\r\n";
		if ($fp = fsockopen(www.paypal.com, 80, $errno, $errstr, 30)) {
			socket_set_timeout($fp, 15);
			fwrite($fp, $header . $query);
			while (!feof($fp)) {
				$result = fgets($fp, 1024);
				if (strcmp($result, 'VERIFIED') == 0)
					break;
			}
			fclose($fp);
		}
	}
 
	if ($result == 'VERIFIED' || strtolower($result) == 'verified') {
 
		if($txn_type == 'subscr_signup') {
			/* Do something */
			exit;
		} else if($txn_type == 'subscr_modify') {
			/* Do something */
			exit;
		} else if($txn_type == 'subscr_cancel') {
			/* Do something */
			exit;
		} else if($txn_type == 'subscr_payment') {
			/* This will go bellow so the payments can be recorded */
		} else if($txn_type == 'subscr_failed') {
			/* Do something */
			exit;
		} else {
			/* Do something */
			exit();
		}
 
		$paypal = array();
		$paypal['user_id'] = $user_id;
		$paypal['payment_date'] = time();
		$paypal['completed_date'] = ($payment_status == 'Completed' ? time() : '');
		$paypal['item_name'] = $item_name;
		$paypal['payment_type'] = $payment_type;
		$paypal['payment_status'] = $payment_status;
		$paypal['pending_reason'] = $pending_reason;
		$paypal['payment_amount'] = $mc_gross;
		$paypal['paypal_fee'] = (isset($mc_fee) ? $mc_fee : 0);
		$paypal['payment_currency'] = $mc_currency;
		$paypal['txn_id'] = $txn_id;
		$paypal['receiver_email'] = $receiver_email;
		$paypal['payer_name'] = $first_name .' ' .$last_name;
		$paypal['payer_email'] = $payer_email;
		$paypal['custom'] = $custom;
		$paypal['raw_payment_data'] = serialize($_POST);
 
		if (DO YOU HAVE A PAYMENT WITH THIS INFO IN THE DB? IF YOU DO, THIS WAS PROBABLY CLEARED SA YOU DONT HAVE ) {
 
			/* Insert this row */
 
		} else if (YOU DO HAVE?) {
 
			/* Update this row */
 
		}
 
		$user = array();
		if ($payment_status == 'Completed') {
			/* Do something */
		} elseif ($payment_status == 'Pending') {
			/* Do something */
		} elseif ($payment_status == 'Failed') {
			/* If this is a subscription payment that is failed, then the code won't reach here and the $txn_type will be 'subscr_failed', see line 57 */
			/* Do something */
		}
	}
 
	header('HTTP/1.1 200 OK');
 
 
?>

I hope this helps someone :)

Update:

One of the ways to experiment with Paypal is to setup some fake payments – in Sandbox of course – and send the $_POST variable that comes to the IPN script in an email to yourself…

A Paypal IPN Script With Subscription Support
Comments (4)   Filed under: General,PHP,Web Development   Posted by: Codehead

PHP; Advancing Array Pointer In a Foreach Loop

This is not possible because ‘foreach’ operates on a copy of the array so there is no way to do it, don’t waste your time :)

BUT

You can work around this by replacing the ‘foreach’ with a ‘while’ loop, but before you do so, you must know that the following loops are functionally identical:

foreach ($days as $day) {
   echo $day;
}
 
while (list(, $day) = each($days)) {
   echo $day;
}

The same is true for these two, they are functionally identical:

foreach ($days as $i => $day) {
   echo $i .': ' .$day;
}
 
while (list($i, $day) = each($days)) {
   echo $i .': ' .$day;
}

‘While’ used this way with ‘each’ doesn’t operate on a copy of the array so you can do something like this, replace your ‘foreach’ with a ‘while’ loop and:

while (list(, $token) = each($tokens)) {
   /* Skip white spaces */
   if ($token == ' ') {
      while ($token == ' ') $token = next($tokens);
   }
}

I hope this makes sense :)

PHP; Advancing Array Pointer In a Foreach Loop
Comments (1)   Filed under: PHP,Programming,Web Development   Posted by: Codehead

Get The Contents Of a Folder

One method is to use folder functions such opendir, readdir etc.

Here is a function that returns the contents of a folder in an array:

<?php
           function get_folder_contents($folder) {		
		if(!is_dir($folder)) {
			return array(); /* You might want to do something more useful here */
		}
		$return_array = array();
		if ($dh = opendir($folder)) {
			while (($file = readdir($dh)) !== false) {
				if($file == '.' || $file == '..') continue;
 
				$return_array[] = $folder .$file;
 
			}
			closedir($dh);
		}
		return $return_array;
	}
?>
Get The Contents Of a Folder
Comments (0)   Filed under: PHP   Posted by: Hamid

SEO Friendly Redirect

Place this on top of your php file:

header('HTTP/1.1 301 Moved Permanently'); 
header('Location: http://www.the-new-url.com/maybe-file.php');
exit;
SEO Friendly Redirect
Comments (0)   Filed under: PHP   Posted by: Codehead

Insure That a File Didn’t Change

The best way is to save a sha1 hash of the file somewhere (depending on your app) and check the files to make sure their sha1 hash is still the same:

$sha1_hash = sha1_file('test.php');

If the sha1 hash of the file is different, that file was modified.

Insure That a File Didn’t Change
Comments (0)   Filed under: PHP   Posted by: Codehead
« Newer PostsOlder Posts »