Archive for the ‘PHP’ Category

Hello Script for PHP

Saturday, March 15th, 2008

In the last post I introduced the concept of ‘Hello Script’ - a file that contains the most commonly used elements of a programming language so that it can be used as a cheat sheet when working with that language. I thought I can elaborate on that concept by creating Hello Scripts for all the languages that I am familiar with.

Let’s start with PHP - I already provided this as an example for the last post. Here is the entire PHP Hello Script…


<?php
// Printing(IO)
print "Hello World!\n";

// Variables, concatenation
$name = 'Binny';
$year = 2008;
print "Hello, " . $name . " - welcome to " . $year . "\n";

//If,else conditions
if ($year > 2008) {
	print "Welcome to the future - yes, we have flying cars!";
}
else if($year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!";
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo.";
}
print "\n";

// For loop
for($i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}

//Numerical Array, While
$rules = array(
	'Do no harm',
	'Obey',
	'Continue Living'
);
$i = 0;
while($i<count($rules)) {
	print "Rule " . ($i+1) . " : " . $rules[$i] . “\n”;
	$i++;
}

// Associated array, foreach
$associated = array(
	‘hello’	=>	‘world’,
	‘foo’	=>	‘bar’,
	‘lorem’	=>	‘ipsum’
);
foreach($associated as $key => $value) {
	print “$key: $value\n”;
}

