Category Archives: PHP

Automatically generate .htaccess code for your website.

Greetings,

It is cumbersome and tedious to write .htaccess redirection rules.

Moreover due to its overall impact on the behaviour of the website, most developers refrain from writing code into htaccess. They usually take the help of their server support department to achieve this.

However now you can also generate .htaccess code depending on your requirement by visiting URL:
http://www.htaccessredirect.net/index.php

It has helped me a lot. Hope it helps you as well.

Thanks.

Working of Cookies when client & server times are different.

Sometimes we may wonder that,

How can a client (browser) set the correct expiry time of a cookie even though there is a difference between client time and server time?

Example:
Server Time: 21-Jan-2011 10:00:00 GMT
Client Time: 21-Jan-2012 10:00:00 GMT
(Note the 1 year difference between client and server times)

Now consider a scenario where server tells the client to store a cookie for the next 15 minutes.
So according to server’s time, the expiry time of the cookie will be 21-Jan-2011 10:15:00 GMT.
But the problem is client’s is already in the year 2012.
So how will client understand such an instruction from the server?

Answer to this lies in the response header passed by the server to the client.

Sample response header: (This is what the client gets from the server)
———————————————————-
HTTP/1.1 200 OK
Date: Fri, 21 Jan 2011 10:00:00 GMT
Server: Apache/2.2.14
X-Powered-By: PHP/5.3.1
Set-Cookie: username=abc, expires=Fri, 21-Jan-2011 10:15:00 GMT
Content-Length: 10
Connection: close
Content-Type: text/html
———————————————————-

So as visible from the above response from server, it sends its time along with the cookie expiry time.
From both these times, it is very easy for the client to calculate the expiry time of the cookie and set it relative to client’s own time.
(In this example the server wants client to preserve the cookie for the next 15 minutes)

Hope it helps clear some doubts.

Thanks.

PHP program to print simple message using echo and print.

Question: Write a PHP program to print simple message using echo and print.

Similarities between print and echo:
1. Both print and echo are used to display message on screen.
2. Both are language constructs and not functions.
3. Both can work with and without the parentheses.

Differences between print and echo:
1. echo does not return anything whereas print always returns 1.
2. echo can take multiple arguments whereas print can work with only 1 argument.

<?php

//All the following statements will print message 'Hello World'
print("Hello World");
print "<br />";
print "Hello World";
print "<br />";
print "Hello"." "."World";
print "<br />";

print 'Hello World';
print '<br />';
print 'Hello'.' '.'World';
print '<br />';

echo("Hello World");
echo "<br />";
echo "Hello World";
echo "<br />";
echo "Hello"." "."World";
echo "<br />";

echo 'Hello World';
echo '<br />';
echo 'Hello'.' '.'World';
echo '<br />';
echo "Hello", " ", "World";
echo "<br />";
echo 'Hello', ' ', 'World';
echo '<br />';

?>

PHP program to implement a Shopping Cart.

cart.rar

Question: Write a PHP program to implement basic Shopping Cart using the concept of Database & Session.

SQL to create database:

-- phpMyAdmin SQL Dump
-- version 3.2.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: May 02, 2013 at 10:51 AM
-- Server version: 5.1.41
-- PHP Version: 5.3.1

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `homeshop`
--

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `desc` varchar(255) NOT NULL,
  `price` int(11) NOT NULL,
  `category` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`id`, `name`, `desc`, `price`, `category`) VALUES
(1, 'Micromax Canvas 2', 'Micromax', 10000, 'mobile'),
(2, 'Zen XYZ', 'Zen', 5000, 'tablet'),
(3, 'Nokia Lumia', 'Nokia', 30000, 'mobile'),
(4, 'Sony Bravia', 'Sony', 25000, 'TV');

config.php

<?php

ini_set("error_reporting",E_ALL);
session_start();

?>

db-connect.php

<?php
$link = mysql_connect("localhost","root","") or die("Could not connect.");

mysql_select_db("homeshop");
?>

header.php

<a href="category.php">HomeShop</a>
<?php
if(isset($_SESSION['cart']))
{
	$total_products = count($_SESSION['cart']) - 1;
	$total_quantity = $_SESSION['cart']['total'];

	echo "($total_products - $total_quantity)";
	// echo "<pre>";
	// print_r($_SESSION['cart']);
	// echo "</pre>";
}
?>
<br /><br />

