<?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/"
	>

<channel>
	<title>JaffnaCampus.com &#187; PHP Advanced</title>
	<atom:link href="http://jaffnacampus.com/category/php/php-advanced/feed/" rel="self" type="application/rss+xml" />
	<link>http://jaffnacampus.com</link>
	<description>Gateway to your IT potential</description>
	<lastBuildDate>Tue, 27 Sep 2011 13:57:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP Filter</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-filter/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-filter/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:22:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Filter]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=337</guid>
		<description><![CDATA[PHP filters are used to validate and filter data coming   from   insecure sources, like user input.

What [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $int = 123;</p>
<p>        if(!filter_var($int, FILTER_VALIDATE_INT))<br />
        {<br />
        echo(&quot;Integer is not valid&quot;);<br />
        }<br />
        else<br />
        {<br />
        echo(&quot;Integer is valid&quot;);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The code above uses the &quot;FILTER_VALIDATE_INT&quot;  filter to filter the   variable. Since the integer is valid, the output of the code above will   be:   &quot;Integer is valid&quot;.</p>
<p>If we try with a variable that is not an integer (like &quot;123abc&quot;), the   output   will be: &quot;Integer is not valid&quot;.
</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 &quot;min_range&quot;   and &quot;max_range&quot; options:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $var=300;</p>
<p>        $int_options = array(<br />
        &quot;options&quot;=&gt;array<br />
        (<br />
        &quot;min_range&quot;=&gt;0,<br />
        &quot;max_range&quot;=&gt;256<br />
        )<br />
        );</p>
<p>        if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))<br />
        {<br />
        echo(&quot;Integer is not valid&quot;);<br />
        }<br />
        else<br />
        {<br />
        echo(&quot;Integer is valid&quot;);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>Like the code above, options must be put in an associative array with   the   name &quot;options&quot;. If a flag is used it does not need to be in an array.</p>
<p>Since the integer is &quot;300&quot; it is not in the specified range, and the   output of the code above will be:   &quot;Integer is not valid&quot;.</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 &quot;email&quot; is sent to the PHP   page:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if(!filter_has_var(INPUT_GET, &quot;email&quot;))<br />
        {<br />
        echo(&quot;Input type does not exist&quot;);<br />
        }<br />
        else<br />
        {<br />
        if (!filter_input(INPUT_GET, &quot;email&quot;, FILTER_VALIDATE_EMAIL))<br />
        {<br />
        echo &quot;E-Mail is not valid&quot;;<br />
        }<br />
        else<br />
        {<br />
        echo &quot;E-Mail is valid&quot;;<br />
        }<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has an input (email) sent to it using the &quot;GET&quot;   method:</p>
<ol>
<li>Check if an &quot;email&quot; input variable of the &quot;GET&quot; 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 &quot;url&quot; is sent to the PHP   page:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if(!filter_has_var(INPUT_POST, &quot;url&quot;))<br />
        {<br />
        echo(&quot;Input type does not exist&quot;);<br />
        }<br />
        else<br />
        {<br />
        $url = filter_input(INPUT_POST, <br />
        &quot;url&quot;, FILTER_SANITIZE_URL);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has an input (url) sent to it using the &quot;POST&quot;   method:</p>
<ol>
<li>Check if the &quot;url&quot; input of the &quot;POST&quot; 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   &quot;http://www.W3ååSchøøools.com/&quot;, the $url variable after the sanitizing   will   look like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> http://www.W3Schools.com/ </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $filters = array<br />
        (<br />
        &quot;name&quot; =&gt; array<br />
        (<br />
        &quot;filter&quot;=&gt;FILTER_SANITIZE_STRING<br />
        ),<br />
        &quot;age&quot; =&gt; array<br />
        (<br />
        &quot;filter&quot;=&gt;FILTER_VALIDATE_INT,<br />
        &quot;options&quot;=&gt;array<br />
        (<br />
        &quot;min_range&quot;=&gt;1,<br />
        &quot;max_range&quot;=&gt;120<br />
        )<br />
        ),<br />
        &quot;email&quot;=&gt; FILTER_VALIDATE_EMAIL,<br />
        );</p>
<p>        $result = filter_input_array(INPUT_GET, $filters);</p>
<p>        if (!$result[&quot;age&quot;])<br />
        {<br />
        echo(&quot;Age must be a number between 1 and 120.&lt;br /&gt;&quot;);<br />
        }<br />
        elseif(!$result[&quot;email&quot;])<br />
        {<br />
        echo(&quot;E-Mail is not valid.&lt;br /&gt;&quot;);<br />
        }<br />
        else<br />
        {<br />
        echo(&quot;User input is valid&quot;);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above has three inputs (name, age and email) sent to it   using the &quot;GET&quot; 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 &quot;age&quot; and &quot;email&quot; 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 &quot;age&quot; 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 &quot;options&quot;</p>
<p>In the example below, we use a user created function to convert all    &quot;_&quot;   to whitespaces:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        function convertSpace($string)<br />
        {<br />
        return str_replace(&quot;_&quot;, &quot; &quot;, $string);<br />
        }</p>
<p>        $string = &quot;Peter_is_a_great_guy!&quot;;</p>
<p>        echo filter_var($string, FILTER_CALLBACK,<br />
        array(&quot;options&quot;=&gt;&quot;convertSpace&quot;));<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The result from the code above should look like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> Peter is a great guy! </td>
</tr>
</tbody>
</table>
<h2>Example Explained</h2>
<p>The example above converts all &quot;_&quot; to whitespaces:</p>
<ol>
<li>Create a function to replace &quot;_&quot; to whitespaces</li>
<li>Call the filter_var() function with the FILTER_CALLBACK filter and   an   	array containing our function</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-filter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Exception Handling</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-exception-handling/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-exception-handling/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:20:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Exception Handling]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=335</guid>
		<description><![CDATA[Exceptions are used to change the normal flow of a   script if a   specified error occurs

What [...]]]></description>
			<content:encoded><![CDATA[<p>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 &quot;catch&quot; block.</p>
<p>If an exception is not caught, a fatal error will be issued with an   &quot;Uncaught   Exception&quot; message.</p>
<p>Lets try to throw an exception without catching it:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        //create function with an exception<br />
        function checkNum($number)<br />
        {<br />
        if($number&gt;1)<br />
        {<br />
        throw new Exception(&quot;Value must be 1 or below&quot;);<br />
        }<br />
        return true;<br />
        }</p>
<p>        //trigger exception<br />
        checkNum(2);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The code above will get an error like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Fatal error</strong>: Uncaught exception &#8216;Exception&#8217;<br />
        with message &#8216;Value must be 1 or below&#8217; in C:\webfolder\test.php:6<br />
        Stack trace: #0 C:\webfolder\test.php(12):<br />
        checkNum(28) #1 {main} thrown in <strong>C:\webfolder\test.php</strong> on line <strong>6</strong></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 &quot;try&quot; block. If   the   	exception does not trigger, the code will continue as normal. However   if the   	exception triggers, an exception is &quot;thrown&quot;</li>
<li>Throw &#8211; This is how you trigger an exception. Each &quot;throw&quot; must   have at   	least one &quot;catch&quot;</li>
<li>Catch &#8211; A &quot;catch&quot; 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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        //create function with an exception<br />
        function checkNum($number)<br />
        {<br />
        if($number&gt;1)<br />
        {<br />
        throw new Exception(&quot;Value must be 1 or below&quot;);<br />
        }<br />
        return true;<br />
        }</p>
<p>        //trigger exception in a &quot;try&quot; block<br />
        try<br />
        {<br />
        checkNum(2);<br />
        //If the exception is thrown, this text will not be shown<br />
        echo &#8216;If you see this, the number is 1 or below&#8217;;<br />
        }</p>
<p>        //catch exception<br />
        catch(Exception $e)<br />
        {<br />
        echo &#8216;Message: &#8216; .$e-&gt;getMessage();<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The code above will get an error like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> Message: Value must be 1 or below </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 &quot;try&quot; block</li>
<li>The exception within the checkNum() function is thrown</li>
<li>The &quot;catch&quot; 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 &quot;every throw must have a catch&quot;   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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        class customException extends Exception<br />
        {<br />
        public function errorMessage()<br />
        {<br />
        //error message<br />
        $errorMsg = &#8216;Error on line &#8216;.$this-&gt;getLine().&#8217; in   &#8216;.$this-&gt;getFile()<br />
        .&#8217;: &lt;b&gt;&#8217;.$this-&gt;getMessage().&#8217;&lt;/b&gt; is not a valid   E-Mail address&#8217;;<br />
        return $errorMsg;<br />
        }<br />
        }</p>
<p>        $email = &quot;someone@example&#8230;com&quot;;</p>
<p>        try<br />
        {<br />
        //check if<br />
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)<br />
        {<br />
        //throw exception if email is not valid<br />
        throw new customException($email);<br />
        }<br />
        }</p>
<p>        catch (customException $e)<br />
        {<br />
        //display custom message<br />
        echo $e-&gt;errorMessage();<br />
        }<br />
        ?&gt; </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 &quot;try&quot; block is executed and an exception is thrown since   	the e-mail address is invalid</li>
<li>The &quot;catch&quot; 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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        class customException extends Exception<br />
        {<br />
        public function errorMessage()<br />
        {<br />
        //error message<br />
        $errorMsg = &#8216;Error on line &#8216;.$this-&gt;getLine().&#8217; in   &#8216;.$this-&gt;getFile()<br />
        .&#8217;: &lt;b&gt;&#8217;.$this-&gt;getMessage().&#8217;&lt;/b&gt; is not a valid E-Mail   address&#8217;;<br />
        return $errorMsg;<br />
        }<br />
        }</p>
<p>        $email = &quot;someone@example.com&quot;;</p>
<p>        try<br />
        {<br />
        //check if<br />
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)<br />
        {<br />
        //throw exception if email is not valid<br />
        throw new customException($email);<br />
        }<br />
        //check for &quot;example&quot; in mail address<br />
        if(strpos($email, &quot;example&quot;) !== FALSE)<br />
        {<br />
        throw new Exception(&quot;$email is an example e-mail&quot;);<br />
        }<br />
        }</p>
<p>        catch (customException $e)<br />
        {<br />
        echo $e-&gt;errorMessage();<br />
        }</p>
<p>        catch(Exception $e)<br />
        {<br />
        echo $e-&gt;getMessage();<br />
        }<br />
        ?&gt; </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 &quot;example&quot;</li>
<li>The &quot;try&quot; 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 &quot;example&quot;</li>
<li>The &quot;catch&quot; 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 &quot;catch&quot; 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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        class customException extends Exception<br />
        {<br />
        public function errorMessage()<br />
        {<br />
        //error message<br />
        $errorMsg = $this-&gt;getMessage().&#8217; is not a valid E-Mail   address.&#8217;;<br />
        return $errorMsg;<br />
        }<br />
        }</p>
<p>        $email = &quot;someone@example.com&quot;;</p>
<p>        try<br />
        {<br />
        try<br />
        {<br />
        //check for &quot;example&quot; in mail address<br />
        if(strpos($email, &quot;example&quot;) !== FALSE)<br />
        {<br />
        //throw exception if email is not valid<br />
        throw new Exception($email);<br />
        }<br />
        }<br />
        catch(Exception $e)<br />
        {<br />
        //re-throw exception<br />
        throw new customException($email);<br />
        }<br />
        }</p>
<p>        catch (customException $e)<br />
        {<br />
        //display custom message<br />
        echo $e-&gt;errorMessage();<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<h2>Example explained:</h2>
<p>The code above tests if the email-address contains the string   &quot;example&quot; 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 &quot;example&quot;</li>
<li>The &quot;try&quot; block contains another &quot;try&quot; block to make it   	possible to re-throw the exception</li>
<li>The exception is triggered since the e-mail contains the string   	&quot;example&quot;</li>
<li>The &quot;catch&quot; block catches the exception and re-throws a   &quot;customException&quot;</li>
<li>The &quot;customException&quot; is caught and displays an error message</li>
</ol>
<p>If the exception is not caught in its current &quot;try&quot; block, it will   search for a catch block on &quot;higher levels&quot;.</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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        function myException($exception)<br />
        {<br />
        echo &quot;&lt;b&gt;Exception:&lt;/b&gt; &quot; , $exception-&gt;getMessage();<br />
        }</p>
<p>        set_exception_handler(&#8216;myException&#8217;);</p>
<p>        throw new Exception(&#8216;Uncaught Exception occurred&#8217;);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Exception:</strong> Uncaught Exception occurred </td>
</tr>
</tbody>
</table>
<p>In the code above there was no &quot;catch&quot; 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 &quot;throw&quot; 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>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-exception-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Error Handling</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-error-handling/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-error-handling/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:18:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Error Handling]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=332</guid>
		<description><![CDATA[The default error handling in PHP is very simple. An   error message with file name, line   [...]]]></description>
			<content:encoded><![CDATA[<p>The default error handling in PHP is very simple. An   error message with file name, 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 &quot;die()&quot; 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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $file=fopen(&quot;welcome.txt&quot;,&quot;r&quot;);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>If the file does not exist you might get an error like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Warning</strong>: fopen(welcome.txt) [function.fopen]: failed to open   stream:<br />
        No such file or directory in <strong>C:\webfolder\test.php</strong> on line <strong>2</strong></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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if(!file_exists(&quot;welcome.txt&quot;))<br />
        {<br />
        die(&quot;File not found&quot;);<br />
        }<br />
        else<br />
        {<br />
        $file=fopen(&quot;welcome.txt&quot;,&quot;r&quot;);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>Now if the file does not exist you get an error like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> File not found </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> error_function(error_level,error_message,<br />
        error_file,error_line,error_context) </td>
</tr>
</tbody>
</table>
<p></p>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th align="left" valign="top" width="20%">Parameter</th>
<th align="left" valign="top" width="80%">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 border="1" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th align="left" width="5%">Value</th>
<th align="left" width="30%">Constant</th>
<th align="left" width="65%">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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> function customError($errno, $errstr)<br />
        {<br />
        echo &quot;&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;&quot;;<br />
        echo &quot;Ending Script&quot;;<br />
        die();<br />
        } </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> set_error_handler(&quot;customError&quot;); </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        //error handler function<br />
        function customError($errno, $errstr)<br />
        {<br />
        echo &quot;&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&quot;;<br />
        }</p>
<p>        //set error handler<br />
        set_error_handler(&quot;customError&quot;);</p>
<p>        //trigger error<br />
        echo($test);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Error:</strong> [8] Undefined variable: test </td>
</tr>
</tbody>
</table>
<p></p>
<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 &quot;test&quot; variable is bigger than   &quot;1&quot;:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $test=2;<br />
        if ($test&gt;1)<br />
        {<br />
        trigger_error(&quot;Value must be 1 or below&quot;);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Notice</strong>: Value must be 1 or below<br />
        in <strong>C:\webfolder\test.php</strong> on line <strong>6</strong></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 &quot;test&quot; variable is   bigger   than &quot;1&quot;. If an E_USER_WARNING occurs we will use our custom error   handler   and end the script:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        //error handler function<br />
        function customError($errno, $errstr)<br />
        {<br />
        echo &quot;&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;&quot;;<br />
        echo &quot;Ending Script&quot;;<br />
        die();<br />
        }</p>
<p>        //set error handler<br />
        set_error_handler(&quot;customError&quot;,E_USER_WARNING);</p>
<p>        //trigger error<br />
        $test=2;<br />
        if ($test&gt;1)<br />
        {<br />
        trigger_error(&quot;Value must be 1 or below&quot;,E_USER_WARNING);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Error:</strong> [512] Value must be 1 or below<br />
        Ending Script </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        //error handler function<br />
        function customError($errno, $errstr)<br />
        {<br />
        echo &quot;&lt;b&gt;Error:&lt;/b&gt; [$errno] $errstr&lt;br /&gt;&quot;;<br />
        echo &quot;Webmaster has been notified&quot;;<br />
        error_log(&quot;Error: [$errno] $errstr&quot;,1,<br />
        &quot;someone@example.com&quot;,&quot;From: webmaster@example.com&quot;);<br />
        }</p>
<p>        //set error handler<br />
        set_error_handler(&quot;customError&quot;,E_USER_WARNING);</p>
<p>        //trigger error<br />
        $test=2;<br />
        if ($test&gt;1)<br />
        {<br />
        trigger_error(&quot;Value must be 1 or below&quot;,E_USER_WARNING);<br />
        }<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>The output of the code above should be something like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Error:</strong> [512] Value must be 1 or below<br />
        Webmaster has been notified </td>
</tr>
</tbody>
</table>
<p>And the mail received from the code above looks like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> Error: [512] Value must be 1 or below </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>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-error-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Secure E-mails</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-secure-e-mails/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-secure-e-mails/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:17:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Secure E-mails]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=330</guid>
		<description><![CDATA[There is a weakness in the PHP e-mail script in the   previous   chapter.

PHP E-mail Injections
First, look [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        if (isset($_REQUEST['email']))<br />
        //if &quot;email&quot; is filled out, send email<br />
        {<br />
        //send email<br />
        $email = $_REQUEST['email'] ;<br />
        $subject = $_REQUEST['subject'] ;<br />
        $message = $_REQUEST['message'] ;<br />
        mail(&quot;someone@example.com&quot;, &quot;Subject: $subject&quot;,<br />
        $message, &quot;From: $email&quot; );<br />
        echo &quot;Thank you for using our mail form&quot;;<br />
        }<br />
        else<br />
        //if &quot;email&quot; is not filled out, display the form<br />
        {<br />
        echo &quot;&lt;form method=&#8217;post&#8217; action=&#8217;mailform.php&#8217;&gt;<br />
        Email: &lt;input name=&#8217;email&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Subject: &lt;input name=&#8217;subject&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Message:&lt;br /&gt;<br />
        &lt;textarea name=&#8217;message&#8217; rows=&#8217;15&#8242; cols=&#8217;40&#8242;&gt;<br />
        &lt;/textarea&gt;&lt;br /&gt;<br />
        &lt;input type=&#8217;submit&#8217; /&gt;<br />
        &lt;/form&gt;&quot;;<br />
        }<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> someone@example.com%0ACc:person2@example.com<br />
        %0ABcc:person3@example.com,person3@example.com,<br />
        anotherperson4@example.com,person5@example.com<br />
        %0ABTo:person6@example.com </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;<br />
        &lt;?php<br />
        function spamcheck($field)<br />
        {<br />
        //filter_var() sanitizes the e-mail<br />
        //address using FILTER_SANITIZE_EMAIL<br />
        $field=filter_var($field, FILTER_SANITIZE_EMAIL);</p>
<p>        //filter_var() validates the e-mail<br />
        //address using FILTER_VALIDATE_EMAIL<br />
        if(filter_var($field, FILTER_VALIDATE_EMAIL))<br />
        {<br />
        return TRUE;<br />
        }<br />
        else<br />
        {<br />
        return FALSE;<br />
        }<br />
        }</p>
<p>        if (isset($_REQUEST['email']))<br />
        {//if &quot;email&quot; is filled out, proceed</p>
<p>        //check if the email address is invalid<br />
        $mailcheck = spamcheck($_REQUEST['email']);<br />
        if ($mailcheck==FALSE)<br />
        {<br />
        echo &quot;Invalid input&quot;;<br />
        }<br />
        else<br />
        {//send email<br />
        $email = $_REQUEST['email'] ;<br />
        $subject = $_REQUEST['subject'] ;<br />
        $message = $_REQUEST['message'] ;<br />
        mail(&quot;someone@example.com&quot;, &quot;Subject: $subject&quot;,<br />
        $message, &quot;From: $email&quot; );<br />
        echo &quot;Thank you for using our mail form&quot;;<br />
        }<br />
        }<br />
        else<br />
        {//if &quot;email&quot; is not filled out, display the form<br />
        echo &quot;&lt;form method=&#8217;post&#8217; action=&#8217;mailform.php&#8217;&gt;<br />
        Email: &lt;input name=&#8217;email&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Subject: &lt;input name=&#8217;subject&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Message:&lt;br /&gt;<br />
        &lt;textarea name=&#8217;message&#8217; rows=&#8217;15&#8242; cols=&#8217;40&#8242;&gt;<br />
        &lt;/textarea&gt;&lt;br /&gt;<br />
        &lt;input type=&#8217;submit&#8217; /&gt;<br />
        &lt;/form&gt;&quot;;<br />
        }<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </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>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-secure-e-mails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Sending E-mails</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-sending-e-mails/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-sending-e-mails/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:15:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Sending E-mails]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/php/php-advanced/php-sending-e-mails/</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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> mail(to,subject,message,headers,parameters) </td>
</tr>
</tbody>
</table>
<p></p>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<th align="left" valign="top" width="20%">Parameter</th>
<th align="left" valign="top" width="80%">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.</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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $to = &quot;someone@example.com&quot;;<br />
        $subject = &quot;Test mail&quot;;<br />
        $message = &quot;Hello! This is a simple email message.&quot;;<br />
        $from = &quot;someonelse@example.com&quot;;<br />
        $headers = &quot;From: $from&quot;;<br />
        mail($to,$subject,$message,$headers);<br />
        echo &quot;Mail Sent.&quot;;<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        if (isset($_REQUEST['email']))<br />
        //if &quot;email&quot; is filled out, send email<br />
        {<br />
        //send email<br />
        $email = $_REQUEST['email'] ;<br />
        $subject = $_REQUEST['subject'] ;<br />
        $message = $_REQUEST['message'] ;<br />
        mail( &quot;someone@example.com&quot;, &quot;Subject: $subject&quot;,<br />
        $message, &quot;From: $email&quot; );<br />
        echo &quot;Thank you for using our mail form&quot;;<br />
        }<br />
        else<br />
        //if &quot;email&quot; is not filled out, display the form<br />
        {<br />
        echo &quot;&lt;form method=&#8217;post&#8217; action=&#8217;mailform.php&#8217;&gt;<br />
        Email: &lt;input name=&#8217;email&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Subject: &lt;input name=&#8217;subject&#8217; type=&#8217;text&#8217; /&gt;&lt;br /&gt;<br />
        Message:&lt;br /&gt;<br />
        &lt;textarea name=&#8217;message&#8217; rows=&#8217;15&#8242; cols=&#8217;40&#8242;&gt;<br />
        &lt;/textarea&gt;&lt;br /&gt;<br />
        &lt;input type=&#8217;submit&#8217; /&gt;<br />
        &lt;/form&gt;&quot;;<br />
        }<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </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>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-sending-e-mails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Sessions</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-sessions/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-sessions/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:14:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Sessions]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=327</guid>
		<description><![CDATA[A PHP session variable is used to store information   about, or   change settings for a user [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php session_start(); ?&gt;</p>
<p>        &lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        session_start();<br />
        // store session data<br />
        $_SESSION['views']=1;<br />
        ?&gt;</p>
<p>        &lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        //retrieve session data<br />
        echo &quot;Pageviews=&quot;. $_SESSION['views'];<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>Output:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> Pageviews=1 </td>
</tr>
</tbody>
</table>
<p>In the example below, we create a simple page-views counter. The   isset()   function checks if the &quot;views&quot; variable has already been set. If &quot;views&quot;   has   been set, we can increment our counter. If &quot;views&quot; doesn&#8217;t exist, we   create a &quot;views&quot;   variable, and set it to 1:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        session_start();</p>
<p>        if(isset($_SESSION['views']))<br />
        $_SESSION['views']=$_SESSION['views']+1;<br />
        else<br />
        $_SESSION['views']=1;<br />
        echo &quot;Views=&quot;. $_SESSION['views'];<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        unset($_SESSION['views']);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p>You can also completely destroy the session by calling the   session_destroy() function:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        session_destroy();<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p><strong>Note:</strong> session_destroy() will reset your session and you will   lose all   your stored session data.</p>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-sessions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Cookies</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-cookies/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-cookies/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:13:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Cookies]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=325</guid>
		<description><![CDATA[A cookie is often used to identify a user.

What is a Cookie? 
A cookie is often used to identify a [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> setcookie(name, value, expire, path, domain); </td>
</tr>
</tbody>
</table>
<h3>Example 1</h3>
<p>In the example below, we will create a cookie named &quot;user&quot; and assign   the   value &quot;Alex Porter&quot; to it. We also specify that the cookie should expire   after   one hour:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        setcookie(&quot;user&quot;, &quot;Alex Porter&quot;, time()+3600);<br />
        ?&gt;</p>
<p>        &lt;html&gt;<br />
        &#8230;.. </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $expire=time()+60*60*24*30;<br />
        setcookie(&quot;user&quot;, &quot;Alex Porter&quot;, $expire);<br />
        ?&gt;</p>
<p>        &lt;html&gt;<br />
        &#8230;.. </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 &quot;user&quot;   and   display it on a page:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        // Print a cookie<br />
        echo $_COOKIE[&quot;user&quot;];</p>
<p>        // A way to view all cookies<br />
        print_r($_COOKIE);<br />
        ?&gt; </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        if (isset($_COOKIE[&quot;user&quot;]))<br />
        echo &quot;Welcome &quot; . $_COOKIE[&quot;user&quot;] . &quot;!&lt;br /&gt;&quot;;<br />
        else<br />
        echo &quot;Welcome guest!&lt;br /&gt;&quot;;<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        // set the expiration date to one hour ago<br />
        setcookie(&quot;user&quot;, &quot;&quot;, time()-3600);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<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 &quot;welcome.php&quot; when the user   clicks on   the &quot;Submit&quot; button:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;form action=&quot;welcome.php&quot; method=&quot;post&quot;&gt;<br />
        Name: &lt;input type=&quot;text&quot; name=&quot;name&quot; /&gt;<br />
        Age: &lt;input type=&quot;text&quot; name=&quot;age&quot; /&gt;<br />
        &lt;input type=&quot;submit&quot; /&gt;<br />
        &lt;/form&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>Retrieve the values in the &quot;welcome.php&quot; file like this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        Welcome &lt;?php echo $_POST[&quot;name&quot;]; ?&gt;.&lt;br /&gt;<br />
        You are &lt;?php echo $_POST[&quot;age&quot;]; ?&gt; years old.</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-cookies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP File Upload</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-file-upload/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-file-upload/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:11:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP File Upload]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=323</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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;form action=&quot;upload_file.php&quot; method=&quot;post&quot;<br />
        enctype=&quot;multipart/form-data&quot;&gt;<br />
        &lt;label for=&quot;file&quot;&gt;Filename:&lt;/label&gt;<br />
        &lt;input type=&quot;file&quot; name=&quot;file&quot; id=&quot;file&quot; /&gt; <br />
        &lt;br /&gt;<br />
        &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot; /&gt;<br />
        &lt;/form&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </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. &quot;multipart/form-data&quot; is used when a form requires     	binary data, like the contents of a file, to be uploaded</li>
<li>The type=&quot;file&quot; 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 &quot;upload_file.php&quot; file contains the code for uploading a file:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if ($_FILES[&quot;file&quot;][&quot;error&quot;] &gt; 0)<br />
        {<br />
        echo &quot;Error: &quot; . $_FILES[&quot;file&quot;][&quot;error&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        }<br />
        else<br />
        {<br />
        echo &quot;Upload: &quot; . $_FILES[&quot;file&quot;][&quot;name&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Type: &quot; . $_FILES[&quot;file&quot;][&quot;type&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Size: &quot; . ($_FILES[&quot;file&quot;][&quot;size&quot;] / 1024) . &quot; Kb&lt;br /&gt;&quot;;<br />
        echo &quot;Stored in: &quot; . $_FILES[&quot;file&quot;][&quot;tmp_name&quot;];<br />
        }<br />
        ?&gt; </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 &quot;name&quot;, &quot;type&quot;, &quot;size&quot;, &quot;tmp_name&quot; or &quot;error&quot;. Like this:</p>
<ul>
<li>$_FILES[&quot;file&quot;][&quot;name&quot;] &#8211; the name of the uploaded file</li>
<li>$_FILES[&quot;file&quot;][&quot;type&quot;] &#8211; the type of the uploaded file</li>
<li>$_FILES[&quot;file&quot;][&quot;size&quot;] &#8211; the size in bytes of the uploaded file</li>
<li>$_FILES[&quot;file&quot;][&quot;tmp_name&quot;] &#8211; the name of the temporary copy of   	the file stored on the server</li>
<li>$_FILES[&quot;file&quot;][&quot;error&quot;] &#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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if ((($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/gif&quot;)<br />
        || ($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/jpeg&quot;)<br />
        || ($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/pjpeg&quot;))<br />
        &amp;&amp; ($_FILES[&quot;file&quot;][&quot;size&quot;] &lt; 20000))<br />
        {<br />
        if ($_FILES[&quot;file&quot;][&quot;error&quot;] &gt; 0)<br />
        {<br />
        echo &quot;Error: &quot; . $_FILES[&quot;file&quot;][&quot;error&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        }<br />
        else<br />
        {<br />
        echo &quot;Upload: &quot; . $_FILES[&quot;file&quot;][&quot;name&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Type: &quot; . $_FILES[&quot;file&quot;][&quot;type&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Size: &quot; . ($_FILES[&quot;file&quot;][&quot;size&quot;] / 1024) . &quot; Kb&lt;br   /&gt;&quot;;<br />
        echo &quot;Stored in: &quot; . $_FILES[&quot;file&quot;][&quot;tmp_name&quot;];<br />
        }<br />
        }<br />
        else<br />
        {<br />
        echo &quot;Invalid file&quot;;<br />
        }<br />
        ?&gt; </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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        if ((($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/gif&quot;)<br />
        || ($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/jpeg&quot;)<br />
        || ($_FILES[&quot;file&quot;][&quot;type&quot;] == &quot;image/pjpeg&quot;))<br />
        &amp;&amp; ($_FILES[&quot;file&quot;][&quot;size&quot;] &lt; 20000))<br />
        {<br />
        if ($_FILES[&quot;file&quot;][&quot;error&quot;] &gt; 0)<br />
        {<br />
        echo &quot;Return Code: &quot; . $_FILES[&quot;file&quot;][&quot;error&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        }<br />
        else<br />
        {<br />
        echo &quot;Upload: &quot; . $_FILES[&quot;file&quot;][&quot;name&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Type: &quot; . $_FILES[&quot;file&quot;][&quot;type&quot;] . &quot;&lt;br /&gt;&quot;;<br />
        echo &quot;Size: &quot; . ($_FILES[&quot;file&quot;][&quot;size&quot;] / 1024) . &quot; Kb&lt;br   /&gt;&quot;;<br />
        echo &quot;Temp file: &quot; . $_FILES[&quot;file&quot;][&quot;tmp_name&quot;] . &quot;&lt;br /&gt;&quot;;</p>
<p>        if (file_exists(&quot;upload/&quot; . $_FILES[&quot;file&quot;][&quot;name&quot;]))<br />
        {<br />
        echo $_FILES[&quot;file&quot;][&quot;name&quot;] . &quot; already exists. &quot;;<br />
        }<br />
        else<br />
        {<br />
        move_uploaded_file($_FILES[&quot;file&quot;][&quot;tmp_name&quot;],<br />
        &quot;upload/&quot; . $_FILES[&quot;file&quot;][&quot;name&quot;]);<br />
        echo &quot;Stored in: &quot; . &quot;upload/&quot; . $_FILES[&quot;file&quot;][&quot;name&quot;];<br />
        }<br />
        }<br />
        }<br />
        else<br />
        {<br />
        echo &quot;Invalid file&quot;;<br />
        }<br />
        ?&gt; </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   &quot;upload&quot;</p>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-file-upload/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP File Handling</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-file-handling/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-file-handling/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:09:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP File Handling]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/php/php-advanced/php-file-handling/</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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        $file=fopen(&quot;welcome.txt&quot;,&quot;r&quot;);<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>The file may be opened in one of the following modes:</p>
<table border="1" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr valign="top">
<th align="left" width="20%">Modes</th>
<th align="left" width="80%">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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        $file=fopen(&quot;welcome.txt&quot;,&quot;r&quot;) or exit(&quot;Unable to open file!&quot;);<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<hr />
<h2>Closing a File</h2>
<p>The fclose() function is used to close an open file:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $file = fopen(&quot;test.txt&quot;,&quot;r&quot;);</p>
<p>        //some code to be executed</p>
<p>        fclose($file);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<hr />
<h2>Check End-of-file</h2>
<p>The feof() function checks if the &quot;end-of-file&quot; (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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td> if (feof($file)) echo &quot;End of file&quot;; </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $file = fopen(&quot;welcome.txt&quot;, &quot;r&quot;) or exit(&quot;Unable to open file!&quot;);<br />
        //Output a line of the file until the end is reached<br />
        while(!feof($file))<br />
        {<br />
        echo fgets($file). &quot;&lt;br /&gt;&quot;;<br />
        }<br />
        fclose($file);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<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 border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;?php<br />
        $file=fopen(&quot;welcome.txt&quot;,&quot;r&quot;) or exit(&quot;Unable to open file!&quot;);<br />
        while (!feof($file))<br />
        {<br />
        echo fgetc($file);<br />
        }<br />
        fclose($file);<br />
        ?&gt; </td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-file-handling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Include File</title>
		<link>http://jaffnacampus.com/php/php-advanced/php-include-file/</link>
		<comments>http://jaffnacampus.com/php/php-advanced/php-include-file/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 07:08:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP Advanced]]></category>
		<category><![CDATA[PHP Include File]]></category>

		<guid isPermaLink="false">http://jaffnacampus.com/?p=320</guid>
		<description><![CDATA[Server Side Includes (SSI)
You can insert the content of one PHP file into another PHP file   before the [...]]]></description>
			<content:encoded><![CDATA[<h2>Server Side Includes (SSI)</h2>
<p>You can insert the content of one PHP file into another PHP file   before the   server executes it, with the include() or require() function.</p>
<p>The two functions are   identical in every way, except how they handle errors:</p>
<ul>
<li>include()    generates a warning, but the script will continue execution</li>
<li>require()   	generates a fatal error, and the script will stop</li>
</ul>
<p>These two functions are used to   create functions, headers, footers, or elements that will be reused on   multiple   pages.</p>
<p>Server side includes saves a lot of work. This means that   you can create a standard header, footer, or menu file for all your web   pages. When the header needs to be updated, you can only   update the 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 your web pages).</p>
<hr />
<h2>PHP include() Function</h2>
<p>The include() function takes all the content in a specified file and   includes it   in the current file.</p>
<p>If an error occurs, the include()    function generates a warning, but the script will continue execution.</p>
<h3>Example 1</h3>
<p>Assume that you have a standard header file, called &quot;header.php&quot;. To   include   the header file in a page, use the include() function:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php include(&quot;header.php&quot;); ?&gt;<br />
        &lt;h1&gt;Welcome to my home page!&lt;/h1&gt;<br />
        &lt;p&gt;Some text.&lt;/p&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<h3>Example 2</h3>
<p>Assume we have a standard menu file, called &quot;menu.php&quot;, that should   be used on all   pages:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;a href=&quot;/default.php&quot;&gt;Home&lt;/a&gt;<br />
        &lt;a href=&quot;/tutorials.php&quot;&gt;Tutorials&lt;/a&gt;<br />
        &lt;a href=&quot;/references.php&quot;&gt;References&lt;/a&gt;<br />
        &lt;a href=&quot;/examples.php&quot;&gt;Examples&lt;/a&gt; <br />
        &lt;a href=&quot;/about.php&quot;&gt;About Us&lt;/a&gt; <br />
        &lt;a href=&quot;/contact.php&quot;&gt;Contact Us&lt;/a&gt; </td>
</tr>
</tbody>
</table>
<p>All pages in the Web site should include this menu file.   Here is how it can be done:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;div class=&quot;leftmenu&quot;&gt;<br />
        &lt;?php include(&quot;menu.php&quot;); ?&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;h1&gt;Welcome to my home page.&lt;/h1&gt;<br />
        &lt;p&gt;Some text.&lt;/p&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>If you look at the source code of the page above (in a browser), it   will look like   this:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;div class=&quot;leftmenu&quot;&gt;<br />
        &lt;a href=&quot;/default.php&quot;&gt;Home&lt;/a&gt;<br />
        &lt;a href=&quot;/tutorials.php&quot;&gt;Tutorials&lt;/a&gt;<br />
        &lt;a href=&quot;/references.php&quot;&gt;References&lt;/a&gt;<br />
        &lt;a href=&quot;/examples.php&quot;&gt;Examples&lt;/a&gt; <br />
        &lt;a href=&quot;/about.php&quot;&gt;About Us&lt;/a&gt; <br />
        &lt;a href=&quot;/contact.php&quot;&gt;Contact Us&lt;/a&gt;<br />
        &lt;/div&gt;</p>
<p>        &lt;h1&gt;Welcome to my home page!&lt;/h1&gt;<br />
        &lt;p&gt;Some text.&lt;/p&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p></p>
<hr />
<h2>PHP require() Function</h2>
<p>The require() function is identical to include(), except that it   handles   errors differently.</p>
<p>If an error occurs, the include()    function generates a warning, but the script will continue execution.   The require()   	generates a fatal error, and the script will stop.</p>
<h3>Error Example include() Function</h3>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        include(&quot;wrongFile.php&quot;);<br />
        echo &quot;Hello World!&quot;;<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>Error message:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Warning:</strong> include(wrongFile.php) [function.include]:<br />
        failed to open stream:<br />
        No such file or directory in C:\home\website\test.php on line 5</p>
<p>        <strong>Warning:</strong> include() [function.include]:<br />
        Failed opening &#8216;wrongFile.php&#8217; for inclusion<br />
        (include_path=&#8217;.;C:\php5\pear&#8217;)<br />
        in C:\home\website\test.php on line 5</p>
<p>        Hello World! </td>
</tr>
</tbody>
</table>
<p>Notice that the echo statement is executed! This is because a Warning     does not stop the script execution.</p>
<h3>Error Example require() Function</h3>
<p>Now, let&#8217;s run the same example with the require() function.</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td>&lt;html&gt;<br />
        &lt;body&gt;</p>
<p>        &lt;?php<br />
        require(&quot;wrongFile.php&quot;);<br />
        echo &quot;Hello World!&quot;;<br />
        ?&gt;</p>
<p>        &lt;/body&gt;<br />
        &lt;/html&gt; </td>
</tr>
</tbody>
</table>
<p>Error message:</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td><strong>Warning:</strong> require(wrongFile.php) [function.require]:<br />
        failed to open stream:<br />
        No such file or directory in C:\home\website\test.php on line 5</p>
<p>        <strong>Fatal error:</strong> require() [function.require]:<br />
        Failed opening required &#8216;wrongFile.php&#8217;<br />
        (include_path=&#8217;.;C:\php5\pear&#8217;)<br />
        in C:\home\website\test.php on line 5 </td>
</tr>
</tbody>
</table>
<p>The echo statement is 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 after an error.</p>
]]></content:encoded>
			<wfw:commentRss>http://jaffnacampus.com/php/php-advanced/php-include-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

