How to parse an XML file in PHP using XML parser

PHP offers a new and fast way to parse XML files. This approach makes it easier to parse very large XML files in a couple of seconds.

Here goes the code to parse a sample XML file. The XML in that file is also given below

<!-- The XML to be parsed with the code below -->

<person>
<name>Adeel Sarfraz</name>
<phone>123456790</phone>
<address>Karachi</address>
</person>


<?php

$parser = xml_parser_create();

// This function is called whenever a start tag is encountered 
function start($parser,$element_name,$element_attrs) {
 switch($element_name) {
    case "NAME":
           //Add code here
	    break; 
    case "PHONE":
            //Add code here
	    break; 
    case "ADDRESS":
            //Add code here
	    break; 
    default:
           //Add code here
	   break;
   }
}

// This function is called whenever an end tag is encountered
function stop($parser,$element_name) {
}

// This function is called when the data within the tags is to be read
function char($parser,$data) {
  	print $data;
}
xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,true);
$fp=fopen("example.xml","r");
while ($data=fread($fp,4096))  {
  xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser)));
}
xml_parser_free($parser);
?>

Hope the above helps.

How to read a zip file in PHP

If you want to read all the files a zip file contains and extract those files to a location on your computer then you can do the following.

First of all make sure that the zip package is included in your PHP distribution. I use Windows so Windows users can just uncomment the entry for php_zip.dll in php.ini and restart the IIS service to start using it.

<?php
$zip = zip_open("e:/myfiles/example.zip");
if ($zip) {
  while ($zip_entry = zip_read($zip)) {
    $fp = fopen("unzipped/".zip_entry_name($zip_entry), "w");
    if (zip_entry_open($zip, $zip_entry, "r")) {
      $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
      fwrite($fp,"$buf");
      zip_entry_close($zip_entry);
      fclose($fp);
    }
  }
  zip_close($zip);
}
else {
	print "error no. = ". $zip;
}
?>

As you can see from the above, we provided the exact location of the zip file and then read and copied each file to the unzipped folder.

Hope the above helps

How to download a file using CURL in PHP

Downloading a file is easy but what if you had to download a file through your page and save it on our machine.

Well here goes. We use our friendly CURL library in PHP for this. You can use the following code to download and save the file on your machine

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/example_file.zip");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$str = curl_exec($ch);
curl_close($ch);
$f = fopen("my_example_file.zip","w");
fwrite($f,$str);
fclose($f);
?>

That’s all there is to it. You can save the file by any name and start using it.

Hope the above helps

Custom Error Handling in PHP

While working on PHP websites you may have come across error messages like Fatal Error, Warning and Notice of one sort or the other. These are fine while the website is in development phase however once the website goes to production these messages do not look professional and the visitor may feel that the website does not look credible.

After all we are humans and bugs can creep into the system at any time so the best way is to implement custom error handling in your website i.e. telling PHP not to print error messages on the screen.

Use the following code:

<?php
/*First tell PHP we are going to handle error messages ourselves*/
error_reporting(0);                            
/*Include the script which contains the code to handle the error messages or write here*/
include "err_handle.php";
/*Give the name of the function which will be sent the error messages by PHP*/
$old_error_handler = set_error_handler("MyErrorHandler");
?>

Following is the code for err_handle.php

<?php
/* I am going to email my error messages. You can choose to save it into a file or database*/
function MyErrorHandler($errno, $errmsg, $filename, $linenum, $vars) 
{
    $strMesg = "";
    $xheaders="";

    $xheaders .= "From: <from_email_address>\n";
    $xheaders .= "X-Sender: <from_email_address>\n"; 
    $xheaders .= "X-Mailer: PHP\n"; 

    $strMesg .= "<b>My Error Log</b> \n";
    $strMesg .= "Error No : $errno\n";
    $strMesg .= "Error Message : $errmsg\n";
    $strMesg .= "Error File name : $filename\n";
    $strMesg .= "Error Line Number : $linenum\n";
    $strMesg .= "Error Date/Time : ". date("Y-m-d H:i:s (T)") ."\n";

    mail("<to_email_address>", "Error Log", $strMesg,$xheaders);
}
?>

Remember to place the above code in each file as you have to explicitly tell PHP in each page that you are going to handle the messages yourselves

Hope the above helps.

Passing by reference in PHP

There are two ways to pass a variable to a function. Pass by value and pass by reference.

Here we’ll discuss passing a variable by reference to a function. When you need to actually modify the value of the variable you need to pass it by reference. Actually reference means to pass the address of the variable in memory to the function (remember pointers). Then the function will use that address to actually use the actual value and modify it according to its working.

function passme( &$var ) {
   $var = 'tester';
}

$var1 = 'me';
passme($var1);
print $var1;        // prints tester