footer.php

<br />
Copyright HomeShop <?php echo date("Y"); ?>

category.php (This is the home page)

<?php
require_once("config.php");
?>
<html>
	<body>
		<?php require_once("header.php"); ?>

		<?php

		require_once("db-connect.php");

		$sql = "SELECT DISTINCT category FROM product";

		$rs = mysql_query($sql);

		while($row = mysql_fetch_assoc($rs))
		{
			$category = $row['category'];
			echo "<a href='product.php?cat=$category'>$category</a>";
			echo "<br />";	
		}

		?>

		<?php require_once("footer.php"); ?>
	</body>
</html>

product.php

<?php
require_once("config.php");
?>
<html>
	<body>
		<?php require_once("header.php"); ?>

		<?php		
		require_once("db-connect.php");

		$category = $_GET['cat'];

		$sql = "SELECT id, name FROM product WHERE category='$category'";
		$rs = mysql_query($sql);

		while($row = mysql_fetch_assoc($rs))
		{
			$prod_id = $row['id'];
			$prod_name = $row['name'];
			echo "<a href='product-details.php?pid=$prod_id'>$prod_name</a>";
			echo "<br />";
		}

		?>

		<?php require_once("footer.php"); ?>
	</body>
</html>

product-details.php

<?php
require_once("config.php");
?>
<html>
	<body>
		<?php require_once("header.php"); ?>

		<?php require_once("db-connect.php"); ?>

		<?php
		$product_id = $_GET['pid'];
		$_SESSION['prod_id'] = $product_id;

		$sql  = "SELECT * FROM product WHERE id='$product_id' LIMIT 1";
		$rs = mysql_query($sql);

		$row = mysql_fetch_assoc($rs);
		echo $row['name']."-".$row['desc'];
		echo "<br />";
		echo $row['price'];
		?>
		<form method="POST" action="add-cart.php">
			Quantity:
			<input type="text" name="quantity" value="1" />
			<br />
			<input type="submit" name="submit_form" value="Add to Cart" />
		</form>

		<?php require_once("footer.php"); ?>
	</body>
</html>

add-cart.php

<?php
require_once("config.php");

$product_id = $_SESSION['prod_id'];
$quantity = $_POST['quantity'];

if(isset($_SESSION['cart'][$product_id]))
{
	$_SESSION['cart'][$product_id] += $quantity;
}
else
{
	$_SESSION['cart'][$product_id] = $quantity;
}

if(isset($_SESSION['cart']['total']))
{
	$_SESSION['cart']['total'] += $quantity;
}
else
{
	$_SESSION['cart']['total'] = $quantity;
}

// echo "<pre>";
// print_r($_SESSION['cart']);
header("Location: category.php");
exit;

?>

PHP program to generate and parse (read) XML.

xml.rar

generate-xml.php

<?php

$data =
array(
	array("raj","mehta","99999","raj@raj.com"),
	array("rahul","bajaj","88888","rahul@rahul.com"),
);

$str = "<contact_data>";

foreach($data as $key=>$val)
{
	$str .= "<person>";
	$str .= "<fname>{$val[0]}</fname>";
	$str .= "<lname>{$val[1]}</lname>";
	$str .= "<phone>{$val[2]}</phone>";
	$str .= "<email>{$val[3]}</email>";
	$str .= "</person>";
}

$str .= "</contact_data>";

$fp = fopen("contacts.xml", "w+");
fwrite($fp, $str);

?>

read-xml.php

<?php

$xml_file = "contacts.xml";
$xsd_file = "contacts.xsd";

//Validate XML against XSD
$xml = new DOMDocument();
$xml->load($xml_file);
if($xml->schemaValidate($xsd_file))
{
	echo "Validated";

	$xml = simplexml_load_file($xml_file);
	print "<pre>";
	print_r($xml);
	foreach($xml->person as $person)
	{
		echo $person->fname;
		echo $person->lname;
		echo $person->phone;
		echo $person->email;
		echo "<br />";
	}
}
else
{
	echo "Not valid";
}

?>

contacts.xsd

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="contact_data">
  <xs:complexType>
    <xs:sequence>      
      <xs:element name="person" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="fname" type="xs:string"/>
            <xs:element name="lname" type="xs:string"/>
            <xs:element name="phone" type="xs:string"/>
            <xs:element name="email" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>