<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>PHPDemon</title>
	<atom:link href="http://phpdemon.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpdemon.wordpress.com</link>
	<description>Your Hell for PHP.</description>
	<lastBuildDate>Sat, 02 May 2009 12:21:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='phpdemon.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>PHPDemon</title>
		<link>http://phpdemon.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://phpdemon.wordpress.com/osd.xml" title="PHPDemon" />
	<atom:link rel='hub' href='http://phpdemon.wordpress.com/?pushpress=hub'/>
		<item>
		<title>PHP Filter</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-filter/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-filter/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:13:08 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=78</guid>
		<description><![CDATA[PHP filters are used to validate and filter data coming from insecure sources, like user input. What is a PHP Filter? A PHP filter is used to validate and filter data coming from insecure sources. To test, validate and filter user input or custom data is an important part of any web application. The PHP [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=78&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">PHP filters are used to validate and filter data coming from  insecure sources, like user input.</p>
<hr />
<h2>What is a PHP Filter?</h2>
<p>A PHP filter is used to validate and filter data coming from insecure sources.</p>
<p>To test, validate and filter user input or custom data is an important part  of any web application.</p>
<p>The PHP filter extension is designed to make data  filtering easier and quicker.</p>
<hr />
<h2>Why use a Filter?</h2>
<p>Almost all web applications depend on external input. Usually this comes from  a user or another application (like a web service). By using filters you can be  sure your application gets the correct input type.</p>
<p><strong>You should always filter all external data!</strong></p>
<p>Input filtering is one of the most important application security issues.</p>
<p>What is external data?</p>
<ul>
<li>Input data from a form</li>
<li>Cookies</li>
<li>Web services data</li>
<li>Server variables</li>
<li>Database query results</li>
</ul>
<hr />
<h2>Functions and Filters</h2>
<p>To filter a variable, use one of the following filter functions:</p>
<ul>
<li>filter_var() &#8211; Filters a single variable with a specified filter</li>
<li>filter_var_array() &#8211; Filter several variables with the same or different  	filters</li>
<li>filter_input &#8211; Get one input variable and filter it</li>
<li>filter_input_array &#8211; Get several input variables and filter them with  	the same or different filters</li>
</ul>
<p>In the example below, we validate an integer using the filter_var() function:</p>
<table id="table13" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$int = 123;</pre>
<pre>if(!filter_var($int, FILTER_VALIDATE_INT))
 {
 echo("Integer is not valid");
 }
else
 {
 echo("Integer is valid");
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above uses the &#8220;FILTER_VALIDATE_INT&#8221;  filter to filter the  variable. Since the integer is valid, the output of the code above will be:  &#8220;Integer is valid&#8221;.</p>
<p>If we try with a variable that is not an integer (like &#8220;123abc&#8221;), the output  will be: &#8220;Integer is not valid&#8221;.</p>
<p>For a complete list of functions and filters, visit our <a href="http://www.w3schools.com/PHP/php_ref_filter.asp">PHP Filter Reference.</a></p>
<hr />
<h2>Validating and Sanitizing</h2>
<p>There are two kinds of filters:</p>
<p>Validating filters:</p>
<ul>
<li>Are used to validate user input</li>
<li>Strict format rules (like URL or E-Mail validating)</li>
<li>Returns the expected type on success or FALSE on failure</li>
</ul>
<p>Sanitizing filters:</p>
<ul>
<li>Are used to allow or disallow specified characters in a string</li>
<li>No data format rules</li>
<li>Always return the string</li>
</ul>
<hr />
<h2>Options and Flags</h2>
<p>Options and flags are used to add additional filtering options to the  specified filters.</p>
<p>Different filters have different options and flags.</p>
<p>In the example below, we validate an integer using the filter_var() and the &#8220;min_range&#8221;  and &#8220;max_range&#8221; options:</p>
<table id="table14" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$var=300;</pre>
<pre>$int_options = array(
"options"=&gt;array
 (
 "min_range"=&gt;0,
 "max_range"=&gt;256
 )
);</pre>
<pre>if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
 {
 echo("Integer is not valid");
 }
else
 {
 echo("Integer is valid");
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Like the code above, options must be put in an associative array with the  name &#8220;options&#8221;. If a flag is used it does not need to be in an array.</p>
<p>Since the integer is &#8220;300&#8243; it is not in the specified range, and the output of the code above will be:  &#8220;Integer is not valid&#8221;.</p>
<p>For a complete list of functions and filters, visit our <a href="http://www.w3schools.com/PHP/php_ref_filter.asp">PHP Filter Reference.</a> Check each filter to see  what options and flags are available.</p>
<hr />
<h2>Validate Input</h2>
<p>Let&#8217;s try validating input from a form.</p>
<p>The first thing we need to do is to confirm that the input data we are  looking for exists.</p>
<p>Then we filter the input data using the filter_input() function.</p>
<p>In the example below, the input variable &#8220;email&#8221; is sent to the PHP page:</p>
<table id="table3" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
if(!filter_has_var(INPUT_GET, "email"))
 {
 echo("Input type does not exist");
 }
else
 {
 if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL))
  {
  echo "E-Mail is not valid";
  }
 else
  {
  echo "E-Mail is valid";
  }
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has an input (email) sent to it using the &#8220;GET&#8221; method:</p>
<ol>
<li>Check if an &#8220;email&#8221; input variable of the &#8220;GET&#8221; type exist</li>
<li>If the input variable exists, check if it is a valid e-mail address</li>
</ol>
<hr />
<h2>Sanitize Input</h2>
<p>Let&#8217;s try cleaning up an URL sent from a form.</p>
<p>First we confirm that the input data we are  looking for exists.</p>
<p>Then we sanitize the input data using the filter_input() function.</p>
<p>In the example below, the input variable &#8220;url&#8221; is sent to the PHP page:</p>
<table id="table5" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
if(!filter_has_var(INPUT_POST, "url"))
 {
 echo("Input type does not exist");
 }
else
 {
 $url = filter_input(INPUT_POST,
 "url", FILTER_SANITIZE_URL);
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has an input (url) sent to it using the &#8220;POST&#8221; method:</p>
<ol>
<li>Check if the &#8220;url&#8221; input of the &#8220;POST&#8221; type exists</li>
<li>If the input variable exists, sanitize (take away invalid characters)  	and store it in the $url variable</li>
</ol>
<p>If the input variable is a string like this  &#8220;http://www.W3ååSchøøools.com/&#8221;, the $url variable after the sanitizing will  look like this:</p>
<table id="table16" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>http://www.W3Schools.com/</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Filter Multiple Inputs</h2>
<p>A form almost always consist of more than one input field. To avoid calling  the filter_var or filter_input functions over and over, we can use the  filter_var_array or the filter_input_array functions.</p>
<p>In this example we use the filter_input_array() function to filter three GET  variables. The received GET variables is a name, an age and an e-mail address:</p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$filters = array
 (
 "name" =&gt; array
  (
  "filter"=&gt;FILTER_SANITIZE_STRING
  ),
 "age" =&gt; array
  (
  "filter"=&gt;FILTER_VALIDATE_INT,
  "options"=&gt;array
   (
   "min_range"=&gt;1,
   "max_range"=&gt;120
   )
  ),
 "email"=&gt; FILTER_VALIDATE_EMAIL,
 );</pre>
<pre>$result = filter_input_array(INPUT_GET, $filters);</pre>
<pre>if (!$result["age"])
 {
 echo("Age must be a number between 1 and 120.&lt;br /&gt;");
 }
elseif(!$result["email"])
 {
 echo("E-Mail is not valid.&lt;br /&gt;");
 }
else
 {
 echo("User input is valid");
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has three inputs (name, age and email) sent to it using the &#8220;GET&#8221; method:</p>
<ol>
<li>Set an array containing the name of input variables and the filters used  	on the specified input variables</li>
<li>Call the filter_input_array() function with the GET input variables and  	the array we just set</li>
<li>Check the &#8220;age&#8221; and &#8220;email&#8221; variables in the $result variable for  	invalid inputs. (If any of the input variables are invalid, that input  	variable will be FALSE after the filter_input_array() function)</li>
</ol>
<p>The second parameter of the filter_input_array() function can be an array or  a single filter ID.</p>
<p>If the parameter is a single filter ID all values in the input array are  filtered by the specified filter.</p>
<p>If the parameter is an array it must follow these rules:</p>
<ul>
<li>Must be an associative array containing an input variable as an array key  	(like the &#8220;age&#8221; input variable)</li>
<li>The array value must be a filter ID or an array specifying the  	filter, flags and options</li>
</ul>
<hr />
<h2>Using Filter Callback</h2>
<p>It is possible to call a user defined function and use it as a filter using  the FILTER_CALLBACK filter. This way, we have full control of the data  filtering.</p>
<p>You can create your own user defined function or use an existing PHP function</p>
<p>The function you wish to use to filter is specified the same way as an option  is specified. In an associative array with the name &#8220;options&#8221;</p>
<p>In the example below, we use a user created function to convert all  &#8220;_&#8221;  to whitespaces:</p>
<table id="table8" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
function convertSpace($string)
{
return str_replace("_", " ", $string);
}

$string = "Peter_is_a_great_guy!";

echo filter_var($string, FILTER_CALLBACK,
array("options"=&gt;"convertSpace"));
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The result from the code above should look like this:</p>
<table id="table17" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>Peter is a great guy!</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above converts all &#8220;_&#8221; to whitespaces:</p>
<ol>
<li>Create a function to replace &#8220;_&#8221; to whitespaces</li>
<li>Call the filter_var() function with the FILTER_CALLBACK filter and an  	array containing our function</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/78/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=78&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-filter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Exception Handling</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-exception-handling/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-exception-handling/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:12:30 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=76</guid>
		<description><![CDATA[Exceptions are used to change the normal flow of a script if a specified error occurs What is an Exception With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=76&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">Exceptions are used to change the normal flow of a script if a  specified error occurs</p>
<hr />
<h2>What is an Exception</h2>
<p>With PHP 5 came a new object oriented way of dealing with errors.</p>
<p>Exception handling is used to change the normal flow of the code execution if  a specified error (exceptional) condition occurs. This condition is called an  exception.</p>
<p>This is what normally happens when an exception is triggered:</p>
<ul>
<li>The current code state is saved</li>
<li>The code execution will switch to a predefined (custom) exception  	handler function</li>
<li>Depending on the situation, the handler may then resume the execution  	from the saved code state, terminate the script execution or continue the  	script from a different location in the code</li>
</ul>
<p>We will show different error handling methods:</p>
<ul>
<li>Basic use of Exceptions</li>
<li>Creating a custom exception handler</li>
<li>Multiple exceptions</li>
<li>Re-throwing an exception</li>
<li>Setting a top level exception handler</li>
</ul>
<p><strong>Note:</strong> Exceptions should only be used with error conditions, and should not be used  to jump to another place in the code at a specified point.</p>
<hr />
<h2>Basic Use of Exceptions</h2>
<p>When an exception is thrown, the code following it will not be executed, and  PHP will try to find the matching &#8220;catch&#8221; block.</p>
<p>If an exception is not caught, a fatal error will be issued with an &#8220;Uncaught  Exception&#8221; message.</p>
<p>Lets try to throw an exception without catching it:</p>
<table id="table42" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
//create function with an exception
function checkNum($number)
 {
 if($number&gt;1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//trigger exception
checkNum(2);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above will get an error like this:</p>
<table id="table43" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Fatal error</strong>: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in <strong>C:\webfolder\test.php</strong> on line <strong>6</strong></pre>
</td>
</tr>
</tbody>
</table>
<h2>Try, throw and catch</h2>
<p>To avoid the error from the example above, we need to create the proper code  to handle an exception.</p>
<p>Proper exception code should include:</p>
<ol>
<li>Try &#8211; A function using an exception should be in a &#8220;try&#8221; block. If the  	exception does not trigger, the code will continue as normal. However if the  	exception triggers, an exception is &#8220;thrown&#8221;</li>
<li>Throw &#8211; This is how you trigger an exception. Each &#8220;throw&#8221; must have at  	least one &#8220;catch&#8221;</li>
<li>Catch &#8211; A &#8220;catch&#8221; block retrieves an exception and creates an object  	containing the exception information</li>
</ol>
<p>Lets try to trigger an exception with valid code:</p>
<table id="table15" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
//create function with an exception
function checkNum($number)
 {
 if($number&gt;1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//trigger exception in a "try" block
try
 {
 checkNum(2);
 //If the exception is thrown, this text will not be shown
 echo 'If you see this, the number is 1 or below';
 }

//catch exception
catch(Exception $e)
 {
 echo 'Message: ' .$e-&gt;getMessage();
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above will get an error like this:</p>
<table id="table14" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>Message: Value must be 1 or below</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example explained:</h2>
<p>The code above throws an exception and catches it:</p>
<ol>
<li>The checkNum() function is created. It checks if a number is greater  	than 1. If it is, an exception is thrown</li>
<li>The checkNum() function is called in a &#8220;try&#8221; block</li>
<li>The exception within the checkNum() function is thrown</li>
<li>The &#8220;catch&#8221; block retrives the exception and creates an object ($e)  	containing the exception information</li>
<li>The error message from the exception is echoed by calling $e-&gt;getMessage()  	from the exception object</li>
</ol>
<p>However, one way to get around the &#8220;every throw must have a catch&#8221; rule is to  set a top level exception handler to handle errors that slip through.</p>
<hr />
<h2>Creating a Custom Exception Class</h2>
<p>Creating a custom exception handler is quite simple. We simply create a special  class with functions that can be called when an exception occurs in PHP. The  class must be an extension of the exception class.</p>
<p>The custom exception class inherits the properties from PHP&#8217;s  exception class and you can add custom functions to it.</p>
<p>Lets create an exception class:</p>
<table id="table24" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
class customException extends Exception
 {
 public function errorMessage()
  {
  //error message
  $errorMsg = 'Error on line '.$this-&gt;getLine().' in '.$this-&gt;getFile()
  .': &lt;b&gt;'.$this-&gt;getMessage().'&lt;/b&gt; is not a valid E-Mail address';
  return $errorMsg;
  }
 }</pre>
<pre>$email = "someone@example...com";</pre>
<pre>try
 {
 //check if
 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
  {
  //throw exception if email is not valid
  throw new customException($email);
  }
 }</pre>
<pre>catch (customException $e)
 {
 //display custom message
 echo $e-&gt;errorMessage();
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The new class is a copy of the old exception class with an addition of the  errorMessage() function. Since it is a copy of the old class, and it inherits  the properties and methods from the old class, we can use the exception class  methods like getLine() and getFile() and getMessage().</p>
<h2>Example explained:</h2>
<p>The code above throws an exception and catches it with a custom exception  class:</p>
<ol>
<li>The customException() class is created as an extension of the old  	exception class. This way it inherits all methods and properties from the  	old exception class</li>
<li>The errorMessage() function is created. This function returns an error  	message if an e-mail address is invalid</li>
<li>The $email variable is set to a string that is not a valid e-mail  	address</li>
<li>The &#8220;try&#8221; block is executed and an exception is thrown since  	the e-mail address is invalid</li>
<li>The &#8220;catch&#8221; block catches the exception and displays the error message</li>
</ol>
<hr />
<h2>Multiple Exceptions</h2>
<p>It is possible for a script to use multiple exceptions to check for multiple  conditions.</p>
<p>It is possible to use several if..else blocks, a switch, or nest multiple  exceptions. These exceptions can use different exception classes and return  different error messages:</p>
<table id="table51" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this-&gt;getLine().' in '.$this-&gt;getFile()
.': &lt;b&gt;'.$this-&gt;getMessage().'&lt;/b&gt; is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try
 {
 //check if
 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
  {
  //throw exception if email is not valid
  throw new customException($email);
  }
 //check for "example" in mail address
 if(strpos($email, "example") !== FALSE)
  {
  throw new Exception("$email is an example e-mail");
  }
 }

catch (customException $e)
 {
 echo $e-&gt;errorMessage();
 }</pre>
<pre>catch(Exception $e)
 {
 echo $e-&gt;getMessage();
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example explained:</h2>
<p>The code above tests two conditions and throws an exception if any of the  conditions are not met:</p>
<ol>
<li>The customException() class is created as an extension of the old  	exception class. This way it inherits all methods and properties from the  	old exception class</li>
<li>The errorMessage() function is created. This function returns an error  	message if an e-mail address is invalid</li>
<li>The $email variable is set to a string that is a valid e-mail  	address, but contains the string &#8220;example&#8221;</li>
<li>The &#8220;try&#8221; block is executed and an exception is not thrown on  	the first condition</li>
<li>The second condition triggers an exception since the e-mail contains the  	string &#8220;example&#8221;</li>
<li>The &#8220;catch&#8221; block catches the exception and displays the  	correct error message</li>
</ol>
<p>If there was no customException catch, only the base exception catch, the  exception would be handled there</p>
<hr />
<h2>Re-throwing Exceptions</h2>
<p>Sometimes, when an exception is thrown, you may wish to handle it  differently than the standard way. It is possible to throw an exception a second  time within a &#8220;catch&#8221; block.</p>
<p>A script should hide system errors from users. System errors may be important  for the coder, but is of no interest to the user. To make things easier for the  user you can re-throw the exception with a user friendly message:</p>
<table id="table52" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
class customException extends Exception
 {
 public function errorMessage()
  {
  //error message
  $errorMsg = $this-&gt;getMessage().' is not a valid E-Mail address.';
  return $errorMsg;
  }
 }</pre>
<pre>$email = "someone@example.com";</pre>
<pre>try
 {
 try
  {
  //check for "example" in mail address
  if(strpos($email, "example") !== FALSE)
   {
   //throw exception if email is not valid
   throw new Exception($email);
   }
  }
 catch(Exception $e)
  {
  //re-throw exception
  throw new customException($email);
  }
 }</pre>
<pre>catch (customException $e)
 {
 //display custom message
 echo $e-&gt;errorMessage();
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h2>Example explained:</h2>
<p>The code above tests if the email-address contains the string &#8220;example&#8221; in  it, if it does, the exception is re-thrown:</p>
<ol>
<li>The customException() class is created as an extension of the old  	exception class. This way it inherits all methods and properties from the  	old exception class</li>
<li>The errorMessage() function is created. This function returns an error  	message if an e-mail address is invalid</li>
<li>The $email variable is set to a string that is a valid e-mail  	address, but contains the string &#8220;example&#8221;</li>
<li>The &#8220;try&#8221; block contains another &#8220;try&#8221; block to make it  	possible to re-throw the exception</li>
<li>The exception is triggered since the e-mail contains the string  	&#8220;example&#8221;</li>
<li>The &#8220;catch&#8221; block catches the exception and re-throws a &#8220;customException&#8221;</li>
<li>The &#8220;customException&#8221; is caught and displays an error message</li>
</ol>
<p>If the exception is not caught in its current &#8220;try&#8221; block, it will search for a catch block on &#8220;higher levels&#8221;.</p>
<hr />
<h2>Set a Top Level Exception Handler</h2>
<p>The set_exception_handler() function sets a user-defined function to handle all  uncaught exceptions.</p>
<table id="table53" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
function myException($exception)
{
echo "&lt;b&gt;Exception:&lt;/b&gt; " , $exception-&gt;getMessage();
}</pre>
<pre>set_exception_handler('myException');</pre>
<pre>throw new Exception('Uncaught Exception occurred');
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table id="table54" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Exception:</strong> Uncaught Exception occurred</pre>
</td>
</tr>
</tbody>
</table>
<p>In the code above there was no &#8220;catch&#8221; block. Instead, the top level  exception handler triggered. This function should be used to catch uncaught  exceptions.</p>
<hr />
<h2>Rules for exceptions</h2>
<ul>
<li>Code may be surrounded in a try block, to help catch potential  	exceptions</li>
<li>Each try block or &#8220;throw&#8221; must have at least one corresponding catch  	block</li>
<li>Multiple catch blocks can be used to catch different classes of  	exceptions</li>
<li>Exceptions can be thrown (or re-thrown) in a catch block within a try  	block</li>
</ul>
<p>A simple rule: If you throw something, you have to catch it.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/76/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/76/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/76/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=76&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-exception-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Error Handling</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-error-handling/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-error-handling/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:11:48 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=74</guid>
		<description><![CDATA[The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser. PHP Error Handling When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=74&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">The default error handling in PHP is very simple. An error message with filename, line  number and a message describing the error is sent to the browser.</p>
<hr />
<h2>PHP Error Handling</h2>
<p>When creating scripts and web applications, error handling is an important  part. If your code lacks error checking code, your program may look very  unprofessional and you may be open to security risks.</p>
<p>This tutorial contains some  of the most common error checking methods in PHP.</p>
<p>We will show different error handling methods:</p>
<ul>
<li>Simple &#8220;die()&#8221; statements</li>
<li>Custom errors and error triggers</li>
<li>Error reporting</li>
</ul>
<hr />
<h2>Basic Error Handling: Using the die() function</h2>
<p>The first example shows a simple script that opens a text file:</p>
<table id="table12" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$file=fopen("welcome.txt","r");
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>If the file does not exist you might get an error like this:</p>
<table id="table13" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Warning</strong>: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in <strong>C:\webfolder\test.php</strong> on line <strong>2</strong></pre>
</td>
</tr>
</tbody>
</table>
<p>To avoid that the user gets an error message like the one above, we test if  the file exist before we try to access it:</p>
<table id="table15" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
if(!file_exists("welcome.txt"))
 {
 die("File not found");
 }
else
 {
 $file=fopen("welcome.txt","r");
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Now if the file does not exist you get an error like this:</p>
<table id="table14" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>File not found</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above is more efficient than the earlier code, because it  uses a simple error handling mechanism to stop the script after the error.</p>
<p>However, simply stopping the script is not always the right way to go. Let&#8217;s take a  look at alternative PHP functions for handling errors.</p>
<hr />
<h2>Creating a Custom Error Handler</h2>
<p>Creating a custom error handler is quite simple. We simply create a special  function that can be called when an error occurs in PHP.</p>
<p>This function must be able to handle a minimum of two parameters (error  level and error message) but can accept up to five parameters (optionally: file,  line-number, and the error context):</p>
<h2>Syntax</h2>
<table id="table21" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>error_function(error_level,error_message,
error_file,error_line,error_context)</pre>
</td>
</tr>
</tbody>
</table>
<table class="reference" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<th width="20%" align="left" valign="top">Parameter</th>
<th width="80%" align="left" valign="top">Description</th>
</tr>
<tr>
<td valign="top">error_level</td>
<td valign="top">Required. Specifies the error report level for the  		user-defined error. Must be a value number. See table below for possible  		error report levels</td>
</tr>
<tr>
<td valign="top">error_message</td>
<td valign="top">Required. Specifies the error message for the  		user-defined error</td>
</tr>
<tr>
<td valign="top">error_file</td>
<td valign="top">Optional. Specifies the filename in which the error  		occurred</td>
</tr>
<tr>
<td valign="top">error_line</td>
<td valign="top">Optional. Specifies the line number in which the error  		occurred</td>
</tr>
<tr>
<td valign="top">error_context</td>
<td valign="top">Optional. Specifies an array containing every variable,  		and their values, in use when the error occurred</td>
</tr>
</tbody>
</table>
<h2>Error Report levels</h2>
<p>These error report levels are the different types of error the user-defined  error handler can be used for:</p>
<table class="reference" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<th width="5%" align="left">Value</th>
<th width="30%" align="left">Constant</th>
<th width="65%" align="left">Description</th>
</tr>
<tr>
<td valign="top">2</td>
<td valign="top">E_WARNING</td>
<td valign="top">Non-fatal run-time errors. Execution of the script is not  	halted</td>
</tr>
<tr>
<td valign="top">8</td>
<td valign="top">E_NOTICE</td>
<td valign="top">Run-time notices. The script found something that might be  	an error, but could also happen when running a script normally</td>
</tr>
<tr>
<td valign="top">256</td>
<td valign="top">E_USER_ERROR</td>
<td valign="top">Fatal user-generated error. This is like an E_ERROR set by  	the programmer using the PHP function trigger_error()</td>
</tr>
<tr>
<td valign="top">512</td>
<td valign="top">E_USER_WARNING</td>
<td valign="top">Non-fatal user-generated warning. This is like an E_WARNING  	set by the programmer using the PHP function trigger_error()</td>
</tr>
<tr>
<td valign="top">1024</td>
<td valign="top">E_USER_NOTICE</td>
<td valign="top">User-generated notice. This is like an E_NOTICE set by the  	programmer using the PHP function trigger_error()</td>
</tr>
<tr>
<td valign="top">4096</td>
<td valign="top">E_RECOVERABLE_ERROR</td>
<td valign="top">Catchable fatal error. This is like an E_ERROR but can be  	caught by a user defined handle (see also set_error_handler())</td>
</tr>
<tr>
<td valign="top">8191</td>
<td valign="top">E_ALL</td>
<td valign="top">All errors and warnings, except level E_STRICT (E_STRICT  	will be part of E_ALL as of PHP 6.0)</td>
</tr>
</tbody>
</table>
<p>Now lets create a function to handle errors:</p>
<table id="table24" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>function customError($errno, $errstr)
 {
 echo "&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;";
 echo "Ending Script";
 die();
 }</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above is a simple error handling function. When it is triggered, it  gets the error level and an error message. It then outputs the error level and  message and terminates the script.</p>
<p>Now that we have created an error handling function we need to decide when it  should be triggered.</p>
<hr />
<h2>Set Error Handler</h2>
<p>The default error handler for PHP is the built in error handler. We are  going to make the function above the default error handler for the duration of  the script.</p>
<p>It is possible to change the error handler to apply for only some errors,  that way the script can handle different errors in different ways. However, in  this example we are going to use our custom error handler for all errors:</p>
<table id="table25" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>set_error_handler("customError");</pre>
</td>
</tr>
</tbody>
</table>
<p>Since we want our custom function to handle all errors, the set_error_handler()  only needed one parameter, a second parameter could be added to specify an error  level.</p>
<h2>Example</h2>
<p>Testing the error handler by trying to output variable that does not exist:</p>
<table id="table26" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
//error handler function
function customError($errno, $errstr)
 {
 echo "&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr";
 }</pre>
<pre>//set error handler
set_error_handler("customError");</pre>
<pre>//trigger error
echo($test);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table id="table27" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Error:</strong> [8] Undefined variable: test</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Trigger an Error</h2>
<p>In a script where users can input data it is useful to trigger errors when an  illegal input occurs. In PHP, this is done by the trigger_error() function.</p>
<h2>Example</h2>
<p>In this example an error occurs if the &#8220;test&#8221; variable is bigger than &#8220;1&#8243;:</p>
<table id="table32" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$test=2;
if ($test&gt;1)
{
trigger_error("Value must be 1 or below");
}
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table id="table33" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Notice</strong>: Value must be 1 or below
in <strong>C:\webfolder\test.php</strong> on line <strong>6</strong></pre>
</td>
</tr>
</tbody>
</table>
<p>An error can be triggered anywhere you wish in a script, and by adding a  second parameter, you can specify what error level is triggered.</p>
<p>Possible error types:</p>
<ul>
<li>E_USER_ERROR &#8211; Fatal user-generated run-time error. Errors that can not  	be recovered from. Execution of the script is halted</li>
<li>E_USER_WARNING &#8211; Non-fatal user-generated run-time warning. Execution of  	the script is not halted</li>
<li>E_USER_NOTICE &#8211; Default. User-generated run-time notice. The script  	found something that might be an error, but could also happen when running a  	script normally</li>
</ul>
<h2>Example</h2>
<p>In this example an E_USER_WARNING occurs if the &#8220;test&#8221; variable is bigger  than &#8220;1&#8243;. If an E_USER_WARNING occurs we will use our custom error handler  and end the script:</p>
<table id="table36" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
//error handler function
function customError($errno, $errstr)
 {
 echo "&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;";
 echo "Ending Script";
 die();
 }</pre>
<pre>//set error handler
set_error_handler("customError",E_USER_WARNING);</pre>
<pre>//trigger error
$test=2;
if ($test&gt;1)
 {
 trigger_error("Value must be 1 or below",E_USER_WARNING);
 }
?&gt;</pre>
<pre></pre>
</td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table id="table37" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Error:</strong> [512] Value must be 1 or below
Ending Script</pre>
</td>
</tr>
</tbody>
</table>
<p>Now that we have learned to create our own errors and how to trigger them,  lets take a look at error logging.</p>
<hr />
<h2>Error Logging</h2>
<p>By default, PHP sends an error log to the servers logging system or a file,  depending on how the error_log configuration is set in the php.ini file. By  using the error_log() function you can send error logs to a specified file or a  remote destination.</p>
<p>Sending errors messages to yourself by e-mail can be a good way of getting  notified of specific errors.</p>
<h2>Send an Error Message by E-Mail</h2>
<p>In the example below we will send an e-mail with an error message and end the  script, if a specific error occurs:</p>
<table id="table40" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
//error handler function
function customError($errno, $errstr)
 {
 echo "&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;";
 echo "Webmaster has been notified";
 error_log("Error: [$errno] $errstr",1,
 "someone@example.com","From: webmaster@example.com");
}</pre>
<pre>//set error handler
set_error_handler("customError",E_USER_WARNING);</pre>
<pre>//trigger error
$test=2;
if ($test&gt;1)
 {
 trigger_error("Value must be 1 or below",E_USER_WARNING);
 }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table id="table42" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Error:</strong> [512] Value must be 1 or below
Webmaster has been notified</pre>
</td>
</tr>
</tbody>
</table>
<p>And the mail received from the code above looks like this:</p>
<table id="table41" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>Error: [512] Value must be 1 or below</pre>
</td>
</tr>
</tbody>
</table>
<p>This should not be used with all errors. Regular errors should be logged on  the server using the default PHP logging system.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/74/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/74/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/74/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=74&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-error-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Secure E-mails</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-secure-e-mails/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-secure-e-mails/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:10:58 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=72</guid>
		<description><![CDATA[There is a weakness in the PHP e-mail script in the previous chapter. PHP E-mail Injections First, look at the PHP code from the previous chapter: &#60;html&#62; &#60;body&#62; &#60;?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email { //send email $email = $_REQUEST['email'] ; $subject = $_REQUEST['subject'] ; $message = $_REQUEST['message'] ; mail("someone@example.com", "Subject: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=72&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">There is a weakness in the PHP e-mail script in the previous  chapter.</p>
<hr />
<h2>PHP E-mail Injections</h2>
<p>First, look at the PHP code from the previous chapter:</p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //send email
  $email = $_REQUEST['email'] ;
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail("someone@example.com", "Subject: $subject",
  $message, "From: $email" );
  echo "Thank you for using our mail form";
  }
else
//if "email" is not filled out, display the form
  {
  echo "&lt;form method='post' action='mailform.php'&gt;
  Email: &lt;input name='email' type='text' /&gt;&lt;br /&gt;
  Subject: &lt;input name='subject' type='text' /&gt;&lt;br /&gt;
  Message:&lt;br /&gt;
  &lt;textarea name='message' rows='15' cols='40'&gt;
  &lt;/textarea&gt;&lt;br /&gt;
  &lt;input type='submit' /&gt;
  &lt;/form&gt;";
  }
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The problem with the code above is that unauthorized users can insert data into the  mail headers via the input form.</p>
<p>What happens if the user adds the following text to the email input field in  the form?</p>
<table id="table4" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com</pre>
</td>
</tr>
</tbody>
</table>
<p>The mail() function puts the text above into the mail headers as usual, and now the  header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit  button, the e-mail will be sent to all of the addresses above!</p>
<hr />
<h2>PHP Stopping E-mail Injections</h2>
<p>The best way to stop e-mail injections is to validate the input.</p>
<p>The code below is the same as in the previous chapter, but now we have added an input validator  that checks the email field in the form:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;
&lt;?php
function spamcheck($field)
  {
  //filter_var() sanitizes the e-mail
  //address using FILTER_SANITIZE_EMAIL
  $field=filter_var($field, FILTER_SANITIZE_EMAIL);

  //filter_var() validates the e-mail
  //address using FILTER_VALIDATE_EMAIL
  if(filter_var($field, FILTER_VALIDATE_EMAIL))
    {
    return TRUE;
    }
  else
    {
    return FALSE;
    }
  }</pre>
<pre>if (isset($_REQUEST['email']))
  {//if "email" is filled out, proceed</pre>
<pre>  //check if the email address is invalid
  $mailcheck = spamcheck($_REQUEST['email']);
  if ($mailcheck==FALSE)
    {
    echo "Invalid input";
    }
  else
    {//send email
    $email = $_REQUEST['email'] ;
    $subject = $_REQUEST['subject'] ;
    $message = $_REQUEST['message'] ;
    mail("someone@example.com", "Subject: $subject",
    $message, "From: $email" );
    echo "Thank you for using our mail form";
    }
  }
else
  {//if "email" is not filled out, display the form
  echo "&lt;form method='post' action='mailform.php'&gt;
  Email: &lt;input name='email' type='text' /&gt;&lt;br /&gt;
  Subject: &lt;input name='subject' type='text' /&gt;&lt;br /&gt;
  Message:&lt;br /&gt;
  &lt;textarea name='message' rows='15' cols='40'&gt;
  &lt;/textarea&gt;&lt;br /&gt;
  &lt;input type='submit' /&gt;
  &lt;/form&gt;";
  }
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>In the code above we use PHP filters to validate input:</p>
<ul>
<li>The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters  	from a string</li>
<li>The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address</li>
</ul>
<p>You can read more about filters in our <a href="http://www.w3schools.com/PHP/php_filter.asp">PHP Filter</a> chapter.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/72/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=72&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-secure-e-mails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Sending E-mails</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-sending-e-mails/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-sending-e-mails/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:10:03 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=70</guid>
		<description><![CDATA[PHP allows you to send e-mails directly from a script. The PHP mail() Function The PHP mail() function is used to send emails from inside a script. Syntax mail(to,subject,message,headers,parameters) Parameter Description to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. Note: This parameter cannot contain any [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=70&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">PHP allows you to send e-mails directly from a script.</p>
<hr />
<h2>The PHP mail() Function</h2>
<p>The PHP mail() function is used to send emails from inside a script.</p>
<p><strong>Syntax</strong></p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>mail(to,subject,message,headers,parameters)</pre>
</td>
</tr>
</tbody>
</table>
<table class="reference" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<th width="20%" align="left" valign="top">Parameter</th>
<th width="80%" align="left" valign="top">Description</th>
</tr>
<tr>
<td valign="top">to</td>
<td valign="top">Required. Specifies  	the receiver / receivers of the email</td>
</tr>
<tr>
<td valign="top">subject</td>
<td valign="top">Required. Specifies  	the subject of the email. <strong>Note:</strong> This parameter cannot contain any newline  	characters</td>
</tr>
<tr>
<td valign="top">message</td>
<td valign="top">Required. Defines the message to be sent. Each line should  	be separated with a LF (\n). Lines should not exceed 70 characters</td>
</tr>
<tr>
<td valign="top">headers</td>
<td valign="top">Optional. Specifies additional headers, like From, Cc, and  	Bcc. The additional headers should be separated with a CRLF (\r\n)</td>
</tr>
<tr>
<td valign="top">parameters</td>
<td valign="top">Optional. Specifies an additional parameter to the sendmail program</td>
</tr>
</tbody>
</table>
<p><strong>Note:</strong> For the mail functions to be available, PHP requires an installed  and working email system. The program to be used is defined by the configuration  settings in the php.ini file. Read more in our <a href="http://www.w3schools.com/PHP/php_ref_mail.asp">PHP  Mail reference</a>.</p>
<hr />
<h2>PHP Simple E-Mail</h2>
<p>The simplest way to send an email with PHP is to send a text email.</p>
<p>In the example below we first declare the variables ($to, $subject, $message,  $from, $headers), then we use the variables in the mail() function to send an e-mail:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php</pre>
<pre>$to = "someone@example.com";
$subject = "Test mail";
$message = "Hello! This is a simple email message.";
$from = "someonelse@example.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
echo "Mail Sent.";</pre>
<pre>?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>PHP Mail Form</h2>
<p>With PHP, you can create a feedback-form on your website. The example below  sends a text message to a specified e-mail address:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //send email
  $email = $_REQUEST['email'] ;
  $subject = $_REQUEST['subject'] ;
  $message = $_REQUEST['message'] ;
  mail( "someone@example.com", "Subject: $subject",
  $message, "From: $email" );
  echo "Thank you for using our mail form";
  }
else
//if "email" is not filled out, display the form
  {
  echo "&lt;form method='post' action='mailform.php'&gt;
  Email: &lt;input name='email' type='text' /&gt;&lt;br /&gt;
  Subject: &lt;input name='subject' type='text' /&gt;&lt;br /&gt;
  Message:&lt;br /&gt;
  &lt;textarea name='message' rows='15' cols='40'&gt;
  &lt;/textarea&gt;&lt;br /&gt;
  &lt;input type='submit' /&gt;
  &lt;/form&gt;";
  }
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>This is how the example above works:</p>
<ul>
<li>First, check if the email input field is filled out</li>
<li>If it is not set (like when the page is  	first visited); output the HTML form</li>
<li>If it is set (after the form is filled out);  	send the email from the form</li>
<li>When submit is pressed after the form is filled out, the page reloads,  	sees that the email input is set, and sends the email</li>
</ul>
<p><strong>Note:</strong> This is the simplest way to send e-mail, but it is not   secure. In the next chapter of this tutorial you can read more about vulnerabilities in e-mail  scripts, and how to validate user input to make it more secure.</p>
<hr />
<h2>PHP Mail Reference</h2>
<p>For more information about the PHP mail() function, visit our <a href="http://www.w3schools.com/PHP/php_ref_mail.asp">PHP Mail Reference</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/70/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/70/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/70/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=70&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-sending-e-mails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Sessions</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-sessions/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-sessions/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:07:06 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=68</guid>
		<description><![CDATA[A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application. PHP Session Variables When you are working with an application, you open it, do some changes and then you close it. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=68&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">A PHP session variable is used to store information about, or  change settings for a user session. Session variables hold information about one  single user, and are available to all pages in one application.</p>
<hr />
<h2>PHP Session Variables</h2>
<p>When you are working with an application, you open it, do some changes and  then you close it. This is much like a Session. The computer knows who you are.  It knows when you start the application and when you end. But on the internet  there is one problem: the web server does not know who you are and what you do  because the HTTP address doesn&#8217;t maintain state.</p>
<p>A PHP session solves this problem by allowing you to store user information  on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and  will be deleted after  the user has left the website. If you need a permanent storage you may want to store the data in a database.</p>
<p>Sessions work by creating a unique id (UID) for each  visitor and store variables based on this UID. The UID is either stored in a  cookie or is propagated in the URL.</p>
<hr />
<h2>Starting a PHP Session</h2>
<p>Before you can store user information in your PHP session, you must  first start up the session.</p>
<p><strong>Note:</strong> The session_start() function must appear BEFORE the &lt;html&gt; tag:</p>
<table id="table6" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php session_start(); ?&gt;</pre>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The code above will register the user&#8217;s session with the server, allow you to  start saving user information, and assign a UID  for that user&#8217;s session.</p>
<hr />
<h2>Storing a Session Variable</h2>
<p>The correct way to store and retrieve session variables is to use the  PHP $_SESSION variable:</p>
<table id="table7" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
session_start();
// store session data
$_SESSION['views']=1;
?&gt;</pre>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Output:</p>
<table id="table8" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>Pageviews=1</pre>
</td>
</tr>
</tbody>
</table>
<p>In the example below, we create a simple page-views counter. The isset()  function checks if the &#8220;views&#8221; variable has already been set. If &#8220;views&#8221; has  been set, we  can increment our counter. If &#8220;views&#8221; doesn&#8217;t exist, we create a &#8220;views&#8221;  variable,  and set it to 1:</p>
<table id="table9" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php

session_start();</pre>
<pre>if(isset($_SESSION['views']))
  $_SESSION['views']=$_SESSION['views']+1;

else
  $_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Destroying a Session</h2>
<p>If you wish to delete some session data, you can use the unset() or the  session_destroy() function.</p>
<p>The unset() function is used to free the specified session variable:</p>
<table id="table10" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
unset($_SESSION['views']);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>You can also completely destroy the session by calling the session_destroy() function:</p>
<table id="table11" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
session_destroy();
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p><strong>Note:</strong> session_destroy() will reset your session and you will lose all  your stored session data.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/68/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=68&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-sessions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Cookies</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-cookies/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-cookies/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:06:09 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=66</guid>
		<description><![CDATA[A cookie is often used to identify a user. What is a Cookie? A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user&#8217;s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=66&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">A cookie is often used to identify a user.</p>
<hr />
<h2>What is a Cookie?</h2>
<p>A cookie is often used to identify a user. A cookie is a small file that the  server embeds on the user&#8217;s computer. Each time the same computer requests a  page with a browser, it will send the cookie too. With PHP, you can both create  and retrieve cookie values.</p>
<hr />
<h2>How to Create a Cookie?</h2>
<p>The setcookie() function is used to set a cookie.</p>
<p><strong>Note:</strong> The setcookie() function must appear BEFORE the &lt;html&gt; tag.</p>
<h3>Syntax</h3>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>setcookie(name, value, expire, path, domain);</pre>
</td>
</tr>
</tbody>
</table>
<h3>Example 1</h3>
<p>In the example below, we will create a cookie named &#8220;user&#8221; and assign the  value &#8220;Alex Porter&#8221; to it. We also specify that the cookie should expire after  one hour:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
setcookie("user", "Alex Porter", time()+3600);
?&gt;</pre>
<pre>&lt;html&gt;
.....</pre>
</td>
</tr>
</tbody>
</table>
<p><strong>Note: </strong>The value of the cookie is automatically URLencoded when  sending the cookie, and automatically decoded when received (to prevent  URLencoding, use setrawcookie() instead).</p>
<h3>Example 2</h3>
<p>You can also set the expiration time of the cookie in another way. It may be  easier than using seconds.</p>
<table id="table6" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?&gt;</pre>
<pre>&lt;html&gt;
.....</pre>
</td>
</tr>
</tbody>
</table>
<p>In the example above the expiration time is set to a month (<em>60 sec * 60  min * 24 hours * 30 days</em>).</p>
<hr />
<h2>How to Retrieve a Cookie Value?</h2>
<p>The PHP $_COOKIE variable is used to  retrieve a cookie value.</p>
<p>In the example below, we retrieve the value of the cookie named &#8220;user&#8221; and  display it on a page:</p>
<table id="table3" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
// Print a cookie
echo $_COOKIE["user"];</pre>
<pre>// A way to view all cookies
print_r($_COOKIE);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>In the following example we use the isset() function to find out if a cookie  has been set:</p>
<table id="table4" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!&lt;br /&gt;";
else
  echo "Welcome guest!&lt;br /&gt;";
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>How to Delete a Cookie?</h2>
<p>When deleting a cookie you should assure that the expiration date is in the  past.</p>
<p>Delete example:</p>
<table id="table5" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>What if a Browser Does NOT Support Cookies?</h2>
<p>If your application deals with browsers that do not support cookies, you will  have to use other methods to pass information from one page to another in your  application. One method is to pass the data through forms (forms and user input are described  earlier in this tutorial).</p>
<p>The form below passes the user input to &#8220;welcome.php&#8221; when the user clicks on  the &#8220;Submit&#8221; button:</p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;form action="welcome.php" method="post"&gt;
Name: &lt;input type="text" name="name" /&gt;
Age: &lt;input type="text" name="age" /&gt;
&lt;input type="submit" /&gt;
&lt;/form&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Retrieve the values in the &#8220;welcome.php&#8221; file like this:</p>
<table id="table2" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>Welcome &lt;?php echo $_POST["name"]; ?&gt;.&lt;br /&gt;
You are &lt;?php echo $_POST["age"]; ?&gt; years old.</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/66/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/66/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/66/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=66&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-cookies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP File Upload</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-file-upload/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-file-upload/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:05:11 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=64</guid>
		<description><![CDATA[With PHP, it is possible to upload files to the server. Create an Upload-File Form To allow users to upload files from a form can be very useful. Look at the following HTML form for uploading files: &#60;html&#62; &#60;body&#62; &#60;form action="upload_file.php" method="post" enctype="multipart/form-data"&#62; &#60;label for="file"&#62;Filename:&#60;/label&#62; &#60;input type="file" name="file" id="file" /&#62; &#60;br /&#62; &#60;input type="submit" name="submit" [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=64&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">With PHP, it is possible to upload files to the server.</p>
<hr />
<h2>Create an Upload-File Form</h2>
<p>To allow users to upload files from a form can be very useful.</p>
<p>Look at the following HTML form for uploading files:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;form action="upload_file.php" method="post"
enctype="multipart/form-data"&gt;
&lt;label for="file"&gt;Filename:&lt;/label&gt;
&lt;input type="file" name="file" id="file" /&gt;
&lt;br /&gt;
&lt;input type="submit" name="submit" value="Submit" /&gt;
&lt;/form&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Notice the following about the HTML form above:</p>
<ul>
<li>The enctype attribute of the &lt;form&gt; tag specifies which content-type to use when  	submitting the form. &#8220;multipart/form-data&#8221; is used when a form requires  	binary data, like the contents of a file, to be uploaded</li>
<li>The type=&#8221;file&#8221; attribute of the &lt;input&gt; tag specifies that the input should  	be processed as a file. For example, when viewed in a browser, there will be  	a browse-button next to the input field</li>
</ul>
<p><strong>Note:</strong> Allowing users to upload files is a big security risk. Only permit  trusted users  to perform file uploads.</p>
<hr />
<h2>Create The Upload Script</h2>
<p>The &#8220;upload_file.php&#8221; file contains the code for uploading a file:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
if ($_FILES["file"]["error"] &gt; 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "&lt;br /&gt;";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "&lt;br /&gt;";
  echo "Type: " . $_FILES["file"]["type"] . "&lt;br /&gt;";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb&lt;br /&gt;";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>By using the global PHP $_FILES array you can upload files from a client computer to  the remote server.</p>
<p>The first parameter is the form&#8217;s input name and the second index can be  either &#8220;name&#8221;, &#8220;type&#8221;, &#8220;size&#8221;, &#8220;tmp_name&#8221; or &#8220;error&#8221;. Like this:</p>
<ul>
<li>$_FILES["file"]["name"] &#8211; the name of the uploaded file</li>
<li>$_FILES["file"]["type"] &#8211; the type of the uploaded file</li>
<li>$_FILES["file"]["size"] &#8211; the size in bytes of the uploaded file</li>
<li>$_FILES["file"]["tmp_name"] &#8211; the name of the temporary copy of  	the file stored on the server</li>
<li>$_FILES["file"]["error"] &#8211; the error code resulting from the file  	upload</li>
</ul>
<p>This is a very simple way of uploading files. For security reasons, you  should add  restrictions on what the user is allowed to upload.</p>
<hr />
<h2>Restrictions on Upload</h2>
<p>In this script we add some restrictions to the file upload. The user may only upload  .gif or .jpeg files and the file size must be under 20 kb:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php</pre>
<pre>if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&amp;&amp; ($_FILES["file"]["size"] &lt; 20000))
  {
  if ($_FILES["file"]["error"] &gt; 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "&lt;br /&gt;";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "&lt;br /&gt;";
    echo "Type: " . $_FILES["file"]["type"] . "&lt;br /&gt;";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb&lt;br /&gt;";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }</pre>
<pre>?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p><strong>Note:</strong> For IE to recognize jpg files the type must be pjpeg, for  FireFox it must be jpeg.</p>
<hr />
<h2>Saving the Uploaded File</h2>
<p>The examples above create a temporary copy of the uploaded files in the PHP  temp folder on the server.</p>
<p>The temporary copied files disappears when the script ends. To store the  uploaded file we need to copy it to a different location:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&amp;&amp; ($_FILES["file"]["size"] &lt; 20000))
  {
  if ($_FILES["file"]["error"] &gt; 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "&lt;br /&gt;";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "&lt;br /&gt;";
    echo "Type: " . $_FILES["file"]["type"] . "&lt;br /&gt;";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb&lt;br /&gt;";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "&lt;br /&gt;";</pre>
<pre>    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The script above checks if the file already exists, if it does not, it copies the file to the specified folder.</p>
<p><strong>Note:</strong> This example saves the file to a new folder called &#8220;upload&#8221;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/64/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=64&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-file-upload/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP File Handling</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-file-handling/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-file-handling/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:03:39 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=62</guid>
		<description><![CDATA[The fopen() function is used to open files in PHP. Opening a File The fopen() function is used to open files in PHP. The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened: &#60;html&#62; &#60;body&#62; &#60;?php $file=fopen("welcome.txt","r"); [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=62&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">The fopen() function is used to open files in PHP.</p>
<hr />
<h2>Opening a File</h2>
<p>The fopen() function is used to open files in PHP.</p>
<p>The first parameter of this function contains the name of the file to be opened and the  second parameter specifies in which mode the file should be opened:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
$file=fopen("welcome.txt","r");
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The file may be opened in one of the following modes:</p>
<table class="reference" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr valign="top">
<th width="20%" align="left">Modes</th>
<th width="80%" align="left">Description</th>
</tr>
<tr valign="top">
<td>r</td>
<td>Read only. Starts at the beginning of the file</td>
</tr>
<tr valign="top">
<td height="18">r+</td>
<td height="18">Read/Write. Starts at the beginning of the file</td>
</tr>
<tr valign="top">
<td>w</td>
<td>Write only. Opens and clears the contents of file; or creates a new file  	if it doesn&#8217;t exist</td>
</tr>
<tr valign="top">
<td>w+</td>
<td>Read/Write. Opens and clears the contents of file; or creates a new file  	if it doesn&#8217;t exist</td>
</tr>
<tr valign="top">
<td>a</td>
<td>Append. Opens and writes to the end of the file or creates a new file if  	it doesn&#8217;t exist</td>
</tr>
<tr>
<td>a+</td>
<td>Read/Append. Preserves file content by writing to the end of the file</td>
</tr>
<tr valign="top">
<td>x</td>
<td>Write only. Creates a new file. Returns FALSE and an error if file  	already exists</td>
</tr>
<tr valign="top">
<td>x+</td>
<td>Read/Write. Creates a new file. Returns FALSE and an error if file  	already exists</td>
</tr>
</tbody>
</table>
<p><strong>Note:</strong> If the fopen() function is unable to open the  specified file, it returns 0 (false).</p>
<h3>Example</h3>
<p>The following example generates a message if the fopen() function is unable  to open the specified file:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Closing a File</h2>
<p>The fclose() function is used to close an open file:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$file = fopen("test.txt","r");</pre>
<pre>//some code to be executed</pre>
<pre>fclose($file);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Check End-of-file</h2>
<p>The feof() function checks if the &#8220;end-of-file&#8221; (EOF) has been reached.</p>
<p>The feof() function is useful for looping through data of unknown length.</p>
<p><strong>Note:</strong> You cannot read from files opened in w, a, and x mode!</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>if (feof($file)) echo "End of file";</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Reading a File Line by Line</h2>
<p>The fgets() function is used to read a single line from a file.</p>
<p><strong>Note:</strong> After a call to this function the file pointer has moved to the next  line.</p>
<h3>Example</h3>
<p>The example below reads a file line by line, until the end of  file is reached:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "&lt;br /&gt;";
  }
fclose($file);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>Reading a File Character by Character</h2>
<p>The fgetc() function is used to read a single character from a file.</p>
<p><strong>Note:</strong> After a call to this function the file pointer moves to the next character.</p>
<h3>Example</h3>
<p>The example below reads a file character by character, until the end of  file is reached:</p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?&gt;</pre>
</td>
</tr>
</tbody>
</table>
<hr />
<h2>PHP Filesystem Reference</h2>
<p>For a full reference of the PHP filesystem functions, visit our <a href="http://www.w3schools.com/PHP/php_ref_filesystem.asp">PHP Filesystem Reference</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/62/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=62&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-file-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
		<item>
		<title>PHP Include File</title>
		<link>http://phpdemon.wordpress.com/2009/05/02/php-include-file/</link>
		<comments>http://phpdemon.wordpress.com/2009/05/02/php-include-file/#comments</comments>
		<pubDate>Sat, 02 May 2009 09:02:47 +0000</pubDate>
		<dc:creator>Varun Chopra</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>

		<guid isPermaLink="false">http://phpdemon.wordpress.com/?p=60</guid>
		<description><![CDATA[Server Side Includes (SSI) are used to create functions, headers, footers, or elements that will be reused on multiple pages. Server Side Includes You can insert the content of a file into a PHP file before the server executes it, with the include() or require() function. The two functions are identical in every way, except [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=60&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p class="intro">Server Side Includes (SSI) are used to create functions, headers,  footers, or elements that will be reused on multiple pages.</p>
<hr />
<h2>Server Side Includes</h2>
<p>You can insert the content of a file into a PHP file before the server  executes it, with the include() or require() function. The two functions are  identical in every way, except how they handle errors. The include() function  generates a warning (but the script will continue execution) while the require()  function generates a fatal error (and the script execution will stop after the  error).</p>
<p>These two functions are used to  create functions, headers, footers, or elements that can be reused on multiple  pages.</p>
<p>This can save the developer a considerable amount of time. This means that  you can create a standard header or menu file that you want all your web pages  to include. When the header needs to be updated, you can only  update this one include file, or when you add a new page to your site, you can simply change the  menu file (instead of updating the links on all web pages).</p>
<hr />
<h2>The include() Function</h2>
<p>The include() function takes all the text in a specified file and copies it  into the file that uses the include function.</p>
<h3>Example 1</h3>
<p>Assume that you have a standard header file, called &#8220;header.php&#8221;. To include  the header file in a page, use the include() function, like this:</p>
<table class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;?php include("header.php"); ?&gt;</pre>
<pre>&lt;h1&gt;Welcome to my home page&lt;/h1&gt;</pre>
<pre>&lt;p&gt;Some text&lt;/p&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<h3>Example 2</h3>
<p>Now, let&#8217;s assume we have a standard menu file that should be used on all  pages (include files usually have a &#8220;.php&#8221;  extension). Look at the &#8220;menu.php&#8221; file below:</p>
<table id="table1" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;</pre>
<pre>&lt;a href="http://www.w3schools.com/default.php"&gt;Home&lt;/a&gt; |
&lt;a href="http://www.w3schools.com/about.php"&gt;About Us&lt;/a&gt; |
&lt;a href="http://www.w3schools.com/contact.php"&gt;Contact Us&lt;/a&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>The three files, &#8220;default.php&#8221;, &#8220;about.php&#8221;, and &#8220;contact.php&#8221;  should all include the &#8220;menu.php&#8221; file.  Here is the code in &#8220;default.php&#8221;:</p>
<table id="table2" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;?php include("menu.php"); ?&gt;</pre>
<pre>&lt;h1&gt;Welcome to my home page&lt;/h1&gt;</pre>
<pre>&lt;p&gt;Some text&lt;/p&gt;</pre>
<pre>&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>If you look at the source code of the &#8220;default.php&#8221; in a browser, it will look something like  this:</p>
<table id="table3" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;
&lt;a href="default.php"&gt;Home&lt;/a&gt; |
&lt;a href="about.php"&gt;About Us&lt;/a&gt; |
&lt;a href="contact.php"&gt;Contact Us&lt;/a&gt;
&lt;h1&gt;Welcome to my home page&lt;/h1&gt;
&lt;p&gt;Some text&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>And, of course, we would have to do the same thing for &#8220;about.php&#8221; and &#8220;contact.php&#8221;.  By using include files, you simply have to update the text in the &#8220;menu.php&#8221;  file if you decide to rename or change the order of the links or add another web page to the site.</p>
<hr />
<h2>The require() Function</h2>
<p>The require() function is identical to include(), except that it handles  errors differently.</p>
<p>The include() function generates a warning (but the script will continue  execution) while the require() function generates a fatal error (and the script  execution will stop after the error).</p>
<p>If you include a file with the include() function and an error occurs, you  might get an error message like the one below.</p>
<p>PHP code:</p>
<table id="table4" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;

&lt;?php
include("wrongFile.php");
echo "Hello World!";
?&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Error message:</p>
<table id="table5" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Warning:</strong> include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5</pre>
<pre><strong>Warning:</strong> include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5</pre>
<pre>Hello World!</pre>
</td>
</tr>
</tbody>
</table>
<p>Notice that the echo statement is still executed! This is because a Warning  does not stop the script execution.</p>
<p>Now, let&#8217;s run the same example with the require() function.</p>
<p>PHP code:</p>
<table id="table8" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre>&lt;html&gt;
&lt;body&gt;

&lt;?php
require("wrongFile.php");
echo "Hello World!";
?&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<p>Error message:</p>
<table id="table9" class="ex" border="1" cellspacing="0" width="100%">
<tbody>
<tr>
<td>
<pre><strong>Warning:</strong> require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5</pre>
<pre><strong>Fatal error:</strong> require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5</pre>
</td>
</tr>
</tbody>
</table>
<p>The echo statement was not executed because the script execution stopped  after the fatal error.</p>
<p>It is recommended to use the require() function instead of include(), because  scripts should not continue executing if files are missing or misnamed.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/phpdemon.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/phpdemon.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/phpdemon.wordpress.com/60/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=phpdemon.wordpress.com&amp;blog=7565626&amp;post=60&amp;subd=phpdemon&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://phpdemon.wordpress.com/2009/05/02/php-include-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Demon</media:title>
		</media:content>
	</item>
	</channel>
</rss>
