online marketing
Posted by admin on December-11-2009 Add Comments

Storing multidimensional arrays in a file

In this tutorial I will show you how to store a multidimensional array in a file and how to retrieve these data. With this method you can imitate a very basic database functionality.

Step 1.
To realize this we need to implement 2 methods. One for the storing array and one which reads the file back and create an array from its content. The most important part is how to convert an array into a format which can be store easy in a file. To do this first we convert the array into a special string format. In this format we use some special characters to separate various sub-arrays and data elements. After it the saving of this string is quite easy.

So let’s try to convert the array into a special string. So I create a new function called array2string() and this function has 3 parameters. They are input array, the output string and a helper variable to store actual key value. This helper variable for the key element will be important later. In case of the last 2 parameters we will use variable references as we will call our function in a recursive way.

The theory is that we create a for each loop on the main array. If the actual data itself is again a new sub-array then the function will call itself. In this case that input array will be the actual sub-array. In case of the actual value is not an other array then we will add this data to the output string in the corresponding key-value format.

The complete code is quite short:

PHP Code:
<?php
function array2string($myarray,&$output,&$parentkey){
foreach(
$myarray as $key=>$value){
if (
is_array($value)) {
$parentkey .= $key."^";
array2string($value,$output,$parentkey);
$parentkey = "";
}
else {
$output .= $parentkey.$key."^".$value."\n";
}
}
}

?>

Don’t forget about the separator character. Select one which is not causes any problem. Now this string can be easily stored in a file. See it in a later step.

Step 2.
Now it’s time to make the reverse function as well. Let’s call it to string2array() and it needs 2 parameters. The input string which we want to convert and an array reference which will store the resulted array. First we need to divide the input string into smaller parts using the explode() function and our main separator character. After it we iterate over the resulted list and analyze it line by line. Inside this loop we divide the actual line it smaller parts again. If there is no more possibilities to divide the string even smaller values then we will add the actual value to the corresponding array element after we created that.

At the end our code looks like this:

PHP Code:
<?php
function string2array($string,&$myarray){
$lines = explode("\n",$string);
foreach (
$lines as $value){
$items = explode("·",$value);
if (
sizeof($items) == 2){
$myarray[$items[0]] = $items[1];
}
else if (
sizeof($items) == 3){
$myarray[$items[0]][$items[1]] = $items[2];
}
}
}
?>

Step 3.
As we have both important functions implemented let’s see an example how it works in the real life.
First I have created some test data. You can use this:

PHP Code:
<?php
// Create some test data
$mydb[0]['name'] = "John";
$mydb[0]['city'] = "Boston";
$mydb[0]['age']  = "32";
$mydb[1]['name'] = "Max";
$mydb[1]['city'] = "London";
$mydb[1]['age']  = "41";
$mydb[2]['name'] = "Ann";
$mydb[2]['city'] = "Bonn";
$mydb[2]['age']  = "29";
$mydb[3]['name'] = "Peter";
$mydb[3]['city'] = "Dallas";
$mydb[3]['age']  = "28";
$mydb[4]['name'] = "Martin";
$mydb[4]['city'] = "Berlin";
$mydb[4]['age']  = "22";
?>

Now we just need to call our implemented array2string() function and store the output string in a text file.

PHP Code:
<?php
// Convert the array into string
array2string($mydb,$output,$parent);

// Store the string in a file
$f1 = fopen("test.txt","w+");
fwrite($f1,$output);
fclose($f1);
?>

To read it back makes no problem.

PHP Code:
<?php
// Read the file back from the disk
$f1 = fopen("test.txt","r");
$newString = fread($f1,filesize('test.txt'));
fclose($f1);

// Convert the content back to an array
string2array($newString, $newArray);

// Print out the array
foreach ($newArray as $item) {
echo
'Name: '.$item['name'].'<br/>';
echo
'City: '.$item['city'].'<br/>';
echo
'Age: '. $item['age'].'<br/>';
}
?>

That’s it!