// Using Join and Split
$csv_values = explode(’,', “hello,world,how,are,you\n”);
print implode(”:”, $csv_values);

// Function, argument, return, call
function hello($name) {
	return “Hello ” . $name;
}
$hello_string = hello(”Binny”);

// One for the OOP fanboys - Class, members, object and stuff.
class Movie {
	public $name = ”;
	public $rating = 0;

	function __construct($name) {
		$this->name = $name;
		$this->rateMovie();
	}
	function rateMovie() {
		$this->rating = (strlen($this->name) % 10) + 1; //IMDBs rating algorithm. True story!
	}

	function printMovieDetails() {
		print “Movie : {$this->name}\n”;
		print “Rating : ” . str_repeat(’*', $this->rating) . “({$this->rating})\n\n”;
	}
}
//Create the object
$ncfom = new Movie(”New Country for Old Men”); //It’s a sequel!
$ncfom->printMovieDetails();

// File IO
// File reading, easy method…
$contents = file_get_contents(’Hello.php’);
print “Hello has ” . strlen($contents) . ” chars\n”;
// Writing to a file
$file_handle = fopen(’/tmp/hello.txt’, ‘w’);
fputs($file_handle, “Hello World”);
fclose($file_handle);

// Command Executing
print `ls`; //Execute the command ‘ls’ and print its output
print “\n”;

// Regular Expressions
$string = “Hello World”;
if(preg_match(’/^Hell/’, $string)) print “Yup - its evil\n”;
print preg_replace(’/l([^l])/’, “$1″, $string); //Remove an ‘l’ from both words. Should print ‘Helo Word’

/*
 * Specialized code
 */
// Database connectivity(native)
mysql_connect(’localhost’, ‘root’, ”) or die(”Cannot connect to the Database server”);
mysql_select_db(’Data’) or die(’Could not find a database called “Data”‘);

// Executing Query
$sql_handle = mysql_query(’SELECT name,url,description FROM Comment LIMIT 1′) or die(’Query Error: ‘ . mysql_error());
while($row = mysql_fetch_assoc($sql_handle)) {
	print “Name	:	$row[name]\n”;
	print “URL	:	$row[url]\n”;
	print “Desc	:	$row[description]\n\n”;
}
/* Just a note here - if you are going to use PHP with database in a production
 * system(and you will, trust me), use a Database abstraction layer rather than
 * the above mentioned native methods.
 */

print $_REQUEST['username']; // Method to get the value of the field ‘username’ after a form submit. Will not work at CLI execution

Save this to a file and keep it around for future reference - if you are just starting out with PHP

Coming up next - Python Hello Script.

Learning a New Programming Language: The ‘Hello World’ Method

Thursday, March 6th, 2008

Hello World Learning

Learning a new programming language is fun - and essential if you want to stay competitive. I try to learn new languages all the time(my latest target is Haskell). As a result, I have a system to make learning new languages easier. This is for people who already know a programming language and want to learn another one.

Requirements

What you must have…

The interpreter/compiler of the language you are learning
You must be able to run the program after writing it.
Language reference manual/documentation
Usually found at the site of the language. Put a shortcut to that on your desktop - because you will be using this all the time.
An easy to follow tutorial
Search for it in Google. If you find one and its hard to follow, ditch it and get another. You may not need this - as manual for most languages have a tutorial in them.
A ‘todo’ project that you cannot live without
This is what forces you to learn the language - more on this later.

What I would recommend you have…

Having this will help you learn - but its not necessary.

A Net Connection
You may want to ask your doubt on the IRC channel. Or on a forum. Or to google the error message you got.
A Decent IDE
This may make your job easier - but if you have notepad, that’s enough.

What you don’t need

Books on the language
You may need a book to master the language - but you don’t need one to learn it.
A Teacher
Its helpful to have someone to clarify the doubts you may have - but no one can teach you anything you cannot learn yourself.

The Hello World Script

First you have to create the ‘hello world’ application. This is more than just ‘print “Hello World”‘ - it will act as a cheatsheet for you until you familiarize yourself with the language. The point of this application is to use all the most commonly used elements of a language and putting it in a single place so that you can refer to it later.

Your first job is to go to the tutorial, the manual and the internet until you create the Hello World application with the following stuff in it. I will provide an example - how the ‘hello world’ application will look in PHP.

After each step run the application and make sure it works.

Print “Hello World\n”

Why do you think we call it a hello world application? Write the code to print a string ‘hello world’ and save it to a file. Now run it using the interpreter - and make sure it works - see it in action.


// Printing(IO)
print "Hello World!\n";
	
Comments

Put a single line comment(like //) on top of the “print ‘hello world’” code and if your language supports it, a multiline comment(/* - */) as well. Run the script to make sure the comments work as advertised.


// Single line comment.
/*
Mulitline comment.
*/
	

I was just kidding about running the script to test the comments - you did’nt do it, did you?

Use a variable(a string and an integer) and a concatenation operator.

Create a variable called name(string) - and give it your name as the value. Create another integer variable and give it the current year. You don’t have to find it programatically - just put it as 2008 or something. Now you have to print out the a string “Hello, <name> - Welcome to year <$year>”. This string will let you concatenate two different type variable to a string - and it makes me feel like a time traveler ;-).

Yeah - the value of variable name should appear at <name>. Use the concatenation operator if possible - in PHP, write

print "Hello, " . $name . " - welcome to year " . $year;

instead of

print "Hello, $name - welcome to year $year";

This is because different languages have different concatenation operators. The other stuff is the same almost universally. + refers to addition. - refers to subtraction. * is multiplication. My point is that if you know the operators for one language, you know the operators for almost all languages. But the concatenation operator differs from language to language - its ‘+’ in javascript, ruby. Its ‘.’ in Perl, PHP, etc.

There are exceptions to this rule - ‘=’ is the equality operator in SQL while it all other language its ‘==’. The assignment operator is ‘:=’ in pascal - in all other it is ‘=’. If you notice any difference in any operator write some code using that operator in this section.

Use if/else if/else

Create something like this pseudo code…

if (year > 2008) {
	print "Welcome to the future - yes we have flying cars!"
}
else if(year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!"
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo."
}

In PHP, this section will look like this…

//If,else conditions
if ($year > 2008) {
	print "Welcome to the future - yes, we have flying cars!";
}
else if($year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and decent, stay away from your parents!";
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo.";
}
print "\n";
	

If you use switch(and the new language supports switch), you can write an example of switch here.

Print ‘Hi there!’ 3 times using a for loop

A PHP example of using for loop(my all time favorite loop)…

// For loop
for($i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}
	
Create a list(array) and iterate through it using while/for/foreach loop.

I am using a while loop here - to keep things different…


//Numerical Array, While
$rules = array(
	'Do no harm',
	'Obey',
	'Continue Living'
);
$i = 0;
while($i<count($rules)) {
	print "Rule " . ($i+1) . " : " . $rules[$i] . “\n”;
	$i++;
}	
Create a hash(associative array) and iterate through it.

If the language you are going to learn have ‘foreach’, this maybe the best time to use it…

// Associated array, foreach
$associated = array(
	'hello'	=>	'world',
	'foo'	=>	'bar',
	'lorem'	=>	'ipsum'
);
foreach($associated as $key => $value) {
	print "$key: $value\n";
}
Create a function with an argument and a return.

If you need, you can create an example for call by reference, optional arguments, default argument value, variable argument count etc. as well - but they are not essential. Make sure you include the code to call a function as well.

// Function, argument, return, call
function hello($name) {
	return "Hello " . $name;
}
$hello_string = hello("Binny");

Optional Code

I don’t usually included some of these in my ‘hello world’ scripts - but they can be useful in some cases. Some may find them useful - so if you think you are going to use any of these, include it in your file.

Class, Objects, Member variables and functions

If you are a big fan of OOP, create the code for a class. Make sure it has all the following elements…

  • At least one member variable
  • At least two member functions
  • Access the member variable and the other function from within a member function.
  • Create an object of this class
  • Call a member function using the object.
// One for the OOP fanboys - Class, members, objects and stuff.
class Movie {
	public $name = '';
	public $rating = 0;

	function __construct($name) {
		$this->name = $name;
		$this->rateMovie();
	}
	function rateMovie() {
		$this->rating = (strlen($this->name) % 10) + 1; //IMDBs rating algorithm. True story!
	}

	function printMovieDetails() {
		print "Movie : {$this->name}\n";
		print "Rating : " . str_repeat('*', $this->rating) . "({$this->rating})\n\n";
	}
}
//Create the object
$ncfom = new Movie("New Country for Old Men"); //It's a sequel!
$ncfom->printMovieDetails();
File IO

Include this code - it is sure to come in useful someday. Unless you are learning JavaScript.

// File IO
// File reading, easy method...
$contents = file_get_contents('hello.php');
// Writing to a file
$file_handle = fopen(’/tmp/hello.txt’, ‘w’);
fputs($file_handle, “Hello World”);
fclose($file_handle);
	
Command Execution

I tend to include this - but it may be unnecessary for you.

// Command Executing
print `ls`; //Execute the command 'ls' and print its output
Regular Expressions

I always include them - I am a big fan of regular expressions. I have lost count of how many times they have saved the day.

// Regular Expressions
$string = "Hello World";
if(preg_match('/^Hell/', $string)) print "Yup - its evil\n";
print preg_replace('/l([^l])/’, “$1″, $string); //Remove an ‘l’ from both words. Should print ‘Helo Word’
	

Specialized Code

The language you learn may have a specialized field which we may have not used yet. If so, put it down here.

If you are learning javascript, write some code to access DOM nodes here. If you are using PHP, database connectivity will go well here. If you are learning any web server side languages, write the code to fetch the POST/GET request values. For PHP, it may look something like this…


// Database connectivity(native)
mysql_connect('localhost', 'root', '') or die("Cannot connect to the Database server");
mysql_select_db('Data') or die('Could not find a database called "Data"');

// Executing Query
$sql_handle = mysql_query('SELECT name,url,description FROM Comment LIMIT 1') or die('Query Error: ' . mysql_error());
while($row = mysql_fetch_assoc($sql_handle)) {
	print "Name	:	$row[name]\n”;
	print “URL	:	$row[url]\n”;
	print “Desc	:	$row[description]\n\n”;
}
// Just a note here - if you are going to use PHP with database in a production system(and you will, trust me), use a Database abstraction layer rather than the above mentioned native methods.

print $_REQUEST['username']; // Method to get the value of the field ‘username’ after a form submit. Will not work at CLI execution
	

Project

Next thing you need is a project - which you are going to build using the new language. Some points that you have to look for when choosing the new project…

  1. It should not be a huge project.
  2. At the same time, it should not be something trivial.
  3. There must be something about the project which would force you to finish it.

The third point needs a little explaining. You should not just pick any project that pops into your mind. It must be something that you need - something you could not live without. If it is important to you, you will have a motivation to finish the project. Otherwise, you will drop the project at the first sign of trouble. But if its important to you, you will spend more time on it - you will look at documentation, post the problem in forums, ask others in IRC channels. And eventually, you will fix the problem. And you will finish the project.

While working on the project, keep the ‘hello world’ open - you will find yourself referring to it often.

Nexty, The Online Application

Wednesday, September 26th, 2007

Nexty Logo

I just released the latest version of Nexty - and to celebrate that, I am making Nexty an online application. That is, you can use Nexty from the web - without having to install it on your local system.

Of course, Nexty code is available as well - you can download and install it locally if you wish. In fact, I will recommend that you install it locally. That way, the application will be much faster than the online alternatives.

This happens to be my first online app. I have worked on many online projects before - but those were for various clients. This is the first online application that I have created for the use of others! I am working on anther online application - but by the look of things, it is not going to be over soon.

And thanks to Brad Nickel for suggesting this idea.

Finally! Nexty 1.01.A Released

Saturday, September 22nd, 2007

I have released Nexty 1.01.A. If you are a user of Nexty, I will recommend that you switch to the new version.

Changelog

Search
Search for tasks, projects and reminders
Next Action
Dedicated page for the next action - and only that
Inbox Feature
Add a lot of tasks in one go using the inbox
Linux Command Line
A script to control Nexty from the Linux command line.
Code uses iFrame
iFrame is my PHP framework
Bug Fixs
Too many to list
Better Installer
Will not overwrite the old data
Printing Support
Well, its better than before

To Learn more…

Seinfeld Calendar - Simple way to Force Yourself to Create Content Regularly

Sunday, September 16th, 2007

BinnyVA.com

I created an RSS aggregater for my site BinnyVA.com that aggregates the content from all my sites. The basic idea is to build a Seinfeld Calendar that will force me to continually publish posts - at least 1 per day.

It is very simple to create - whole system is contained in the following files…

fetcher.php

This will run once a day as a cron job. It downloads the feeds for all my sites, parses the XML and inserts the new posts into the database.

The download is done by my load PHP function. It uses the curl library.

The XML parsing uses the xml2array() PHP function. Currently I parse only the RSS format - I am completely ignoring the atom format.

Finally the data is inserted into the database - the following data is stored…

  • Title
  • Link
  • Date
  • Summary
  • Full Content
  • Categories/Tags

The full file is around 100 lines long.

index.php

This is a simple calendar scripts that lists all the posts of each days of one month. Includes a navigation to enable the visitor to go to the past months as well.

Other Files

There is a bit of mod_rewrite code that make sure that the URL are very clean. For example, the URL for April 2007 is http://www.binnyva.com/2007/04/.

The mod_rewrite for this is in the .htaccess file…


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/([0-9]+) index.php?year=$1&month=$2

Don’t Break the Chain

Now all you have to do is make sure that each day has at least one post in it. This system had me creating content continually for the last two months.

If you are looking for an easier way to create the calendar, try out Don’t break the chain.

Nexty Updates

Wednesday, August 22nd, 2007

Nexty Logo

I made some more updates to nexty. Still not packaged - give me a little more time. In the meantime, try out the demo

There is one really cool feature in this release - but it is for Linux Users only. I made a command line script that integrates with Nexty - you can add tasks directly from the console. It needs the curl command - so not available in windows.

But then again, who uses the terminal in windows?

Anyway this uses the concept I introduced in CLI Twitter. If you want to try it, login to Nexty and go to the settings page. If you are on a linux system, you will see a Download Nexty Shell Script section. Just follow the instructions there.

Demo for Nexty 1.01.A Uploaded

Thursday, August 16th, 2007

Nexty Logo

I uploaded the demo for the new beta version of Nexty today. The code is too ‘beta’ to be packaged and released - so I am just uploaded the demo. If the bugs are found and fixed soon, I will release the code into the wild. If you cannot wait for the code, it is available at the SVN repository.

Whats New…

A few new features are…

  • Search
  • Next Action
  • Inbox Feature
  • Code uses IFrame
  • And more…

Please try out the demo and let me know if you spot any errors. That is the whole point of uploaded the demo.

Nexty 1.01.A Demo

Nexty 2 will use PHP 5

Saturday, August 4th, 2007

GoPHP5

The next version of nexty is coming out very soon - and unlike the last version, Nexty 2 will require PHP 5.

The main reason behind this change is GoPHP5. Go PHP 5 is a movement to promote the use of PHP5 in hosting servers and for projects.

Another reason for this decision is that iFrame, the framework I used in Nexty, uses PHP 5.

If you are stuck with PHP 4, I cannot help it. You can still use the first version. But if you have a choice, PHP 4 is dead - move on.

More on GoPHP5

Web Installer: The Code

Wednesday, July 11th, 2007

The last two posts on web installer did not include any code. I wanted to dump all code into one post - this is it. Please note that this is what I did - you don’t have to copy my code as it is. Just look at the code and modify it according to your needs.

Getting Database Details

The Form/Frontend

<form action="" method="post">
<h1>Installation : Step 1</h1>
Please provide the database connection details...
<fieldset>
<legend>Database Details</legend>

<label for='host'>Database Host</label><input type='text' name='host' value='localhost' /><br />
<label for='db_user'>Database User</label><input type='text' name='db_user' value='root' /><br />
<label for='password'>Database Password</label><input type='text' name='password' /><br />
<label for='database'>Database</label><input type='text' name='database' value='nexty' /><br />
</fieldset>

<input type="hidden" name="step" value="2" /><br />
<input type="submit" name="action" value="Continue >>" /><br />
</form>

Backend

Make sure that the given database details are correct.

// The First step is Setting up Database connection
//					   (the '2' is NOT a typo)
if($_REQUEST['step'] == 2) {
	//Save the data to the Session
	if(isset($_REQUEST['host'])) $_SESSION['host'] = $_REQUEST['host'];
	if(isset($_REQUEST['db_user'])) $_SESSION['db_user'] = $_REQUEST['db_user'];
	if(isset($_REQUEST['password'])) $_SESSION['password'] = $_REQUEST['password'];
	if(isset($_REQUEST['database'])) $_SESSION['database'] = $_REQUEST['database'];
	if(isset($_REQUEST['url'])) $_SESSION['url'] = $_REQUEST['url'];

	if(mysql_connect($_SESSION['host'],$_SESSION['db_user'],$_SESSION['password'])) { //Try to connect to the DB.
		$QUERY['success'][] = ‘Connection to Database server successful’;

		if(mysql_select_db($_SESSION['database'])) {//Select the provided database.
			$QUERY['success'][] = “Database ‘$_SESSION[database]‘ selected”;

		} else {
			$QUERY['error'][] = ‘The given database(’.$_SESSION['database'].’) does not exist. Please povide a valid database.’;
			$_REQUEST['step'] = 1;
		}
	} else {
		$QUERY['error'][] = ‘Unable to connect to the database. Make sure that the entered details are correct’;
		$_REQUEST['step'] = 1;
	}
}

Notice the over use of $_SESSION? That will come in use if I decide to add a Back button that enables the users to modify the data entered previously.

Database Creation

//Create the database only if it does not exist
//See if the database exists
$tables_sql = mysql_query("SHOW TABLES") or die(mysql_error());
$necessary_tables = array('Context','Project','Reminder','Setting','Task','TaskContext','User');
while($table = mysql_fetch_row($tables_sql)) {
	$necessary_tables = array_diff($necessary_tables,array($table[0])); //Remove the table from the array if it exists
}

//If there are no tables in the array that means that the all the necessary tables are present in the Database
//If some tables are missing, that means we have to create those tables…
if($necessary_tables) {
	$quries = <<<END
– Insert all the SQL to create the necessary tables here…
END;

	//Execute all the queries
	$all_quires = explode(”;”,$quries);
	$query_count = 0;
	foreach($all_quires as $query) {
		$query = trim($query);
		if($query) {
			@mysql_query($query);
			$query_count++;
		}
	}
	$QUERY['success'][] = “Database Populated.”;
} else {
	$QUERY['error'][] = “Tables already in Database - I did not overwrite it. If you want to remove the old data, please delete the tables and run the installer script agian.”;
}

Saving the Database connection details


//I don't know how to escape the $ charector in heredocs - so I did this...
$config = '$config';//Heh, Heh ;-)
$system_installed = '$system_installed';
$configuration = <<<END
<?php
//Configuration file for Nexty
$system_installed = true;
$config = array(
	'db_host'		=>	'$_SESSION[host]‘,
	‘db_user’		=>	‘$_SESSION[db_user]‘,
	‘db_password’	=>	‘$_SESSION[password]‘,
	‘db_database’	=>	‘$_SESSION[database]‘,
	‘url’			=>	‘$_SESSION[url]‘,
	‘absolute_path’	=>	‘$abs’
);

END;
if(is_writable(’../configuration.php’)) {
        // …Write the $config text into the configuration.php file…

	$QUERY['success'][] = ‘Saved the configuration file. <a href=”‘.$_REQUEST['url'].’”>Go to Nexty</a>’;
} else {
	$QUERY['error'][] = ‘Configuration file (configuration.php) is not writable. Please copy the configuration code and enter it into the “configuration.php” file. Then press continue.’;
}

See the install folder for Nexty in the Subversion server.

What I learned from Nexty

Sunday, May 27th, 2007

Nexty Logo

Remember Nexty? Recently I was able to make the 1.0 version. Currently I am planning for the second version. But before starting on that I want to document the different things I learned when creating Nexty. These are a list of things you can expect on this series…

Client Side

  • CSS
    • Icons
    • Theming using CSS
  • JavaScript
    • Ajax - Success/Failure Pattern

Server Side

  • Installer
  • Framework
  • API
  • Distributed Apps

Before starting, a small notice - I will include links to Nexty’s internal pages in this series. Most of these pages are behind a login. So I would advice that you get an account in Nexty and login into it using the ‘Remember Me’ option enabled. This would make sure that you have the most seamless experience.

Subscribe to Feed