Hope it helps.

How to use AJAX to check user already exists or not in PHP

AJAX is a wonderful technology that provides the visitor with a “no refresh” experience on the web. With the advent and popularity of Web 2.0 this technology is making progress by leaps and bounds.

If you would like to verify whether a user is registered on your website or not then you can use the following code to implement that functionality.

As AJAX uses JavaScript we will be using the XMLHTTP object.

<script><!--
/*
Due to browser compatibility issues following function instantiates the right object with respect to the browser
*/

function getHTTPObject() {
var xmlhttp;

if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

// Instantiating the object
var http = getHTTPObject();
// --></script>

Next we will define the function which actually gets called to verify the user from the web page

<script><!--
function getMemberEmail() {
/*
Place validation code here to verify whether the input is in the correct format or not.  If it is not in the correct format then prompt user other wise start checking the user.
*/

sId = document.frmCheck.txtEmail.value;
document.getElementById('spnMessage').innerHTML = "Please wait...";
var url = "chk_user_email.php?e=";

// Note the http is a global variable as you can see from the above code

http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleResponse;
http.send(null);
}
// --></script>

Now we have to write the code which handles the response from the chk_user_email.php file.

<script><!--

function handleResponse() {
/*
We have to check the response status and whether the operation has completed or  not. 4 means completed and 200 means that response is OK.
*/

if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('spnMessage').innerHTML = results;
}
}
}
// --></script>

The complete code as it would appear on the page for the above example is below:

<script><!--
function getHTTPObject() {
var xmlhttp;

if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

var http = getHTTPObject();

function getMemberEmail() {

sId = document.frmCheck.txtEmail.value;
document.getElementById('spnMessage').innerHTML = "Please wait...";
var url = "chk_user_email.php?e=";

http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleResponse;
http.send(null);
}

function handleResponse() {

if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('spnMessage').innerHTML = results;
}
}
}
// --></script>
<form> <input name="txtEmail" type="text" />
<span id="spnMessage" type="text" /> </span>

</form>

Redirect from non-SSL to SSL pages in PHP

If you are working on a website which is hosted on a Windows machine and needs to be browsed in SSL aka Secure Sockets Layer by visitors then you can use the following code to make sure that visitors are made to do it.

Place the following code at the top of the file.

First build the SSL URL by using the following code:

if ($_SERVER['QUERY_STRING'] == "") {
	$strNewUrl = "https://". $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
}
else {
	$strNewUrl = "https://". $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] ."?" . $_SERVER['QUERY_STRING'];
}

Now check if the visitor is browsing in non SSL mode or not. If he is then redirect him to the respective page in SSL mode.

if ($_SERVER['HTTPS'] == "off") {
	header("Location: $strNewUrl");
	exit;
}

New wordpress theme implemented on AdeelSarfaraz.com

Today I changed the theme of my blog. I sat down in the morning and downloaded WordPress and went to work on developing my own theme.

After a couple of hours here is what you see. It is not fancy in any way but it was my first go and Ill keep on improving its look as much as I can.

If you would like to use this them then you can download my version of the tableplain wordpress theme from here

Problems while installing Drupal 6.x

If you are facing problem on step 3 of Drupal installation where you enter your database name, username and password and after clicking Continue button the page just refreshes blanking out everything then the following fix applies to you if are on Windows 2003.

This problem has also been mentioned on Drupal website

1. Go to the sites/default folder.
2. Create an empty file by the name of settings.php in that folder.
3. Right click on settings.php and click on Security tab.
4. Search and add the IUSR_ account.
5. Give it read and write permissions on the settings.php file and proceed normally.

The installation will complete without a hitch.

Redirect from SSL URLs to non-SSL URLs in Zencart

A client of the company I work for pointed out a problem in which some how the SSL version of his website got indexed into Google and other search engines.  Now this posed a problem for the client as search engines don’t rank web pages well which can be referenced from two or more different urls.

As the website was in Zencart I knew that there was no option than to write code to effect redirection from SSL to non-SSL url.

So, I opened the html_header.php file present in the includes/templates/<Your_Template>/common folder and wrote the following code at the top:

<?php
if ($_SERVER['HTTPS'] == 'on') {
if (isset($_GET['main_page'])) {
$strMainPage = $_GET['main_page'];
switch($strMainPage) {
case 'index':
case 'product_info':
case 'privacy':
$strURL = "https://". $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
$arrFrom[] = "https://";
$arrTo[] = "http://";

$strURL = str_replace($arrFrom,$arrTo,$strUrl);
header("Location: $strUrl");
exit;
}
}
}
?>

The above code helped redirect those pages whose SSL version got indexed by mistake into the search engines. If you note from above I have not redirected post shopping cart pages as they need to be running in secure mode so that customer can enjoy safe and secure shopping.