Download:
You can download an ArrayHandler script: http://www.ziddu.com/download/7236479/ArrayHandler.zip.html

Posted by admin on December-11-2009 Add Comments

How to execute PHP with cron

How to execute PHP with cron

Every now and then you will run across a task that needs to be executed through PHP however this task cannot or should not be ran by a visitor opening a webpage (such as a maintanance or caching script). The only way to run these scripts would be to do it manually as an administrator or to do it automatically using cron.
Manually sucks which is why I wrote this tutorial. Specifically this will target users of cPanel installations (gotta love shared hosting). All cPanel installs that I have used have cron as an option. When you log into cPanel there should be an option called crontab or Cron Jobs or any other such thing. Clicking this option brings up the cron jobs window.
On my install I am given the choice between Standard and Advanced (Unix Style) Cron settings. Standard makes the task more easier and offers the same amount of control, so lets press Standard.
You are given two sections to enter a cron job. If you need more, just fill in the first two and more will become visible when you save your settings. You can set all sorts of options concerning when the script will run. You can run it from every minute to ever year, controling what times down to the second that the script is executed.
The command that you run is the fun part. In my install I enter the absolute path to the script (/home/ACCOUNT/public_html/script.php). Inside of the script I have added the line:

Code:
#!/usr/bin/php -q

This will run php in command line mode when the script is run (you may need to change the path to your PHP binary). Finally, you will need to chmod 755 your php file so that it can be executed.
And there you have it. Your script will be run automatically. If you don’t want the script to be executed by a person by typing in the URL, drop it into a folder and change .htaccess settings to nobody can open the file. While debugging your script (and even making sure that it is ran at all) you may want to have output saved to a log file and execute the script manually.

Posted by admin on December-11-2009 Add Comments

Generating random passwords

Generating random passwords

It becomes practical and more useful if the tutorial is written in the form of a funtction. This function will hopefully work anywhere.
The basic idea behind this random password is that it will give a different password every time it is called. This can only be done by using the time as the main core input. So we will start of by defining a PHP function which will generate this password for us. There will be one input from the user, the length of the password. When the function will be called, it will return a random password of characters ranging from 0-32 depending on the length given (alphabets and numbers).
Here is the complete function:

PHP Code:
<?php
function randomPassword($length){

$pass = md5(time());
$pass = substr($pass, 0, $length);
return
$pass;
}
?>

The above function is pretty straight forward. The first line defines a function called “randomPassword” which takes a parameter ‘length’. The next line uses the built-in PHP function MD5(). MD5 function returns the hash of the input given. Here we give MD5 the time as input. The time() function returns the timestamp. Remember that the timestamp will always be different because the date is always changing (here date includes time and seconds). So basically when we give the MD5 function the latest timestamp, it generates the hash for that specific instant, which is also always different because of the ever changing time.
Next we substr the password returned. Substr is used for returning some specific length of a given string. For example, the substr used here will return the initial string of the password of the length that the user will give.
The last line of code returns the password randomly generated.
You can use the function the following ways:

PHP Code:
<?php
echo randomPassword(15);
//or
$password = randomPassword(15);
?>

The above code will return something like 1b415353bde123a
Enjoy the tutorial

Posted by admin on December-11-2009 Add Comments

Looping Statements in PHP

In programming it is often required to repeat a block of code for a given number of times or until a certain condition is not true. For this, we use looping statements. PHP has two major looping statements (FOR and WHILE).

In common practice, FOR loop is mostly used when we need to loop a code for specific number of times. Whereas WHILE loops are best used when we are using conditions and number of loop is not of primary priority.

THE WHILE LOOP

As said above, the while statement executes a block of code until the condition isn’t fulfilled.
Here is the syntax of while loop.

PHP Code:
while (condition){
code needed to loop;
}

The above code between { } will be executed until the condition turns to false.

Here is a proper PHP example.

PHP Code:
<?php
$i
= 0;
while (
$i <= 10){
echo
"The number is ". $i . "<br/>";
$i++;
}
?>

The above program will show output Something like.

The number is 0
The number is 1
The number is 2
…and so on.

it will show 11 outputs, from 0 to 10.

THE DO WHILE LOOP

This loop is almost the same as the WHILE loop except that it executes the code atleast once before the condition

is checked. The reason for this is that the condition statement is written at the end.
Here is a DO WHILE loop syntax.

do{
code needed to loop;
}while (condition);

if we want to write the same above program with DO WHILE

PHP Code:
<?php
$i
= 0;
do{
echo
"The number is " . $i . "<br/>";
}while (
$i <= 10);
?>

The above code will give the same output.

THE FOR LOOP

As mentioned above, the FOR loop is mostly used when we know how many times we need to loop the code. FOR loop is also known as definite loop. FOR loop is prefered by most programmers because its more convenient to use. The

syntax of FOR loop is given as follows.

PHP Code:
for (initialization; condition; increment){
code needed to loop;
}

FOR loop takes three arguments separated by ( semicolons. Although the required argument is the condition, the other two are optional.

The initialization argument is a variable which we use for incrementation/decrementation.
The condition is the expression which is evaluated everytime the code is executed and the code loops if the condition is true.
The increment or decrement updates the counter variable.

Given below is a PHP example.

PHP Code:
<?php
for ($i = 0; $i <= 10; $i++){
echo
"The number is " . $i . "<br/>";
}
?>

Next Comes the FOREACH Loop

THE FOREACH LOOP

This is basically a variation of the FOR loop and allows to iterate over array elements. The two different

versions of the Foreach loop are written below.

PHP Code:
foreach (array as value){
code needed to loop;
}
PHP Code:
foreach (array as key => value){
code needed to loop;
}

given below is a PHP based example.

PHP Code:
<?php
$num
= array('1', '2', '3');
foreach (
$num as $value){
echo
"Num " . $value . "<br/>";
}
?>

Foreach’s different type is more useful.

PHP Code:
<?php
$num
= array('1' => 'One', '2', => 'Two');
foreach (
$num as $key => $value){
echo
"Num " . $key . " is also called " . $value . "<br/>";
}
?>

In the above example, the key for each element is placed in the $key variable and its corresponding value in $value.

Although, Foreach construct does not operate on the the array itself, but rather on a copy of it. This means that what ever you change or manipulate of the $value, it wouldn’t effect the orignal array.

Break and Continue Statements

These statements are not used that often. Although they are sometimes really useful when saving some resources.
As the statements imply, Break is used to break the loop and continue is used to jump to the next iteration without executing the code beneath it.

Two examples are written below.

PHP Code:
<?php
for ($i = 0; $i <= 10; $i++){
if(
$i==5){break;}
echo
"The number is " . $i . "<br/>";
}
?>

The above program will break the loop when $i = 5;
it will show previous outputs.

Below is an example of continue.

PHP Code:
<?php
for ($i = 0; $i <= 10; $i++){
if(
$i==5){continue;}
echo
"The number is " . $i . "<br/>";
}
?>

The above program will skip the loop when $i = 5; It will show the prevous and next values.

I hope this tutorial becomes handy to those who are new to PHP.

Enjoy

Posted by admin on December-11-2009 Add Comments

PHP Login script tutorial

PHP Login script tutorial

Overview In this tutorial create 3 files
1. main_login.php
2. checklogin.php
3. login_success.php

Step
1. Create table “members” in database “test”.
2. Create file main_login.php.
3. Create file checklogin.php.
4. Create file login_success.php.
5. Create file logout.php

1- Create table “members”

Code:
CREATE TABLE `members` (
                                                `id` int(4) NOT NULL auto_increment,
                                                `username` varchar(65) NOT NULL default '',
                                                `password` varchar(65) NOT NULL default '',
                                                PRIMARY KEY  (`id`)
                                                ) TYPE=MyISAM AUTO_INCREMENT=2 ;
                                               --
                                                -- Dumping data for table `members`
                                                --
                                               INSERT INTO `members` VALUES (1, 'john', '1234');

2- Create file main_login.php
View In Browser

HTML Code:
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

3- Create file checklogin.php

PHP Code:
<?php
$host
="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from  form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched  $myusername  and $mypassword,  table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo
"Wrong Username or Password";
}
?>

4- Create file login_success.php

// Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.

PHP Code:
<?
session_start
();
if(!
session_is_registered(myusername)){
header("location:main_login.php");
}
?>

<html>
<body>
Login Successful
</body>
</html>

5- Logout.php

If you want to logout, create this file

// Put this code in first line of web page.

PHP Code:
<?
session_start
();
session_destroy();
?>

6- For PHP5 User – checklogin.php

PHP Code:
<?php
ob_start
();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched  $myusername  and $mypassword,  table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo
"Wrong Username or Password";
}
ob_end_flush();
?>

7- Encrypting Password – Make your Login More Secure

Posted by admin on December-11-2009 Add Comments

Simple Ad Rotation Script

Overview

In this script (very easy script), we have 3 ads for rotation
first ad we want it to display 70%
second ad we want to display 20%
and the last one we want to display 10%

What to do

1. Random number 1-100
- if result = 1-70 (we have opportunity to display ad 1, 70%)
- if result = 71-90 (we have opportunity to display ad 2, 20%)
- if result = 91-100 (we have opportunity to display ad 3, 10%)

Example

In this script use rand(1, 100); to random number between 1 -100 and keep result in variable name “$result_random” if result = 85 ad 2 will display.

############### Code

PHP Code:
<?php

// random number 1 - 100
$result_random=rand(1, 100);

// if result less than or equal 70, display ad 1 (70%)
if($result_random<=70){
echo
"Display ad1";
}

// if result less than or equal 90, display ad 2 (20%)
elseif($result_random<=90){
echo
"Display ad2";
}

// if result less than or equal 100, display ad 3 (10%)
elseif($result_random<=100){
echo
"Display ad3";
}

?>

Posted by admin on December-11-2009 Add Comments

Get adsense stats from PHP

Get adsense stats from PHP

Why not let your own script fetch the statistics directly from google adsense reporting site? It’s always much easier to have the data locally in your own database, and then create scripts to display the stats in the way you are interested in.
I will now give you the code that collects the present stats from adsense, for any channel you specify. Because I also love to work with databases, we will store the results in mysql.
The basics behind the script is that you choose what channels you want to fetch stats for, and then you let your script do that as often as you which. You can schedule this script with crontab or something similar as often you which. Don’t do it more often than every 15 minutes, because I have heared something from google that you are not allowed to script things mroe often against adsense …
Here’s what to do:

  1. Login to adsense and click on “advanced reports”. Create channels if you don’t have any yet, because this script shows stats for separate channels.
  2. This part might be the most complicated, but still very easy. “View source” for the page and search for select name=”reportId”. Scroll further out on that row in the source and look for your channel names. You will find something similar to this Cholesterol-week . Write down the number and the name on a paper or somewhere. Do this for every channel you want to track.
  3. Create a database and assign a user with a password for that.
  4. Run this sql code:
    Code:
    CREATE TABLE `adsense` (
    `id` int(11) NOT NULL auto_increment,
    `channel` varchar(50) NOT NULL,
    `reportedWhen` datetime NOT NULL,
    `impressions` int(11) NOT NULL,
    `clicks` int(11) NOT NULL,
    `rate` decimal(10,3) NOT NULL,
    `cpm` decimal(10,3) NOT NULL,
    `earnings` decimal(10,3) NOT NULL,
    PRIMARY KEY (`id`)
    )
  5. Save the file you see in the blue box below as adsense.php or similar. Look at the first lines where you need to fill in your details. Both for your adsense account and your db details.
  6. In the file you need to enter all channelId’s and channelNames in the array. Just increase that array if you have more channels!

I have not created any script to display the stats yet, but that might come in the future :-) For now, enjoy the script and let me know if you like it!
Here is the script:

PHP Code:
<?
// Change things from here!!!
$adsenseUsername = "yourname@yourcompany.se";
$adsensePassword = "yourpassword";

$dbHostname = "localhost";
$dbUsername = "dbUsername";
$dbPassword = "dbPasswd";
$dbName = "theDbName";

$reports = Array("1234" => "channel1",
"56215" => "channel4",
"35507" => "channel3");
// Stop changing things here!!!

$adsenseCookie = "adsenseCookie.txt";

// Google time
putenv('TZ=US/Pacific');
$now = date("Y-m-d H:i:s");

$dbLink = mysql_pconnect($dbHostname, $dbUsername, $dbPassword) or die('Could not connect to database: '.$dbHostname);
mysql_select_db($dbName, $dbLink) or die('Could not find database: '.$dbName);

// Handle every report separately
foreach($reports as $id => $name)
{
$result = getAdsenseReport($id);
logChannel($name, $result, $now);

Posted by admin on December-11-2009 Add Comments

XML processing with PHP

XML processing with PHP

Introduction

XML is Extensible Markup Language. It is a markup language – much like HTML – and was designed to describe data. XML uses tags but these tags are not predefined as in HTML. In XML you define your own tags. All XML documents have 3 types of components: Elements, attributes and data.

Let’s see a basic XML file:

Code:
<root>
  <child attribute='test'>
    <subchild attribute='sub'>testdata</subchild>
  </child>
</root>

The first line defines the root element of the XML. It is the <root>. The root element can contain any number of child elements. All of them can be found between the opening <root> and closing </root> tag. In our example the file contains a child element. The child element has and that in turn can have its own and so on. There is no restriction as to how many child element is defined. All is up to you.
In the second line there is a new element which is a child of the root element. In this case it has an attribute which you can interpret as a property of the given element. In this example the property name is attribute and the property values is ‘test’. This element has again a child (line 3) – which is a subchild of the root – element with an attribute. Besides this it has a data with the value of ‘testdata’.

As you can see from this small example:

  1. 1. Each XML element has an opening and a closing tag.
  1. 2. The attributes is defined inside the opening tag.
  1. 3. The data is surrounded by opening and closing tags.

PHP and XML

PHP has its own built in functions for XML handling. To process an XML file first of all you need an XML parser. You can create it with the following code:

PHP Code:
$parser = xml_parser_create();

This code creates an empty XML parser object which will process our XML file later. The parser requires the XML document as a string so we read the file as follows:

PHP Code:
$document = file_get_contents("test.xml");

Now we have an XML document in string format and an XML parser. Let’s process the file.

PHP Code:
xml_parse($parser, $document);

After processing we free up the resources:

PHP Code:
xml_parser_free($parser);

The complete code looks like this at the moment:

PHP Code:
<?php
$parser
= xml_parser_create();
$document = file_get_contents("test.xml");
xml_parse($parser, $document);
xml_parser_free($parser);
?>

And our test XML file (test.xml), which is located in the same directory as our PHP script:

Code:
<carlist>
  <car type="Mercedes">S 600</car>
  <car type="Mercedes">E 270 CDI</car>
  <car type="BMW">535 D</car>
  <car type="Lexus">IS 220</car>
</carlist>



Try to execute it!
What happened?
Nothing.
It is normal as we didn’t define what to do with the results and how the result should look like. Then for example how can I list all Mercedeses?

XML processing refinement

To get a list of Mercedes we need to write some additional code. First make some refinement how the parser should process the XML you can set some property with the xml_parser_set_option() function
In our example I set the case folding property to false, which generally means that no tag name will convert to uppercase.

PHP Code:
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);

XML element handlers

Besides this we have to tell the parser what to do if an opening or closing tag is found. To do this I wrote two functions to handle these events. Both have a well defined attribute list.

PHP Code:
function openElement($parser, $element, $attributes)
function
closeElement($parser, $element)


The first parameter in both cases is the parser object. The second is the element name. The openElement has a third parameter the attributes which is an array representation of the actual element attribute names and values.

You can assign these function to the parser as follows:

PHP Code:
xml_set_element_handler($parser, "openElement", "closeElement");


Take care that the functions defined above must have the same names as the parameters of the xml_set_element_handler. As result if the parser finds an open element than it will call the openElement function. Of course it calls closeElement if a closing tag was found.

XML data handler

One more thing is missing. A handler function to process the XML data values. For that I implemented a new function:

PHP Code:
function characterData($parser, $data);


The first parameter is already known. The second contains the actual data value. To make the assignment you should use the following statement:

PHP Code:
xml_set_character_data_handler($parser, "characterData");




Now the full code looks like this:

PHP Code:
<?php

function openElement($parser, $element, $attributes) {
}

function closeElement($parser, $element) {
}

function characterData($parser, $data) {
}

$parser = xml_parser_create();

xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, "openElement", "closeElement");
xml_set_character_data_handler($parser, "characterData");

$document = file_get_contents("test.xml");
xml_parse($parser, $document);

xml_parser_free($parser);

?>

Of course this code will result again is an empty page. Just to have some output and demonstrate how the functions are called I added some code in the handler functions.

The new code is:

PHP Code:
<?php

function openElement($parser, $element, $attributes) {
foreach (
$attributes as $key => $value) $attr .= $key." : ".$value." - ";
echo
"-> openElement element: $element, attribute: $attributes ($attr) <br/>";
}

function closeElement($parser, $element) {
echo
"-> closeElement element is: $element<br/>";
}

function characterData($parser, $data) {
echo
"-> characterData data is: [$data]<br/>";
}

$parser = xml_parser_create();

xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, "openElement", "closeElement");
xml_set_character_data_handler($parser, "characterData");

$document = file_get_contents("test.xml");
xml_parse($parser, $document);

xml_parser_free($parser);

?>

And the output is:

-> openElement element: carlist, attribute: Array ()
-> characterData data is: [ ]
-> characterData data is: [ ]
-> openElement element: car, attribute: Array (type : Mercedes – )
-> characterData data is: [S 600]
-> closeElement element is: car
-> characterData data is: [ ]
-> characterData data is: [ ]
-> openElement element: car, attribute: Array (type : Mercedes – )
-> characterData data is: [E 270 CDI]
-> closeElement element is: car
-> characterData data is: [ ]
-> characterData data is: [ ]
-> openElement element: car, attribute: Array (type : BMW – )
-> characterData data is: [535 D]
-> closeElement element is: car
-> characterData data is: [ ]
-> characterData data is: [ ]
-> openElement element: car, attribute: Array (type : Lexus – )
-> characterData data is: [IS 220]
-> closeElement element is: car
-> characterData data is: [ ]
-> closeElement element is: carlist

In the output you can find the root element <carlist>, the four child elements <car> the attribute list and the data values.
The only interesting thing is why we have so many time characterData with an empty string?
To understand this you should open the XML file and displays the hidden characters. After it you can see that there is a new line character after a <carlist> element and it is handled as a data value. After it in the second line there are some spaces before the <car> element and it results again a characterData call.
Try to remove all hidden character from the test.xml.

The result will be the following:

-> openElement element: carlist, attribute: Array ()
-> openElement element: car, attribute: Array (type : Mercedes – )
-> characterData data is: [S 600]
-> closeElement element is: car
-> openElement element: car, attribute: Array (type : Mercedes – )
-> characterData data is: [E 270 CDI]
-> closeElement element is: car
-> openElement element: car, attribute: Array (type : BMW – )
-> characterData data is: [535 D]
-> closeElement element is: car
-> openElement element: car, attribute: Array (type : Lexus – )
-> characterData data is: [IS 220]
-> closeElement element is: car
-> closeElement element is: carlist

Now it is much more clear. Of course you don’t have to remove these characters from the XML. I did it just to demonstrate how the processing works.

Last steps

We are almost ready. Some further modification and we have the list of Mercedeses. To do that we have to change the handler functions code as follows:

function openElement($parser, $element, $attributes) {
global
$flag;
if ((
$element == ‘car’) && ($attributes['type'] == ‘Mercedes’)) $flag = true;
}

function closeElement($parser, $element) {
global
$flag;
$flag = false;
}

function characterData($parser, $data) {
global
$flag,$mblist;
if (
$flag) $mblist[] = $data;
}


The $flag and $type are defined outside of the functions and used inside as global variables.

  • - The openElement function sets the flag to true if a car with the type of Mercedes was found.
  • - The closeElement function resets the flag, to represent we are using not more the relevant element.
  • - The characterData function checks the flag and if it is set – means that the actual element is a car and the attribute type is Mercedes – than add the data value to the type array.

At the end we have an array with the requested list. Just display it. The complete code looks like this:

PHP Code:
<?php

$mblist = '';
$flag = false;

function openElement($parser, $element, $attributes) {
global
$flag;
if ((
$element == 'car') && ($attributes['type'] == 'Mercedes')) $flag = true;
}

function closeElement($parser, $element) {
global
$flag;
$flag = false;
}

function characterData($parser, $data) {
global
$flag,$mblist;
if (
$flag) $mblist[] = $data;
}

$parser = xml_parser_create();

xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, "openElement", "closeElement");
xml_set_character_data_handler($parser, "characterData");

$document = file_get_contents("test.xml");
xml_parse($parser, $document);

xml_parser_free($parser);

foreach ($mblist as $value) {
echo
$value.'<br/>';
}

?>



And the output is:

S 600
E 270 CDI

Final words

I hope that this small tutorial helps you to understand the basics of PHP XML processing. If everything is clear then it will not cause any further problem to extend the script and process your own XML file.

Thanks for your time and attention!

Posted by admin on December-11-2009 Add Comments

Simple PHP Hit Counter Script

Important

It is worth noting that this tutorial is paginated, and that the entire tutorial contains 4 pages. Just remember that the tutorial is not finished just after the first page!

PHP 4+ is required for this tutorial. PHP 5 is optional

This tutorial is for beginners with very limited knowledge of PHP. You will learn to make a very simple hit counter. The counter isn’t important — it’s the techniques used that you should try to remember. Something similar will pop up later on, so try to remember what was said in this tutorial.

If you are rather experienced with PHP, you still can follow along. It never hurts to brush up on some old easy stuff. I will show you how to create a hit counter (not uniques, just simple hits) using a flatfile. Alright, let’s get started.

Step 1 A

Open your text editor and create a new document. I will use NotePad as an example here. Before you even start typing a single thing, press File -> Save As… and save your document first. We want to create all our files first before starting the code.

I saved my file as “counter.php“. The name doesn’t matter, but make sure you don’t forget the .php extension.

Step 1 B

Now, we need to create a new file to store the number of hits. This is called a flat file. A flat file is similar to a database, but it is a file instead. Press File -> New. This new file will consist of nothing but a number. This number will be the hit count. Because we’ve just started, type “0” in the document and press File->Save As…. Save this file as a TXT document. I named mine “hits.txt”, but you can name it differently.

Step 2

Alright, now that we’ve got our files set up, lets start codin’. Open up counter.php (or whatever you named it) and type the PHP tags.

PHP Code:
<?php

?>

Step 3

Now, we open up the flat file (hits.txt) and tell PHP to read the number inside and set it as a variable (we’ve already put “0″ into hits.txt)

PHP Code:
<?php
$hits
= file_get_contents("hits.txt");

?>

The function file_get_contents reads all the text in the file that is quoted in the first argument (the first argument being hits.txt in this case) and puts it into a string. A string is simply data. It could be text, numbers, anything. In this case, it is only one thing — a number.

When we put “$hits =”, this means we are defining a variable. In this case, we are saying that the variable $hits (all variables must have a dollar sign before it) is equal to everything inside hits.txt (which in this case, is only “0″).

Step 4

Because we are viewing the file, we have to add a new hit to the counter. Take a look at the following code and try to figure out yourself what it means:

PHP Code:
<?php
$hits
= file_get_contents("hits.txt");
$hits = $hits + 1;

?>

The new line that I’ve added — “$hits = $hits + 1;” should be easy to decipher. I am redefining the variable $hits. This time, $hits is “$hits + 1″. The line basically says in plain english — $hits should now be whatever’s inside the file “hits.txt” plus one. What’s inside the file? Well, it was only 0… which means $hits should equal 0 + 1.. = 1.

Step 5

Now that we’ve updated the hits count to add one, lets update hits.txt to the NEW hits count.

Take a look at this code:

PHP Code:
<?php
$hits
= file_get_contents("hits.txt");
$hits = $hits + 1;

$handle = fopen("hits.txt", "w");
fwrite($handle, $hits);
fclose($handle);

?>

The function fopen opens the file “hits.txt” in the first argument. The “w” tells PHP that we are only opening the file to write, and nothing else. It also tells PHP to erase everything in the file and set the pointer (something like little flashing black line you see when you type in a text box) to the beginning.

Why do we need a variable? Because we need a handle from fopen to execute other commands like — in this case — fwrite(). To write, you have to tell PHP that you’ve previously opened the file — and give PHP the handle. The line “fwrite($handle, $hits);” tells PHP to write to the file specified in the $handle (”hits.txt”) and it also tells PHP to write $hits into the file. $hits — as we’ve already discovered — is the old hit number plus one. Now you can see somewhat of a hit counter resemblance. Adding one hit to the old number.

fclose() tells PHP that we’re done with the file, so close it.

Side Note — in PHP 5, it is possible to fopen, fwrite and fclose all at once with the function file_put_contents

Step 6

This part’s the easiest — output the number.

PHP Code:
<?php
$hits
= file_get_contents("hits.txt");
$hits = $hits + 1;

$handle = fopen("hits.txt", "w");
fwrite($handle, $hits);
fclose($handle);

print $hits;

?>

It’s a no-brainer: “print $hits”. It prints out whatever’s in the variable $hits — in this case, it’s “1″. But as time goes on, when we execute this script over and over again — it will always add 1 and so — this is a hit counter.

Completed

Now, assuming you saved this file as counter.php, in any other file you want to count hits — put

PHP Code:
<?php include "counter.php"; ?>

This will include the counter file — which will only output a number, and nothing else. You can put something like
There are <?php include “counter.php”; ?> hits.

or something like that.

Posted by admin on December-11-2009 Add Comments

Basic Variables

Basic Variables

PHP Code:
<?php
$hello
="Hello people,";
$php="this is my first PHP script.";
$php2="FTW!";
echo
$hello." ".$php." ".$php2;
?>

Outputs….

Quote:
Hello people, this is my first PHP script. FTW!
I could of used just one variable, for example….
PHP Code:
<?php
$text
="Hello people, his is my first PHP script. FTW!";
echo
$text;
?>

But I wanted to use multi variables ftw. Learn how to join them and put spaces between then and shiz.

The . is used to join two comands/variable outputs, like this.

PHP Code:
<?php
$hello
="Hello people,";
$php="this is my first PHP script.";
$php2="FTW!";
echo
$hello.$php.$php2;
?>

That would output…

Quote:
Hello people,this is my first PHP script.FTW!
See, there is no spaces in between the variables. So we want to add spaces yea? Yea ftw. So we use ” ” to add spaces between the variables. But we also want to join the variables after the space so we use . ” ” . between the variables like this.
PHP Code:
<?php
$hello
="Hello people,";
$php="this is my first PHP script.";
$php2="FTW!";
echo
$hello. " " .$php. " " .$php2;
?>