<?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>Hot Scripts Blog &#187; PHP</title>
	<atom:link href="http://www.hotscripts.com/blog/category/tutorials/php-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hotscripts.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 17 May 2012 12:18:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>PHP Parameter Skipping and Named Parameters – Finally?</title>
		<link>http://www.hotscripts.com/blog/php-parameter-skipping/</link>
		<comments>http://www.hotscripts.com/blog/php-parameter-skipping/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 15:38:19 +0000</pubDate>
		<dc:creator>seoegghead</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=889</guid>
		<description><![CDATA[Well, sort of; it's not 100% native, but it works, and requires only 1 simple cut-and-pasted line added per function to implement.  This article will detail how to do so, as well as the gist of its inner workings.  It's certainly easy to grep up complaints and feature requests for both parameter skipping and named parameters...<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-parameter-skipping/">PHP Parameter Skipping and Named Parameters – Finally?</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/basics-of-setting-cookies-with-php/' rel='bookmark' title='Basics of Setting Cookies with PHP'>Basics of Setting Cookies with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/track-your-visitors-using-php/' rel='bookmark' title='Track Your Visitors, Using PHP'>Track Your Visitors, Using PHP</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Well, sort of; it&#8217;s not 100% native, but it works, and requires only <strong><em><span style="text-decoration: underline;">1</span></em></strong> simple cut-and-pasted line added per function to implement.  This article will detail how to do so, as well as the gist of its inner workings.  It&#8217;s certainly easy to grep up complaints and feature requests for both parameter skipping and named parameters – two oft-wanted language features.  Stanislav Malyshev, a core PHP developer says on his &#8220;PHP 10.0&#8243; blog that he misses these features in August, 2009 (<a href="http://php100.wordpress.com/2009/08/21/syntax-i-miss-in-php/">http://php100.wordpress.com/2009/08/21/syntax-i-miss-in-php/</a>).  Unfortunately, as we&#8217;ll document below, not everyone agrees.</p>
<p>Many other high-level languages support these features as well.  No matter.  We&#8217;ll examine a nice little workaround approach and implement it.  Let&#8217;s first peruse an example of a hypothetical function that may benefit from these features:</p>
<p><span style="text-decoration: underline;">function getUsers($id=null, $group_id=1, $username = &#8221;, $order=&#8217;order_fld&#8217;, $order_asc=1) {</span><br />
return $users_matching_all_criteria;<br />
}</p>
<p>As to whether 1 public function/method with so many parameters is good practice is beyond the scope of this article – it&#8217;s just a (somewhat contrived) example!  However, one may take the approach of lightly wrapping such a function with special dedicated getters, i.e.:</p>
<p><span style="text-decoration: underline;">function getUserByUsername($username) {</span><br />
return getUsers(null, 1, $username);<br />
}</p>
<p>This is a valid approach.  However, it represents a bunch of meaningless mechanical coding work.  We must have something more productive to do.  Calling the function directly is, of course, even less desirable:</p>
<p>getUsers(null, 1, &#8216;bob&#8217;);</p>
<p>And this will inevitably result in many “off-by-1” errors in parameter passing, as well as hard-coding defaults.</p>
<p>So wouldn&#8217;t it be nice if there were a better way &#8212; an easy way to specify the setting via a named list or skip over parameters with ease?</p>
<p>Unfortunately, there is no totally native way to do this.  Both of the below code snippets or similar might work in another language, but – alas – not PHP:</p>
<p>getUsers(, , $username); // <span style="text-decoration: underline;">Hypothetical; this does not work!</span></p>
<p>or –</p>
<p>getUsers(&#8216;username&#8217; =&gt; $username); // <span style="text-decoration: underline;">Hypothetical; this does not work!</span></p>
<p>Such a syntax would preserve the defaults implicitly, while allowing the programmer to modify those parameters that matter to the task at hand.  PHP IDEs that implement implicit code completion could still indicate the defaults based on the function prototype.  As another perk, it permits the programmer to retroactively change a default without locating all references to that function.  If this is not desired, simply do as one must in PHP currently anyway – hard-code the default value in a particular function call.</p>
<p>Many have proposed solutions that involve the use of hashed arrays as 1 argument, but this involves a lot of repetitive work, and the function no longer works via a list-based syntax unless a lot of code for both types of parameter syntaxes is written.  This will also disable the implicit code completion support of various PHP IDEs.  We happen to use Zend Studio for development, and we find that particular feature enhances our productivity.</p>
<p>We will present an implementation of the above features with a 1 line snippet (an include() file) as the first line of every applicable function like so:</p>
<p>(<strong>Note:</strong> No changes are made to the prototype, and implicit code completion with the various PHP IDEs will even document the function calls!)</p>
<p>function getUsers($id=null, $group_id=1, $username = &#8221;, $order=&#8217;order_fld&#8217;, $order_asc=1) {</p>
<p><strong>include(par.php); // </strong>hook in the Par code</p>
<p>&#8230; code &#8230;</p>
<p>}</p>
<p>One may then call the function like so:</p>
<p>getUsers(_, _, $username); // <span style="text-decoration: underline;">Note the underscores.</span></p>
<p>or –</p>
<p>getUsers(PAR( array(&#8216;username&#8217; =&gt; $username) ));</p>
<p>or even mix named and skipped parameters &#8211;</p>
<p>getUsers(_. PAR( array(&#8216;username&#8217; =&gt; $username) ) );</p>
<p>or even –</p>
<p>getUsers(_. PAR(&#8216;username&#8217;, $username));</p>
<p>(Note: If &#8220;_&#8221; presents a problem, another safer constant may be chosen.  PHP itself allows extended characters 128..255 to be used in the constant and variable grammars.  We briefly examined using &#8220;¬¨ (not symbol),&#8221; but this is very difficult to key on Windows machines; and just plain annoying on Macs.)</p>
<p>As for native support in PHP 6, don&#8217;t count on it:</p>
<p>A PHP &#8220;Developer Minutes&#8221; says there is no &#8220;&#8230; real need for named parameters.&#8221; And it states further that that they &#8220;&#8230; do not want to add it&#8221; (<a href="http://www.php.net/%7Ederick/meeting-notes.html#named-parameters">http://www.php.net/~derick/meeting-notes.html#named-parameters</a>).  The &#8220;PHP Todo Backlog&#8221; (<a href="http://wiki.php.net/todo/backlog#dropped_items">http://wiki.php.net/todo/backlog#dropped_items</a>) lists named parameters under &#8220;Dropped Items.&#8221;  Skipped parameters are not mentioned at all in either, but as aforementioned, Stanislav has mentioned he&#8217;d like to see them.</p>
<p>Our non-native syntax is not even terribly unwieldy, and it&#8217;s unlikely to break much, as it&#8217;s on a per-function basis.  If the PHP team decides to introduce the features natively, it will not conflict for a few reasons.  A constant is used instead of an empty parameter – the most likely native syntax for an implementation of parameter skipping.  The PAR object is even less of a problem and wraps all named parameters.  “par.php” handles and abstracts it all, and is itself a combination of reflection and elegant hackery.  It is all blissfully encapsulated inside one simple include call.  So what gives – why an include?</p>
<p>Well, include is a pseudo-closure of sorts.  Anything within the include retains the scope of the parent without specifying the particular variables as with PHP&#8217;s closure support. It is of this form:</p>
<p>$returnval = include(&#8216;FILE_FUNC_NAME&#8217;);</p>
<p>All parameters in the current scope are &#8220;passed&#8221; by reference to the &#8220;function&#8221; within FILE_FUNC_NAME.  The speed-penalty is on the order of half a millisecond per call – half of which seems to be from the include, and the other from the reflection API.  Then penalty, of course, is only present for those functions where it is implemented.  APC seems to speed it up as well, though we didn&#8217;t benchmark as much this way.</p>
<p>It&#8217;s simple on the outside, and trivial to implement on a per-function basis.  As far as we can tell, PHP 5.3&#8242;s closures cannot easily accomplish the same due to their requirement of explicitly stating relevant variables in &#8220;use.&#8221; This implementation does not require PHP 5.3, and works with any version of PHP with support for reflection.  You may download the applicable code and see more examples of implementation at the below URL:<br />
<a href="http://seoegghead.com/software/PHP-parameter-skipping-and-named-parameters.seo">http://seoegghead.com/software/PHP-parameter-skipping-and-named-parameters.seo</a><br />
<strong>Limitations:</strong><br />
So far reference parameters are not implemented for PAR(), and there may be limitations with objects or it may create a copy where you might not expect.  we just rarely use reference parameter passing in our design patterns.  In PHP, references are a tool of convenience, not performance.  Feel free to fix or contribute, and we&#8217;ll credit your contribution.  Enjoy!</p>
<div class="hotlist"><strong>Author: SEO Egghead</strong></p>
<p><a href="http://www.seoegghead.com/">SEO Egghead</a> is a web development firm dedicated to creating custom, search-engine-optimized web site applications.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-parameter-skipping/">PHP Parameter Skipping and Named Parameters – Finally?</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/basics-of-setting-cookies-with-php/' rel='bookmark' title='Basics of Setting Cookies with PHP'>Basics of Setting Cookies with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/track-your-visitors-using-php/' rel='bookmark' title='Track Your Visitors, Using PHP'>Track Your Visitors, Using PHP</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/php-parameter-skipping/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing State-enabled Applications With PHP</title>
		<link>http://www.hotscripts.com/blog/developing-php-applications/</link>
		<comments>http://www.hotscripts.com/blog/developing-php-applications/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:59 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=594</guid>
		<description><![CDATA[This article explains how to increase interactivity of your website by using either cookies or sessions to remember the state of the browsing session of your visitors.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/developing-php-applications/">Developing State-enabled Applications With PHP</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/phps-cookie-handeling-functions/' rel='bookmark' title='PHP&#8217;s Cookie handeling functions'>PHP&#8217;s Cookie handeling functions</a></li>
<li><a href='http://www.hotscripts.com/blog/basics-of-setting-cookies-with-php/' rel='bookmark' title='Basics of Setting Cookies with PHP'>Basics of Setting Cookies with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/login-php-mysql/' rel='bookmark' title='Developing a Login System with PHP and MySQL'>Developing a Login System with PHP and MySQL</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span style="font-family: Verdana; ">When a user is browsing through a website and is surfing from one web page to another, sometimes the website needs to remember the actions (e.g. choices) performed by the user. For example, in a website that sells DVDs, the user typically browses through a list of DVDs and selects individual DVDs for check out at the end of the shopping session. The website needs to remember which DVDs the user has selected because the selected items needs to be presented again to the user when the user checks out. In other words, the website needs to remember the State &#8211; i.e. the selected items &#8211; of the user&#8217;s browsing activities. </span><span><span style="font-family: Verdana; "> </span><span style="font-family: Verdana; ">However, HTTP is a Stateless protocol and is ill-equipped to handle States. A standard HTML website basically provides information to the user and a series of links that simply directs the user to other related web pages. This Stateless nature of HTTP allows the website to be replicated across many servers for load balancing purposes. A major drawback is that while browsing from one page to another, the website does not remember the State of the browsing session. This make interactivity almost impossible. </span></p>
<p><span style="font-family: Verdana; ">In order to increase interactivity, the developer can use the session handling features of PHP to augment the features of HTTP in order to remember the State of the browsing session. The are basically 2 ways PHP does this:</span></p>
<p>- Using cookies<br />
- Using Sessions</p>
<p></span></p>
<p><span style="font-family: Verdana; ">The next installment discusses how to manage sessions using cookies&#8230; </span></p>
<p><span style="font-family: Verdana; "><strong>Cookies </strong></span></p>
<p><span style="font-family: Verdana; ">Cookies are used to store State-information in the browser. Browsers are allowed to keep up to 20 cookies for each domain and the values stored in the cookie cannot exceed 4 KB. If more than 20 cookies are created by the website, only the latest 20 are stored. Cookies are only suitable in instances that do not require complex session communications and are not favoured by some developers because of privacy issues. Furthermore, some users disable support for cookies at their browsers. </span></p>
<p><span style="font-family: Verdana; ">- The following is a typical server-browser sequence of events that occur when a cookie is used:<br />
- The server knows that it needs to remember the State of browsing session<br />
- The server creates a cookie and uses the Set-Cookie header field in the HTTP response to pass the cookie to the browser<br />
- The browser reads the cookie field in the HTTP response and stores the cookie<br />
- This cookie information is passed along future browser-server communications and can be used in the PHP scripts as a variable </span></p>
<p><span style="font-family: Verdana; ">PHP provides a function called setcookie() to allow easy creation of cookies. The syntax for setcookie is: </span></p>
<p><span style="font-family: Verdana; ">int setcookie(string name, [string val], [int expiration_date], [string path], string domain, [int secure]) </span></p>
<p><span style="font-family: Verdana; ">The parameters are:</span></p>
<p><span style="color: #191970;">name</span> &#8211; this is a mandatory parameter and is used subsequently to identify the cookie<br />
<span style="color: #191970;">value</span> &#8211; the value of the cookie &#8211; e.g. if the cookie is used to store the name of the user, the value parameter will store the actual name &#8211; e.g. John<br />
<span style="color: #191970;">expiration_date</span> &#8211; the lifetime of the cookie. After this date, the cookie expires and is unusable<br />
<span style="color: #191970;">path</span> &#8211; the path refers to the URL from which the cookie is valid and allowed<br />
<span style="color: #191970;">domain</span> &#8211; the domain the created the cookie and is allowed to read the contents of the cookie<br />
<span style="color: #000080;">secure</span> &#8211; specifies if the cookie can be sent only through a secure connection &#8211; e.g. SSL enable sessions</p>
<p><span style="font-family: Verdana; ">The following is an example that displays to the user how many times a specific web page has been displayed to the user. Copy the code below (both the php and the html) into a file with the .php extension and test it out. </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">&lt;?php<br />
//check if the $count variable has been associated with the count cookie<br />
if (!isset($count)) {<br />
$count = 0;<br />
} else {<br />
$count++;<br />
}<br />
setcookie(&#8220;count&#8221;, $count, time()+600, &#8220;/&#8221;, &#8220;&#8221;, 0);<br />
?&gt;</span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">&lt;html&gt;<br />
&lt;</span><span style="font-family: Courier New; color: #ff4500; ">head&gt;<br />
&lt;title&gt;Session Handling Using Cookies&lt;/title&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
This page has been displayed: &lt;?=$count ?&gt; times.<br />
&lt;/body&gt;<br />
&lt;/html&gt;</span></p>
<p><span style="font-family: Verdana; ">The next installment discusses how to manage sessions using PHP session handling functions with cookies enabled&#8230; </span></p>
<p><span style="font-family: Verdana; "><strong>PHP Session Handling &#8211; Cookies Enabled</strong> </span></p>
<p><span style="font-family: Verdana; ">Instead of storing session information at the browser through the use of cookies, the information can instead be stored at the server in session files. One session file is created and maintained for each user session. For example, if there are three concurrent users browsing the website, three session files will be created and maintained &#8211; one for each user. The session files are deleted if the session is explicitly closed by the PHP script or by a daemon garbage collection process provided by PHP. Good programming practice would call for sessions to be closed explicitly in the script. </span></p>
<p><span style="font-family: Verdana; ">The following is a typical server-browser sequence of events that occur when a PHP session handling is used:<br />
The server knows that it needs to remember the State of browsing session<br />
PHP generates a sssion ID and creates a session file to store future information as required by subsequent pages<br />
A cookie is generated wih the session ID at the browser<br />
This cookie that stores the session ID is transparently and automatically sent to the server for all subsequent requests to the server </span></p>
<p><span style="font-family: Verdana; ">The following PHP session-handling example accomplishes the same outcome as the previous cookie example. Copy the code below (both the php and the html) into a file with the .php extension and test it out. </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">&lt;?php<br />
//starts a session<br />
session_start(); </span></p>
<p><span style="font-family: Courier New; color: #ff4500; "> //informs PHP that count information needs to be remembered in the session file<br />
if (!session_is_registered(&#8220;count&#8221;)) {<br />
session_register(&#8220;count&#8221;);<br />
$count = 0; } else {<br />
$count++;<br />
}<br />
$session_id = session_id(); ?&gt; </span></p>
<p><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;title&gt;PHP Session Handling &#8211; Cookie-Enabled&lt;/title&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
The current session id is: &lt;?=$session_id ?&gt;<br />
This page has been displayed: &lt;?=$count ?&gt; times.<br />
&lt;/body&gt;<br />
&lt;/html</span>&gt; </span></p>
<p><span style="font-family: Verdana; ">A summary of the functions that PHP provides for session handling are:</span></p>
<p>boolean start_session() &#8211; initializes a session<br />
string session_id([string id]) &#8211; either returns the current session id or specify the session id to be used when the session is created<br />
boolean session_register(mixed name [, mixed ...]) &#8211; registers variables to be stored in the session file. Each parameter passed in the function is a separate variable<br />
boolean session_is_registered(string variable_name) &#8211; checks if a variable has been previously registered to be stored in the session file<br />
session_unregister(string varriable_name) &#8211; unregisters a variable from the session file. Unregistered variables are no longer valid for reference in the session.<br />
session_unset() &#8211; unsets all session variables. It is important to note that all the variables remain registered.<br />
boolean session_destroy() &#8211; destroys the session. This is opposite of the start_session function.</p>
<p><span style="font-family: Verdana; ">The next installment discusses how to manage sessions using PHP session handling functions when cookies are disabled&#8230; </span></p>
<p><span style="font-family: Verdana; "><strong>PHP Session Handling &#8211; Without Cookies</strong> </span></p>
<p><span style="font-family: Verdana; ">If cookies are disabled at the browser, the above example cannot work. This is because although the session file that stores all the variables is kept at the server, a cookie is still needed at the browser to store the session ID that is used to identify the session and its associated session file. The most common way around this would be to explicitly pass the session ID back to the server from the browser as a query parameter in the URL. </span></p>
<p><span style="font-family: Verdana; ">For example, the PHP script generates requests subsequent to the start_session call in the following format: </span></p>
<p><a href="http://www.yourhost.com/yourphpfile.php?PHPSESSID=[actual"><span style="font-family: Courier New; color: #ff4500; ">http://www.yourhost.com/yourphpfile.php?PHPSESSID=[actual</span></a><span style="font-family: Courier New; color: #ff4500; "> session ID] </span></p>
<p><span style="font-family: Verdana; ">The following are excerpts that illustrate the discussion: </span></p>
<p><span style="font-family: Verdana; ">Manually building the URL: </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">$url = &#8220;</span><a href="http://www.yoursite.com/yourphppage.php?PHPSESSID"><span style="font-family: Courier New; color: #ff4500; ">http://www.yoursite.com/yourphppage.php?PHPSESSID</span></a><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">=&#8221; . session_id();<br />
&lt;a href=&#8221;&lt;?=$url ?&gt;&#8221;&gt;Anchor Text&lt;/a&gt;</span> </span></p>
<p><span style="font-family: Verdana; ">Building the URL using SID: </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">&lt;a href=&#8221;</span><a href="http://www.yoursite.com/yourphppage.php?%3C?=SID"><span style="font-family: Courier New; color: #ff4500; ">http://www.yoursite.com/yourphppage.php?&lt;?=SID</span></a><span style="font-family: Courier New; color: #ff4500; "> ?&gt;&#8221;&gt;Anchor Text&lt;/a&gt;</span></div>
<div class="hotlist">
This article is written by daBoss. daBoss is the Webmaster of Designer Banners. daBoss can be contacted at sales (at) designerbanners (dot) com.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/developing-php-applications/">Developing State-enabled Applications With PHP</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/phps-cookie-handeling-functions/' rel='bookmark' title='PHP&#8217;s Cookie handeling functions'>PHP&#8217;s Cookie handeling functions</a></li>
<li><a href='http://www.hotscripts.com/blog/basics-of-setting-cookies-with-php/' rel='bookmark' title='Basics of Setting Cookies with PHP'>Basics of Setting Cookies with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/login-php-mysql/' rel='bookmark' title='Developing a Login System with PHP and MySQL'>Developing a Login System with PHP and MySQL</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/developing-php-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Displaying An RSS Feed On Your Website Using PHP And MagpieRSS</title>
		<link>http://www.hotscripts.com/blog/rss-feed-php-and-magpierss/</link>
		<comments>http://www.hotscripts.com/blog/rss-feed-php-and-magpierss/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:59 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[magpie rss]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rss]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=605</guid>
		<description><![CDATA[By using RSS and the MagpieRSS toolkit, you can import data from another web site or news source and display that information on your own site.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/rss-feed-php-and-magpierss/">Displaying An RSS Feed On Your Website Using PHP And MagpieRSS</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/rss-really-simply-syndication/' rel='bookmark' title='RSS: Really Simply Syndication'>RSS: Really Simply Syndication</a></li>
<li><a href='http://www.hotscripts.com/blog/joobsbox-free-php-job-board-script/' rel='bookmark' title='JoobsBox &#8211; A free PHP Job Board Script'>JoobsBox &#8211; A free PHP Job Board Script</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span><span style="font-family: Verdana; ">These days everybody wants to have fresh content on their web site. Search engines like to see dynamic web pages, where the content is updated on a regular basis. Static pages that have information that doesn&#8217;t change are not only boring, but less likely to be visited by a search engine spider than a page that changes every time it is displayed. </span><span style="font-family: Verdana; ">By using RSS and the MagpieRSS toolkit, you can import data from another web site or news source and display that information on your own site. </span></p>
<p><span style="font-family: Verdana; ">First, download the MagpieRSS kit from </span><a href="http://magpierss.sourceforge.net/"><span style="font-family: Verdana; ">http://magpierss.sourceforge.net</span></a><span style="font-family: Verdana; ">. </span></p>
<p><span style="font-family: Verdana; ">Next, unpack the archive, into a directory off your root on your web site called &#8220;rss&#8221;. </span></p>
<p><span style="font-family: Verdana; ">Then, create a directory off your root called &#8220;cache&#8221;. CHMOD this directory to 777. </span></p>
<p><span style="font-family: Verdana; ">You&#8217;ll need to know the URL for the feed that you want to display. You can find this by searching for &#8220;RSS feed&#8221; in Google, or by going to one of the many sites that allow you to search thrown various sources for feeds. Syndic8.com is one, for example. </span></p>
<p><span style="font-family: Verdana; ">To display data from a single source, you can use code similar to this: </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">require_once(&#8216;rss/rss_fetch.inc&#8217;); </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">$news_feed = &#8221;; </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">error_reporting(E_ERROR); </span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">$rss = fetch_rss(&#8220;</span><a href="http://www.url-of-the-rss-feed.com/"><span style="font-family: Courier New; color: #ff4500; ">http://www.url-of-the-rss-feed.com</span></a><span style="font-family: Courier New; color: #ff4500; ">&#8220;);<br />
$items = array_slice($rss-&gt;items, 0);<br />
foreach ($items as $item )<br />
{<br />
$news_feed .= &#8221; . $item['title'] . &#8221; . $item['summary'] . &#8221;;<br />
} </span></p>
<p><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">echo $news_feed;</span> </span></p>
<p><span style="font-family: Verdana; ">MagpieRSS not only decodes the data, but it will also cache the data so it will retrieve news articles only once per hour. </span></p>
<p><span style="font-family: Verdana; ">Utilizing RSS in this fashion will allow your web site to have fresh content displayed constantly, and will (hopefully!) keep the search engine spiders interested in your site. The more the spiders index your site, the more pages you will have listed in the search engines. And with more pages listed in the search engine indexes you have a much better chance of attracting people to your web site.</span></p>
<p></span></div>
<div class="hotlist"><strong>Author: Mikel Beck</strong><br />
Mikel Beck is the owner of a number of web sites, the latest being <a href="http://www.happyhourpub.com">The Happy Hour Pub</a>.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/rss-feed-php-and-magpierss/">Displaying An RSS Feed On Your Website Using PHP And MagpieRSS</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/rss-really-simply-syndication/' rel='bookmark' title='RSS: Really Simply Syndication'>RSS: Really Simply Syndication</a></li>
<li><a href='http://www.hotscripts.com/blog/joobsbox-free-php-job-board-script/' rel='bookmark' title='JoobsBox &#8211; A free PHP Job Board Script'>JoobsBox &#8211; A free PHP Job Board Script</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/rss-feed-php-and-magpierss/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Developing a Login System with PHP and MySQL</title>
		<link>http://www.hotscripts.com/blog/login-php-mysql/</link>
		<comments>http://www.hotscripts.com/blog/login-php-mysql/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:59 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=608</guid>
		<description><![CDATA[Most interactive websites nowadays would require a user to log in into the website’s system in order to provide a customized experience for the user. Once the user has logged in, the website will be able to provide a presentation that is tailored to the user’s preferences.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/login-php-mysql/">Developing a Login System with PHP and MySQL</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/developing-php-applications/' rel='bookmark' title='Developing State-enabled Applications With PHP'>Developing State-enabled Applications With PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/php-templating-system/' rel='bookmark' title='Making A Basic Templating System'>Making A Basic Templating System</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span>A basic login system typically contains 3 components:</p>
<ol>
<li>The component that allows a user to register his preferred login id and password</li>
<li>The component that allows the system to verify and authenticate the user when he subsequently logs in</li>
<li>The component that sends the user’s password to his registered email address if the user forgets his password</li>
</ol>
<p>Such a system can be easily created using PHP and MySQL.</p>
<p><strong>Component 1 – Registration</strong></p>
<p>Component 1 is typically implemented using a simple HTML form that contains 3 fields and 2 buttons:</p>
<ol>
<li>A preferred login id field</li>
<li>A preferred password field</li>
<li>A valid email address field</li>
<li>A Submit button</li>
<li>A Reset button</li>
</ol>
<p>Assume that such a form is coded into a file named register.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the register.php page is called when the user clicks on the Submit button.</p>
<pre><span style="color: #ff4500;">[form name="register" method="post" action="register.php"]
   [input name="login id" type="text" value="loginid" size="20"/][br]
   [input name="password" type="text" value="password" size="20"/][br]
   [input name="email" type="text" value="email" size="50"/][br]
   [input type="submit" name="submit" value="submit"/]
   [input type="reset" name="reset" value="reset"/]
[/form]</span></pre>
<p>The following code excerpt can be used as part of register.php to process the registration. It connects to the MySQL database and inserts a line of data into the table used to store the registration information.</p>
<pre><span style="color: #ff4500;">@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="INSERT INTO login_tbl (loginid, password and email) VALUES (".$loginid.”,”.$password.”,”.$email.”)”;
$r = mysql_query($sql);
if(!$r) {
   $err=mysql_error();
   print $err;
   exit();
}</span></pre>
<p>The code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid, $password and $email variables are passed in from the form in register.html using the post method.</p>
<p><strong>Component 2 – Verification and Authentication</strong></p>
<p>A registered user will want to log into the system to access the functionality provided by the website. The user will have to provide his login id and password for the system to verify and authenticate.</p>
<p>This is typically done through a simple HTML form. This HTML form typically contains 2 fields and 2 buttons:</p>
<ol>
<li>A login id field</li>
<li>A password field</li>
<li>A Submit button</li>
<li>A Reset button</li>
</ol>
<p>Assume that such a form is coded into a file named authenticate.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the authenticate.php page is called when the user clicks on the Submit button.</p>
<pre><span style="color: #ff4500;">[form name="authenticate" method="post" action="authenticate.php"]
   [input name="login id" type="text" value="loginid" size="20"/][br]
   [input name="password" type="text" value="password" size="20"/][br]
   [input type="submit" name="submit" value="submit"/]
   [input type="reset" name="reset" value="reset"/]
[/form]</span></pre>
<p>The following code excerpt can be used as part of authenticate.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.</p>
<pre><span style="color: #ff4500;">@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT loginid FROM login_tbl WHERE loginid=’".$loginid.”’ and password=’”.$password.”’”;
$r = mysql_query($sql);
if(!$r) {
   $err=mysql_error();
   print $err;
   exit();
}
if(mysql_affected_rows()==0){
   print "no such login in the system. please try again.";
   exit();
}
else{
   print "successfully logged into system.";
   //proceed to perform website’s functionality – e.g. present information to the user
}</span></pre>
<p>As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid and $password variables are passed in from the form in authenticate.html using the post method.</p>
<p><strong>Component 3 – Forgot Password</strong></p>
<p>A registered user may forget his password to log into the website’s system. In this case, the user will need to supply his loginid for the system to retrieve his password and send the password to the user’s registered email address.</p>
<p>This is typically done through a simple HTML form. This HTML form typically contains 1 field and 2 buttons:</p>
<li>A login id field</li>
<li>A Submit button</li>
<li>A Reset buttonAssume that such a form is coded into a file named forgot.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the forgot.php page is called when the user clicks on the Submit button.
<pre><span style="color: #ff4500;">[form name="forgot" method="post" action="forgot.php"]
   [input name="login id" type="text" value="loginid" size="20"/][br]
   [input type="submit" name="submit" value="submit"/]
   [input type="reset" name="reset" value="reset"/]
[/form]</span></pre>
<p>The following code excerpt can be used as part of forgot.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.</p>
<pre><span style="color: #ff4500;">@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT password, email FROM login_tbl WHERE loginid=’".$loginid.”’”;
$r = mysql_query($sql);
if(!$r) {
   $err=mysql_error();
   print $err;
   exit();
}
if(mysql_affected_rows()==0){
   print "no such login in the system. please try again.";
   exit();
}
else {
   $row=mysql_fetch_array($r);
   $password=$row["password"];
   $email=$row["email"];

   $subject="your password";
   $header="from:you@yourdomain.com";
   $content="your password is ".$password;
   mail($email, $subject, $row, $header);

   print "An email containing the password has been sent to you";
}</span></pre>
<p>As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The value of the $loginid variable is passed from the form in forgot.html using the post method.</p>
<p><strong>Conclusion </strong></p>
<p>The above example is to illustrate how a very basic login system can be implemented. The example can be enhanced to include password encryption and additional functionality – e.g. to allow users to edit their login information.</li>
<p></span></div>
<div class="hotlist"><strong>Author: John L</strong><br />This article is written by daBoss. daBoss is the <a href="http://www.designerbanners.com/">Webmaster of Designer Banners</a>. daBoss can be contacted at sales (at) designerbanners (dot) com.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/login-php-mysql/">Developing a Login System with PHP and MySQL</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/developing-php-applications/' rel='bookmark' title='Developing State-enabled Applications With PHP'>Developing State-enabled Applications With PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/php-templating-system/' rel='bookmark' title='Making A Basic Templating System'>Making A Basic Templating System</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/login-php-mysql/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mastering Regular Expressions in PHP</title>
		<link>http://www.hotscripts.com/blog/regular-expressions-in-php/</link>
		<comments>http://www.hotscripts.com/blog/regular-expressions-in-php/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:58 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=617</guid>
		<description><![CDATA[Want to know what regular expressions are? This article will show you exactly what they are, how they are used, and includes some examples to get started with regular expressions.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/regular-expressions-in-php/">Mastering Regular Expressions in PHP</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/pattern-matching-regular-expressions/' rel='bookmark' title='Pattern matching with Regular Expressions'>Pattern matching with Regular Expressions</a></li>
<li><a href='http://www.hotscripts.com/blog/useful-perl-scripts-with-regular-expressions/' rel='bookmark' title='Useful Perl Scripts With Regular Expressions'>Useful Perl Scripts With Regular Expressions</a></li>
<li><a href='http://www.hotscripts.com/blog/automatically-hyperlink-urls-and-e-mail-addresses-in-asp-net/' rel='bookmark' title='Automatically Hyperlink URLs and E-Mail Addresses in ASP.NET Pages with C#'>Automatically Hyperlink URLs and E-Mail Addresses in ASP.NET Pages with C#</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<table border="0" cellspacing="5" width="100%">
<tbody>
<tr>
<td>
<div><span><span style="font-family: Verdana; "><strong>What are Regular Expressions?</strong> </span></p>
<p><span style="font-family: Verdana; ">A regular expression is a pattern that can match various text strings. Using regular expressions you can find (and replace) certain text patterns, for example &#8220;all the words that begin with the letter A&#8221; or &#8220;find only telephone numbers&#8221;. Regular expressions are often used in validation classes, because they are a really powerful tool to verify e-mail addresses, telephone numbers, street addresses, zip codes, and more. </span></p>
<p><span style="font-family: Verdana; ">In this tutorial I will show you how regular expressions work in PHP, and give you a short introduction on writing your own regular expressions. I will also give you several example regular expressions that are often used. </span></p>
<p><span style="font-family: Verdana; "><strong>Regular Expressions in PHP</strong> </span></p>
<p><span style="font-family: Verdana; ">Using regex (regular expressions) is really easy in PHP, and there are several functions that exist to do regex finding and replacing. Let&#8217;s start with a simple regex find. </span></p>
<p><span style="font-family: Verdana; ">Have a look at the documentation of the preg_match function (http://php.net/preg_match). As you can see from the documentation, preg_match is used to perform a regular expression. In this case no replacing is done, only a simple find. Copy the code below to give it a try. </span></p>
<pre><span style="color: #ff4500; ">&lt;?php

// Example string
$str = "Let's find the stuff &lt;bla&gt;in between&lt;/bla&gt; these two previous brackets";

// Let's perform the regex
$do = preg_match("/&lt;bla&gt;(.*)&lt;\/bla&gt;/", $str, $matches);

// Check if regex was successful
if ($do = true) {
	// Matched something, show the matched string
	echo htmlentities($matches['0']);

	// Also how the text in between the tags
	echo '&lt;br /&gt;' . $matches['1'];
} else {
	// No Match
	echo "Couldn't find a match";
}

?&gt;
</span></pre>
<p><span style="font-family: Verdana; ">After having run the code, it&#8217;s probably a good idea if I do a quick run through the code. Basically, the whole core of the above code is the line that contains the preg_match. The first argument is your regex pattern. This is probably the most important. Later on in this tutorial, I will explain some basic regular expressions, but if you really want to learn regular expression then it&#8217;s best if you look on Google for specific regular expression examples. </span></p>
<p><span style="font-family: Verdana; ">The second argument is the subject string. I assume that needs no explaining. Finally, the third argument can be optional, but if you want to get the matched text, or the text in between something, it&#8217;s a good idea to use it (just like I used it in the example). </span></p>
<p><span style="font-family: Verdana; ">The preg_match function stops after it has found the first match. If you want to find ALL matches in a string, you need to use the preg_match_all function (http://www.php.net/preg_match_all). That works pretty much the same, so there is no need to separately explain it. </span></p>
<p><span style="font-family: Verdana; ">Now that we&#8217;ve had finding, let&#8217;s do a find-and-replace, with the preg_replace function (http://www.php.net/preg_replace). The preg_replace function works pretty similar to the preg_match function, but instead there is another argument for the replacement string. Copy the code below, and run it. </span></p>
<pre><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">&lt;?php

// Example string
$str = "Let's replace the &lt;bla&gt;stuff between&lt;/bla&gt; the bla brackets";

// Do the preg replace
$result = preg_replace ("/&lt;bla&gt;(.*)&lt;\/bla&gt;/", "&lt;bla&gt;new stuff&lt;/bla&gt;", $str);

echo htmlentities($result);
?&gt;</span>
</span></pre>
<p><span style="font-family: Verdana; ">The result would then be the same string, except it would now say &#8216;new stuff&#8217; between the bla tags. This is of course just a simple example, and more advanced replacements can be done. </span></p>
<p><span style="font-family: Verdana; ">You can also use keys in the replacement string. Say you still want the text between the brackets, and just add something? You use the $1, $2, etc keys for those. For example: </span></p>
<pre><span style="color: #ff4500; ">&lt;?php

// Example string
$str = "Let's replace the &lt;bla&gt;stuff between&lt;/bla&gt; the bla brackets";

// Do the preg replace
$result = preg_replace ("/&lt;bla&gt;(.*)&lt;\/bla&gt;/", "&lt;bla&gt;new stuff (the old: $1)&lt;/bla&gt;", $str);

echo htmlentities($result);
?&gt;
</span></pre>
<p><span style="font-family: Verdana; ">This would then print &#8220;Let&#8217;s replace the new stuff (the old: stuff between) the bla brackets&#8221;. $2 is for the second &#8220;catch-all&#8221;, $3 for the third, etc. </span></p>
<p><span style="font-family: Verdana; ">That&#8217;s about it for regular expressions. It seems very difficult, but once you grasp it is extremely easy yet one of the most powerful tools when programming in PHP. I can&#8217;t count the number of times regex has saved me from hours of coding difficult text functions. </span></p>
<p><span style="font-family: Verdana; "><strong>An Example</strong> </span></p>
<p><span style="font-family: Verdana; ">What would a good tutorial be without some real examples? Let&#8217;s first have a look at a simple e-mail validation function. An e-mail address must start with letters or numbers, then have a @, then a domain, ending with an extension. The regex for that would be something like this: ^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$ </span></p>
<p><span style="font-family: Verdana; ">Let me quickly explain that regex. Basically, the first part says that it must all be letters or numbers. Then we get the @, and after that there should be letters and/or numbers again (the domain). Finally we check for a period, and then for an extension. The code to use this regex looks like this: </span></p>
<pre><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">&lt;?php

// Good e-mail
$good = "john@example.com";

// Bad e-mail
$bad = "blabla@blabla";

// Let's check the good e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $good)) {
	echo "Valid e-mail";
} else {
	echo "Invalid e-mail";
}

echo '&lt;br /&gt;';

// And check the bad e-mail
if (preg_match("/^[a-zA-Z0-9_\.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/", $bad)) {
	echo "Valid e-mail";
} else {
	echo "Invalid e-mail";
}

?&gt;</span>
</span></pre>
<p><span style="font-family: Verdana; ">The result of this would be &#8220;Valid E-mail. Invalid E-mail&#8221;, of course. We have just checked if an e-mail address is valid. If you wrap the above code in a function, you&#8217;ve got yourself a e-mail validation function. Keep in mind though that the regex isn&#8217;t perfect: after all, it doesn&#8217;t check whether the extension is too long, does it? Because I want to keep this tutorial short, I won&#8217;t give the full fledged regex, but you can find it easily via Google. </span></p>
<p><span style="font-family: Verdana; "><strong>Another Example</strong> </span></p>
<p><span style="font-family: Verdana; ">Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let&#8217;s assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this: </span></p>
<pre><span style="font-family: Verdana; "><span style="font-family: Courier New; color: #ff4500;">&lt;?php

// Good number
$good = "123-4567890";

// Bad number
$bad = "45-3423423";

// Let's check the good number
if (preg_match("/\d{3}-\d{7}/", $good)) {
	echo "Valid number";
} else {
	echo "Invalid number";
}

echo '&lt;br /&gt;';

// And check the bad number
if (preg_match("/\d{3}-\d{7}/", $bad)) {
	echo "Valid number";
} else {
	echo "Invalid number";
}

?&gt;</span>
</span></pre>
<p><span style="font-family: Verdana; ">The regex is fairly simple, because we use \d. This basically means &#8220;match any digit&#8221; with the length behind it. In this example it first looks for 3 digits, then a &#8216;-&#8217; (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want. </span></p>
<p><span style="font-family: Verdana; "><strong>What exactly is possible with Regular Expressions?</strong> </span></p>
<p><span style="font-family: Verdana; ">Regular expressions are actually one of the most powerful tools in PHP, or any other language for that matter (you can use it in your mod_rewrite rules as well!). There is so much you can do with regex, and we&#8217;ve only scratched the surface in this tutorial with some very basic examples. </span></p>
<p><span style="font-family: Verdana; ">If you really want to dig into regex I suggest you search on Google for more tutorials, and try to learn the regex syntax. It isn&#8217;t easy, and there&#8217;s quite a steep learning curve (in my opinion), but the best way to learn is to go through a lot of examples, and try to translate them in plain English. It really helps you learn the syntax. </span></p>
<p><span style="font-family: Verdana; ">In the future I will dedicate a complete article to strictly examples, including more advanced ones, without any explanation. But for now, I can only give you links to other tutorials: </span></p>
<p><span style="font-family: Verdana; ">The 30 Minute Regex Tutorial (</span><a href="http://www.codeproject.com/dotnet/RegexTutorial.asp" target="new"><span style="font-family: Verdana; ">http://www.codeproject.com/dotnet/RegexTutorial.asp</span></a><span style="font-family: Verdana; ">) </span></p>
<p><span style="font-family: Verdana; ">Regular-Expressions.info (</span><a href="http://www.regular-expressions.info/" target="new"><span style="font-family: Verdana; ">http://www.regular-expressions.info/</span></a><span style="font-family: Verdana; ">) </span></p>
<hr id="null" /><span style="font-family: Verdana; ">Dennis Pallett is a young tech writer, with much experience in ASP, PHP and other web technologies. He enjoys writing, and has written several articles and tutorials. To find more of his work, look at his websites at </span><a href="http://www.phpit.net,/" target="new"><span style="font-family: Verdana; ">http://www.phpit.net,</span></a><span style="font-family: Verdana; "> </span><a href="http://www.aspit.net/" target="new"><span style="font-family: Verdana; ">http://www.aspit.net</span></a><span style="font-family: Verdana; "> and </span><a href="http://www.webdev-articles.com/" target="new"><span style="font-family: Verdana; ">http://www.webdev-articles.com</span></a><span style="font-family: Verdana; "> </span></p>
<p></span></div>
</td>
</tr>
<tr>
<td align="right">
<table border="0" cellspacing="0" cellpadding="1">
<tbody>
<tr>
<td><strong>Pages:</strong></td>
<td>1</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td align="left"></td>
</tr>
</tbody>
</table>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/regular-expressions-in-php/">Mastering Regular Expressions in PHP</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/pattern-matching-regular-expressions/' rel='bookmark' title='Pattern matching with Regular Expressions'>Pattern matching with Regular Expressions</a></li>
<li><a href='http://www.hotscripts.com/blog/useful-perl-scripts-with-regular-expressions/' rel='bookmark' title='Useful Perl Scripts With Regular Expressions'>Useful Perl Scripts With Regular Expressions</a></li>
<li><a href='http://www.hotscripts.com/blog/automatically-hyperlink-urls-and-e-mail-addresses-in-asp-net/' rel='bookmark' title='Automatically Hyperlink URLs and E-Mail Addresses in ASP.NET Pages with C#'>Automatically Hyperlink URLs and E-Mail Addresses in ASP.NET Pages with C#</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/regular-expressions-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ajax &amp; PHP without using the XmlHttpRequest Object</title>
		<link>http://www.hotscripts.com/blog/ajax-php-xmlhttprequest-object/</link>
		<comments>http://www.hotscripts.com/blog/ajax-php-xmlhttprequest-object/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:58 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=619</guid>
		<description><![CDATA[In this tutorial Dennis Pallett shows you how to do Ajax, also known as remote scripting, without having to use the XmlHttpRequest object, using some clever PHP and JavaScript<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/ajax-php-xmlhttprequest-object/">Ajax &#038; PHP without using the XmlHttpRequest Object</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/deep-linking-flash-ajax/' rel='bookmark' title='SWFAddress &#8211; Deep linking for Flash and Ajax'>SWFAddress &#8211; Deep linking for Flash and Ajax</a></li>
<li><a href='http://www.hotscripts.com/blog/object-oriented-javascript/' rel='bookmark' title='Object Oriented Javascript'>Object Oriented Javascript</a></li>
<li><a href='http://www.hotscripts.com/blog/php-automated-thumbnails/' rel='bookmark' title='PHP Automated Thumbnails'>PHP Automated Thumbnails</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span><span style="font-family: Verdana; color: #ff4500; font-size: small;"><strong>Introduction</strong></span><br /><span style="font-family: Verdana; ">Ajax is one of the biggest &#8216;discoveries&#8217; in the past year, and it has become a real buzzword, just like Web 2.0. Admittedly, Ajax can be used for a lot of things, and it really does speed up web applications. Already Ajax is used by many highly popular websites, most notably GMail, but other&#8217;s like </span><a href="http://www.tadalist.com/"><span style="font-family: Verdana; ">Ta-da List</span></a><span style="font-family: Verdana; "> or </span><a href="http://www.flickr.com/"><span style="font-family: Verdana; ">Flickr</span></a><span style="font-family: Verdana; "> also use it. Heck, even Microsoft has gotten wind of the Ajax buzz, and is actually moving towards web-based applications as well.</span></p>
<p><span style="font-family: Verdana; ">But there is one problem with most of the current implementations of Ajax: it has one dependency, and that is the XmlHttpRequest object. Most modern browser, like Firefox, have inbuilt support for this object, but older browsers, like Internet Explorer 6, don&#8217;t have native support for this object. Luckily, IE 6 does support it, but it&#8217;s built in as an ActiveX control, which means your visitors get an ugly warning message about the possible danger of an ActiveX control, or in some cases it just doesn&#8217;t work at all.</span></p>
<p><span style="font-family: Verdana; ">In this tutorial, I will show you how to use Ajax without even having to use the XmlHttpRequest object.</span></p>
<h3 id="toc-the-basics"><span><span style="font-family: Verdana; color: #ff4500; font-size: small;"><strong>The Basics</strong></span> </span></h3>
<p><span style="font-family: Verdana; ">If we can&#8217;t use the XmlHttpRequest object, we must find some other way to include content from another page, without having to resort to other objects or non-standard things. A great candidate for this would be the &lt;script&gt; tag, which is used to include external JavaScript files. What if, instead of using a regular JS file, we point that tag to a PHP file, which outputs JavaScript. A PHP file which looks something like this:</span></p>
<table border="0" cellspacing="2" cellpadding="2" width="100%" bgcolor="#dcdcdc">
<tbody>
<tr>
<td><span><span style="color: #ff4500;"><span style="font-family: Courier New;"><span>&lt;?php</span> </span></span></span><span><span style="color: #ff4500;"><span style="font-family: Courier New;"><span>$html</span> = <span>&#8216;&lt;b&gt;This content came from our Ajax Engine&lt;/b&gt;&#8217;</span>;</span></span></span></p>
<p><span><span style="font-family: Courier New; color: #ff4500; ">?&gt;</span></span></p>
<p><span style="font-family: Courier New; color: #ff4500; ">div = document.getElementById<span>(</span><span>&#8216;contentdiv&#8217;</span><span>)</span>;<br />
div.innerHTML = <span>&#8216;&lt;?php echo $html; ?&gt;&#8217;</span>;</span></td>
</tr>
</tbody>
</table>
<div>
<p><span style="font-family: Verdana; ">When this file is used referenced in a script tag, it will try to set the innerHTML of a div with ID &#8216;contentdiv&#8217;. But there&#8217;s one problem; this file shouldn&#8217;t be included when the page loads, but only when a button is clicked or some other action. To do this, we must somehow dynamically add a new script tag, which is possible using JavaScript. Something like the following would do the trick:</span></p>
<table border="0" cellspacing="2" cellpadding="2" width="100%" bgcolor="#dcdcdc">
<tbody>
<tr>
<td><span style="font-family: Courier New; color: #ff4500; "> </span><span style="font-family: Courier New;"><span><span style="color: #ff4500;"><span>// Get base url</span><br />
url = document.<span>location</span>.<span>href</span>;<br />
xend = url.<span>lastIndexOf</span><span>(</span><span>&#8220;/&#8221;</span><span>)</span> + <span>1</span>;<br />
<span>var</span> base_url = url.<span>substring</span><span>(</span><span>0</span>, xend<span>)</span>; </span></span></span><span style="font-family: Courier New;"><span><span style="color: #ff4500;"><span>function</span> ajax_do <span>(</span>url<span>)</span> <span>{</span><br />
<span>// Does URL begin with http?</span><br />
<span>if</span> <span>(</span>url.<span>substring</span><span>(</span><span>0</span>, <span>4</span><span>)</span> != <span>&#8216;http&#8217;</span><span>)</span> <span>{</span><br />
url = base_url + url;<br />
<span>}</span></span></span></span></p>
<p><span style="font-family: Courier New; color: #ff4500; "> <span>// Create new JS element</span><br />
<span>var</span> jsel = document.<span>createElement</span><span>(</span><span>&#8216;SCRIPT&#8217;</span><span>)</span>;<br />
jsel.<span>type</span> = <span>&#8216;text/javascript&#8217;</span>;<br />
jsel.<span>src</span> = url;</span></p>
<p><span style="font-family: Courier New;"><span><span style="color: #ff4500;"> <span>// Append JS element (therefore executing the &#8216;AJAX&#8217; call)</span><br />
document.<span>body</span>.<span>appendChild</span> <span>(</span>jsel<span>)</span>;<br />
<span>}</span></span></span></span></td>
</tr>
</tbody>
</table>
</div>
<div>
<p><span style="font-family: Verdana; ">This code first gets the current directory of the url, so we have a base url. The &#8216;ajax_do&#8217; function is the thing that does all the work. It first checks whether the url passed to the function points to another domain, or is a relative file.</span></div>
<p><span style="font-family: Verdana; ">It then creates a new script element, using the createElement() function. After that it sets the src attribute of the script element, and adds the script element to the body, effectively &#8216;loading&#8217; the file that is referenced by the script element.</span></p>
<p><span style="font-family: Verdana; ">All we need now is a simple page that triggers the Ajax call, i.e.</span></p>
<table border="0" cellspacing="2" cellpadding="2" width="100%" bgcolor="#dcdcdc">
<tbody>
<tr>
<td><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;html&gt;</span><br />
</span></span></span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;head&gt;</span><br />
</span></span></span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;title&gt;</span>Demo 1 &#8211; The Basic&#8217;s</span></span></span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;/title&gt;</span> </span></span></span><span style="font-family: Courier New; color: #ff4500; "> </span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;script</span> <span>type</span>=<span>&#8220;text/javascript&#8221;</span> <span>src</span>=<span>&#8220;engine.js&#8221;</span><span>&gt;</span></span></span></span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;/script&gt;</span><br />
</span></span></span><span><span><span style="font-family: Courier New; color: #ff4500; ">&lt;/head&gt;</span></span></span></span></span></p>
<p><span style="font-family: Courier New; color: #ff4500; "> </span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;body&gt;</span><br />
</span></span></span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;div</span> <span>id</span>=<span>&#8220;contentdiv&#8221;</span><span>&gt;</span></span></span></span></span></span></p>
<p><span style="font-family: Courier New; color: #ff4500; "> </span><span><span><span style="font-family: Courier New; color: #ff4500; ">&lt;/div&gt;</span></span></span></p>
<p><span style="font-family: Courier New; color: #ff4500; "> </span><span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span>&lt;input</span> <span>type</span>=<span>&#8220;button&#8221;</span> <span>onclick</span>=<span>&#8220;ajax_do (&#8216;page1.php&#8217;);&#8221;</span> <span>value</span>=<span>&#8220;Get content&#8221;</span> /<span>&gt;</span><br />
</span></span></span><span><span style="font-family: Courier New;"><span style="color: #ff4500;"><span><span>&lt;/body&gt;</span><br />
</span><span><span><span>&lt;/html&gt;</span></span></span></span></span></span></span></p>
<p></span></span></span></span></td>
</tr>
</tbody>
</table>
<div><span><span><span><span><span><span><span><span><span><span><span><span><span><span style="font-family: Verdana; ">(</span><a href="http://www.phpit.net/demo/php%20and%20ajax%20remix/page1.html"><span style="font-family: Verdana; ">View Live Demo</span></a><span style="font-family: Verdana; ">)</span></span></span></span></p>
<p></span></span></span></span></span></span></span></span></span></span></div>
<p><span style="font-family: Verdana; ">If you view the live demo, or setup it up yourself, you will notice that it works just like Ajax, and probably even better in IE (no more ActiveX warnings).</span></p>
<p><em><span style="font-family: Verdana; ">Please note that for this to work in IE, the security level can&#8217;t be at &#8216;High&#8217;. It must be at &#8216;Medium&#8217; or lower.</span></em></p>
<p></span></div>
<div class="hotlist"><strong>Author: Dennis Pallett</strong><br />
Dennis Pallett is a young web developer, who owns several web sites  including <a href="http://www.phpit.net">PHPit</a> and <a href="http://www.webpubhq.com">WebPubHQ</a>. He has been programming for several years now, and has extensive knowledge in PHP, JavaScript, ASP and other languages.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/ajax-php-xmlhttprequest-object/">Ajax &#038; PHP without using the XmlHttpRequest Object</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/deep-linking-flash-ajax/' rel='bookmark' title='SWFAddress &#8211; Deep linking for Flash and Ajax'>SWFAddress &#8211; Deep linking for Flash and Ajax</a></li>
<li><a href='http://www.hotscripts.com/blog/object-oriented-javascript/' rel='bookmark' title='Object Oriented Javascript'>Object Oriented Javascript</a></li>
<li><a href='http://www.hotscripts.com/blog/php-automated-thumbnails/' rel='bookmark' title='PHP Automated Thumbnails'>PHP Automated Thumbnails</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/ajax-php-xmlhttprequest-object/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP Server to Client with No Refresh</title>
		<link>http://www.hotscripts.com/blog/php-server-client-refresh/</link>
		<comments>http://www.hotscripts.com/blog/php-server-client-refresh/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:58 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=626</guid>
		<description><![CDATA[Although most of our companies work is template based design, the end result is always unique and adapts to each client's individual needs.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-server-client-refresh/">PHP Server to Client with No Refresh</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/active-server-pages/' rel='bookmark' title='Active Server Pages'>Active Server Pages</a></li>
<li><a href='http://www.hotscripts.com/blog/client-side-text-field-validation-with-javascript/' rel='bookmark' title='Client-side text field validation with Javascript'>Client-side text field validation with Javascript</a></li>
<li><a href='http://www.hotscripts.com/blog/6zap-webmail-client/' rel='bookmark' title='6zap – An Open Source Webmail Client'>6zap – An Open Source Webmail Client</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span><span style="font-family: Verdana; ">The process of merging a client&#8217;s content and style with our templates creates an opportunity to challenge ourselves and once again put our web design skills to the test. </span></p>
<p><span style="font-family: Verdana; ">Recently, I found myself in a situation where it was necessary to pass information in the form of GET data from a simple flash button to a server side scripting language- all without reloading the current page. A client was running several different flash animated banners ads via XML layer popup, underlining some of her most popular website products and online services. She needed a simple way to track the overall efficiency of her small ad campaign. Specifically, she needed to know which banners were being clicked on and which banners were simply annoying or inconsequential to her client base. She also needed to know which were the most popular browsers accessing these pages. </span></p>
<p><span style="font-family: Verdana; ">I&#8217;ll try to describe what needed to happen with out getting too techie.</span></p>
<p><span style="font-family: Verdana; ">An XML layer popup would pop up, offering the end user with a two options. In Option A, one could click on the cute little popup. This would take them to wherever the popup was designed to take them. Option B was for the end user to close the popup, and that would simply hide the XML layer&#8217;s visibility property.<br />
At first, it sounded easy. However, beyond the obvious functionality of options A and B, each option needed to open, write, and save to an external file all without refreshing the current page. After all, the last thing anyone wants to see after closing a popup is another page pop up. </span></p>
<p><span style="font-family: Verdana; ">Nevertheless server side scripting languages, like PHP, require a refresh of the page to pass information. Unlike JavaScript which handles its business on the client side of a client server system via your browser (the client), PHP scripts are server-side because they operate solely on the server; data is sent to via POST or GET The script is then parsed, and the new data is sent back to the browser if necessary. </span></p>
<p><span style="font-family: Verdana; ">Here&#8217;s the solution. I created the following &lt;iframe&gt;. </span></p>
<table border="0" cellspacing="2" cellpadding="2" width="100%" bgcolor="#dcdcdc">
<tbody>
<tr>
<td><span style="font-family: Courier New; color: #ff4500; ">&lt;IFRAME id=&#8221;ifrMain&#8221; name=&#8221;main&#8221; src=&#8221;myscript.php&#8221;<br />
frameborder=&#8221;0&#8243; width=&#8221;0&#8243; height=&#8221;0&#8243; scrolling=&#8221;no&#8221;<br />
&gt;&lt;/IFRAME&gt; </span></td>
</tr>
</tbody>
</table>
<p><span style="font-family: Verdana; ">Note that the SRC property is the location of our PHP script, which will be summoned later, to write and save to our external file. Notice our width and height properties are both set to zero. </span></p>
<p><span style="font-family: Verdana; ">I still submit the data to my PHP script, from within the flash banner popup<br />
with the help of ActionScript&#8217;s cool little getURL() function:.</span></p>
<table border="0" cellspacing="2" cellpadding="2" width="100%" bgcolor="#dcdcdc">
<tbody>
<tr>
<td><span style="font-family: Courier New; color: #ff4500; ">on(press){<br />
GetURL(&#8220;myscript.php?banner=this&amp;action=close&#8221;,&#8221;main&#8221;,<br />
&#8220;GET&#8221;);<br />
}</span></td>
</tr>
</tbody>
</table>
<p><span style="font-family: Verdana; ">However because the target (main) was loaded inside our little hidden &lt;iframe&gt;, only the &lt;iframe&gt; refreshes. The user will not see a window refresh, the scrip will be parsed by PHP and everyone lived happily ever after.</span></p>
<p></span></div>
<div class="hotlist"><strong>Author: Adam Fletcher </strong><br />Adam Fletcher is the webmaster of Hardware Software Articles <a href="http://www.hardwaresoftwarearticles.com">http://www.hardwaresoftwarearticles.com</a> .</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-server-client-refresh/">PHP Server to Client with No Refresh</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/active-server-pages/' rel='bookmark' title='Active Server Pages'>Active Server Pages</a></li>
<li><a href='http://www.hotscripts.com/blog/client-side-text-field-validation-with-javascript/' rel='bookmark' title='Client-side text field validation with Javascript'>Client-side text field validation with Javascript</a></li>
<li><a href='http://www.hotscripts.com/blog/6zap-webmail-client/' rel='bookmark' title='6zap – An Open Source Webmail Client'>6zap – An Open Source Webmail Client</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/php-server-client-refresh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP / Apache Templating</title>
		<link>http://www.hotscripts.com/blog/php-apache-templating/</link>
		<comments>http://www.hotscripts.com/blog/php-apache-templating/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:57 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=634</guid>
		<description><![CDATA[Here's a quick tip to have a simple template-based website. I use this method on my Textpattern-powered site and it works great! This method does not requires any installation of PHP template engines such as Smarty, XTemplate, etc. All it takes is 2 lines in your .htaccess file. So, how am I doing it? Sort answer: using Apache directives.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-apache-templating/">PHP / Apache Templating</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/php-templating-system/' rel='bookmark' title='Making A Basic Templating System'>Making A Basic Templating System</a></li>
<li><a href='http://www.hotscripts.com/blog/htaccess-wrappers-with-php/' rel='bookmark' title='.htaccess Wrappers with PHP'>.htaccess Wrappers with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/phps-header-function/' rel='bookmark' title='PHP&#8217;s Header Function'>PHP&#8217;s Header Function</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div><span><span style="font-family: Verdana; ">Here&#8217;s a quick tip to have a simple template-based website. I use this method on my Textpattern-powered site and it works great!</span></p>
<p><span style="font-family: Verdana; ">This method does not requires any installation of PHP template engines such as Smarty, XTemplate, etc. All it takes is 2 lines in your <code>.htaccess</code> file.</span></p>
<p><strong><span style="font-family: Verdana; ">Well, how am I doing it?</span></strong></p>
<p><span style="font-family: Verdana; ">Sort answer: using Apache directives.</span></p>
<p><span style="font-family: Verdana; ">Longer answer: using Apache directives to <strong>auto-append</strong> and <strong>auto-prepend</strong> header and footer files. </span></p>
<p><strong><span style="font-family: Verdana; ">To achieve this, do the following:</span></strong></p>
<ol>
<li><span style="font-family: Verdana; ">Create an HTML/PHP file with your design layout. </span></li>
<li><span style="font-family: Verdana; ">Break this file into 3 portions, <strong>before</strong> dynamic content, <strong>content</strong>, and <strong>after</strong> dynamic content. </span></li>
<li><span style="font-family: Verdana; ">Save the before portion as <span style="font-family: monospace;">head</span><code>er.php</code> and the after portion as <code>footer.php</code> in your server’s root directory. </span></li>
<li><span style="font-family: Verdana; ">In your <code>.htaccess</code>, add the following lines:</span><code><br />
<span style="font-family: Verdana; ">php_value  auto_prepend_file  /header.php<br />
php_value  auto_append_file  /footer.php</span></code><span style="font-family: Verdana; "> </span></li>
<li><span style="font-family: Verdana; ">That’s it. </span></li>
</ol>
<p><span style="font-family: Verdana; ">Now, create your website as you normally would. Every time your pages will load, Apache will automatically “wrap” them with your header and footer files, producing your desired end result.</span></p>
<p><span style="font-family: Verdana; ">I recommend using the .html file extension for the header and footer files to save server load if your pages are not dynamic pages.</span></p>
<p><span style="font-family: Verdana; ">PLEASE NOTE: Your webhost may not allow you to use these Apache directives, so be sure to check that out before hand.</span></p>
<p></span></div>
<table border="0" cellspacing="0" cellpadding="1">
<tbody>
<tr>
<td><strong>Pages:</strong></td>
<td>1</td>
</tr>
</tbody>
</table>
<div class="hotlist"><strong>Author: Ran Aroussi </strong><br /><a href="http://aroussi.com/">Ran Aroussi</a> is a computer developer &#038; designer working with computers and the Internet since 1996. Ran interests include (but not limited to) web development, standards and programming.</div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-apache-templating/">PHP / Apache Templating</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/php-templating-system/' rel='bookmark' title='Making A Basic Templating System'>Making A Basic Templating System</a></li>
<li><a href='http://www.hotscripts.com/blog/htaccess-wrappers-with-php/' rel='bookmark' title='.htaccess Wrappers with PHP'>.htaccess Wrappers with PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/phps-header-function/' rel='bookmark' title='PHP&#8217;s Header Function'>PHP&#8217;s Header Function</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/php-apache-templating/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UnitTesting in PHP using SimpleTest</title>
		<link>http://www.hotscripts.com/blog/unittesting-using-simpletest/</link>
		<comments>http://www.hotscripts.com/blog/unittesting-using-simpletest/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:56 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=640</guid>
		<description><![CDATA[Unit testing is writing more code which will test the main code wirtten by "throwing" sample data at it and examining what it gets back.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/unittesting-using-simpletest/">UnitTesting in PHP using SimpleTest</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/php-error-log-file-archive/' rel='bookmark' title='Create Own PHP Error Log File Archive'>Create Own PHP Error Log File Archive</a></li>
<li><a href='http://www.hotscripts.com/blog/creating-an-image-with-phps-gd/' rel='bookmark' title='Creating an Image with PHP&#8217;s GD'>Creating an Image with PHP&#8217;s GD</a></li>
<li><a href='http://www.hotscripts.com/blog/track-your-visitors-using-php/' rel='bookmark' title='Track Your Visitors, Using PHP'>Track Your Visitors, Using PHP</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>crcr(If you haven’t downloaded SimpleTest framework yet, <a href="http://www.lastcraft.com/simple_test.php">click here</a>.)</p>
<p>You will probably become a Test-infected developer if you try a unit testing framework! But what is unit testing?</p>
<p>&#8220;<em>The basic concept of unit testing is write more code which will test the main code we&#8217;ve written, by &#8220;throwing&#8221; sample data at it and examining what it gets back.</em>&#8220;-Harry Fuecks.</p>
<p>Some developers might not like the idea of writing more code but it will save you a good time pin pointing the exact piece of code causing the problem when your script becomes large.</p>
<p>Time to get practical about UnitTesting! We will write a test case for a simple file manipulation class. This file class will have the basic operations needed to manipulate files. It will be able to create, read, write, append and delete files and our test case should test each operation individually.<br />
First, here is the definition of the class:<br />
<strong>[file.class.php] </strong></p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code>&lt;?php<br />
<strong>class</strong> <strong>File<br />
</strong>{<br />
<strong>var</strong> $filename;</code></p>
<p><em>/**<br />
* Constructor<br />
* will take care of creating the file if it does not exists.<br />
* @param string $file<br />
*/<br />
</em> <strong>function</strong> <strong>File</strong>($file)<br />
{<br />
<strong>if</strong> (<strong>empty</strong>($file))<br />
<strong>die</strong>(&#8216;Filename should not be empty&#8217;);</p>
<p>$this-&gt;filename = $file;</p>
<p><em>//if the file does not exists and we can not create it, terminate the script<br />
</em> <strong>if</strong> (!$this-&gt;exists() &amp;&amp; !$this-&gt;create())<br />
<strong>die</strong>(&#8216;Unable to find/create the file&#8217;);<br />
}</p>
<p><em>/**<br />
* checks if the file exists or not!<br />
* @return bool<br />
*/<br />
</em> <strong>function</strong> exists()<br />
{<br />
<strong>return</strong> <strong>file_exists</strong>($this-&gt;filename);<br />
}</p>
<p><em>/**<br />
* This method will attempt to create a file if it does not exists.<br />
* @return bool<br />
*/<br />
</em> <strong>function</strong> create()<br />
{<br />
<em>//if the file exists, save the trouble opening it.<br />
</em> <strong>if</strong> ($this-&gt;exists())<br />
<strong>return</strong> <strong>true</strong>;</p>
<p><strong>return</strong> $this-&gt;putContents(null);<br />
}</p>
<p><em>/**<br />
* reads the file&#8217;s contents and returns it..<br />
* @return string<br />
*/<br />
</em> <strong>function</strong> getContents()<br />
{<br />
<strong>return</strong> @file_get_contents($this-&gt;filename);<br />
}</p>
<p><em>/**<br />
* writes to the file..<br />
* @param string $content<br />
* @return bool<br />
*/<br />
</em> <strong>function</strong> putContents($content)<br />
{<br />
$fp = @<strong>fopen</strong>($this-&gt;filename, &#8216;wb&#8217;);<br />
$write = @<strong>fwrite</strong>($fp, $content);<br />
@<strong>fclose</strong>($fp);</p>
<p><strong>return</strong> !($write === <strong>false</strong>);<br />
}</p>
<p><em>/**<br />
* append data to the file..<br />
* @param string $content<br />
* @return bool<br />
*/<br />
</em> <strong>function</strong> append($content)<br />
{<br />
$fp = @<strong>fopen</strong>($this-&gt;filename, &#8216;ab&#8217;);<br />
$append = @<strong>fwrite</strong>($fp, $content);<br />
@<strong>fclose</strong>($fp);</p>
<p><strong>return</strong> !($append === <strong>false</strong>);<br />
}</p>
<p><em>/**<br />
* deletes the file..<br />
* @return bool<br />
*/<br />
</em> <strong>function</strong> delete()<br />
{<br />
<strong>return</strong> @unlink($this-&gt;filename);<br />
}<br />
}<br />
?&gt;</td>
</tr>
</tbody>
</table>
<p>I will assume that you are able to understand how the code works since we are talking about unit testing which is far more advanced than file manipulation.<br />
If you can&#8217;t understand how this class works, I suggest you learn first about OOP then learn about unit testing.<br />
Anyway, it&#8217;s not the best file class out there because I created it just for this tutorial so don&#8217;t get mad about it <img src='http://www.hotscripts.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h2 id="toc-writing-the-test-case">Writing The Test Case</h2>
<p>Now we want to create a test case for this class to see if it works as we expect or not!<br />
To create a test case we have to create a new class which inherits from UnitTestCase class which is found in the file unit_tester.php which comes in SimpleTest framework package.<br />
So we create our new PHP file, let&#8217;s name it fileTest.php and include unit_tester.php and our file file.class.php:<br />
[fileTest.php]</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#cccccc">
<tbody>
<tr>
<td><code>&lt;?php<br />
<strong>include_once</strong> 'simpletest/unit_tester.php';<br />
<strong><br />
include_once</strong> 'file.class.php';</code></td>
</tr>
</tbody>
</table>
<p>Of course you have to change the paths to the correct paths in your environment.<br />
We now start the definition of the test case class and let&#8217;s name it fileTest as well:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#cccccc">
<tbody>
<tr>
<td><code><strong>class</strong> fileTest <strong>extends</strong> UnitTestCase<br />
{<br />
<strong>var</strong> $file;<br />
<strong>var</strong> $filename;</code></p>
<p><strong>function</strong> fileTest($filename)<br />
{<br />
$this-&gt;filename = $filename;<br />
$this-&gt;<strong>file</strong> = <strong>new</strong> <strong>file</strong>($this-&gt;filename);<br />
$this-&gt;UnitTestCase(&#8216;File Manipulation Test&#8217;);<br />
}</p>
<p><strong>function</strong> setUp()<br />
{<br />
$fp = @<strong>fopen</strong>($this-&gt;filename, &#8216;x&#8217;);<br />
<strong>if</strong> (!($fp === <strong>false</strong>)) {<br />
<strong>fwrite</strong>($fp, &#8221;);<br />
<strong>fclose</strong>($fp);<br />
}<br />
}</p>
<p><strong>function</strong> tearDown()<br />
{<br />
@unlink($this-&gt;filename);<br />
}</td>
</tr>
</tbody>
</table>
<p>As you can see, we have defined 3 methods (including the constructor) and 2 data members, $file and $filename.<br />
The constructor (fileTest) takes one argument which is the file name and assign it to the data member $filename and create the file object and assign it to $file.<br />
The line:  $this-&gt;UnitTestCase(&#8216;File Manipulation Test&#8217;);  is optional and it just makes a header line in the test reporter (we will talk about this later).</p>
<p>Also we have defined the methods setUp() and tearDown().<br />
setUp() will be called automatically before each and every test and tearDown() will be called after each and every test. However, these two methods are optional.</p>
<p>We have defined the setUp() method to create a new clean file before each test and tearDown() will delete that file after each test.</p>
<p>Now let&#8217;s write our first test! To create a test you simply have to define a method which starts with the word &#8220;test&#8221;.<br />
It doesn&#8217;t matter if you use an underscore after the word &#8220;test&#8221; or not! As long as &#8220;test&#8221; is the first word, it doesn&#8217;t matter. Let&#8217;s see our first test:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code> <strong>function</strong> testFileExists()<br />
{<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;exists());<br />
clearstatcache();<br />
$this-&gt;assertTrue(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
}</code></td>
</tr>
</tbody>
</table>
<p>In this test, we check for the file existence twice (paranoid?) using the method assertTrue() which will insure that the method exists() will return true!<br />
Then  we use the built-in function file_exists() to double check that the file truely exists!<br />
I&#8217;ll tell you later why we checked twice.</p>
<p>UnitTesting in SimpleTest depends heavily on assertions! Like in our previous test we used the method assertTrue() which will require the argument passed to it to be true in order to pass or it will fail!<br />
It&#8217;s worth saying that assertTrue() will pass as long as the argument is neither 0 nor false. So assertTrue(&#8220;String&#8221;) will pass.<br />
If you want to be strict about this, use assertIdentical() which will check the value and the type. e.g. assertIdentical(&#8220;true&#8221;, true) will fail!</p>
<p>SimpleTest has many assert*() methods and in our UnitTestCase class we have these:</p>
<table border="1" cellspacing="1" bordercolor="#c0c0c0">
<tbody>
<tr>
<td>assertTrue($x)</td>
<td>Fail if $x is false</td>
</tr>
<tr>
<td>assertFalse($x)</td>
<td>Fail if $x is true</td>
</tr>
<tr>
<td>assertNull($x)</td>
<td>Fail if $x is set</td>
</tr>
<tr>
<td>assertNotNull($x)</td>
<td>Fail if $x not set</td>
</tr>
<tr>
<td>assertIsA($x, $t)</td>
<td>Fail if $x is not the class or type $t</td>
</tr>
<tr>
<td>assertNotA($x, $t)</td>
<td>Fail if $x is of the class or type $t</td>
</tr>
<tr>
<td>assertEqual($x, $y)</td>
<td>Fail if $x == $y is false</td>
</tr>
<tr>
<td>assertNotEqual($x, $y)</td>
<td>Fail if $x == $y is true</td>
</tr>
<tr>
<td>assertIdentical($x, $y)</td>
<td>Fail if $x == $y is false or a type mismatch</td>
</tr>
<tr>
<td>assertNotIdentical($x, $y)</td>
<td>Fail if $x == $y is true and types match</td>
</tr>
<tr>
<td>assertReference($x, $y)</td>
<td>Fail unless $x and $y are the same variable</td>
</tr>
<tr>
<td>assertCopy($x, $y)</td>
<td>Fail if $x and $y are the same variable</td>
</tr>
<tr>
<td>assertWantedPattern($p, $x)</td>
<td>Fail unless the regex $p matches $x</td>
</tr>
<tr>
<td>assertNoUnwantedPattern($p, $x)</td>
<td>Fail if the regex $p matches $x</td>
</tr>
<tr>
<td>assertNoErrors()</td>
<td>Fail if any PHP error occoured</td>
</tr>
<tr>
<td>assertError($x)</td>
<td>Fail if no PHP error or incorrect message</td>
</tr>
<tr>
<td>assertErrorPattern($p)</td>
<td>Fail unless the error matches the regex $p</td>
</tr>
</tbody>
</table>
<p>We will only need some these assestions to test our current unit <img src='http://www.hotscripts.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Note that you could pass additional argument to all these methods which will be the message to be displayed in case the test fails e.g. $this-&gt;assertTrue(false, &#8216;Passing false to assertTrue faild!&#8217;).<br />
Don&#8217;t worry though, because the error messages generated by SimpleTest are very informative so no need to bother writing new messages.</p>
<p>Now, let&#8217;s proceed to the next test:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code> <strong>function</strong> testCreate()<br />
{<br />
$this-&gt;tearDown();<br />
$this-&gt;assertFalse(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
clearstatcache();</code></p>
<p>$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;create());<br />
$this-&gt;assertTrue(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
}</td>
</tr>
</tbody>
</table>
<p>This test will test the create() method and makes sure it&#8217;s creating the file!</p>
<p>We first delete the file created (automatically) by setUp() by using tearDown() and then check and insure that the file no longer exists by using assertFalse() which will pass only if file_exists() returned false (file does not exists).<br />
We then check to see if the method create() successfully created the file and returned true in the last two lines of the test.</p>
<p>Needless to say that it&#8217;s more reading friendly to make the test name similar or related to the method/part you are testing.</p>
<p>We&#8217;ll now see a new assertion type in the next test:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code> <strong>function</strong> testReadWrite()<br />
{<br />
$contents = 'contents';<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;putContents($contents));<br />
$this-&gt;assertEqual($this-&gt;<strong>file</strong>-&gt;getContents(), $contents);<br />
}</code></td>
</tr>
</tbody>
</table>
<p>This test will check the putContents() and getContents() methods.<br />
We will write some contents to the file using putContents() and make sure everything went ok and then use assertEqual() to make sure that what we&#8217;d written in the file is equal to what we get from getContents().</p>
<p>So you think I am paranoid when I check one part twice? It will be useless to just check for putContents() since it might pass the test but without actually doing what expected by just returning true or maybe because we had defined the method incorrectly! So we have to check the contents of this file and insure they are equal.<br />
This is why we wrote two tests to check file existence and creation as well.</p>
<p>Now, how many operations left to test? Two, right?<br />
Here is the test for the method append():</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code> <strong>function</strong> testAppend()<br />
{<br />
$this-&gt;<strong>file</strong>-&gt;putContents("SimpleTest");<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;append("NeverMind"));<br />
$this-&gt;assertWantedPattern('~nevermind$~i', $this-&gt;<strong>file</strong>-&gt;getContents());<br />
}</code></td>
</tr>
</tbody>
</table>
<p>Note that we didn&#8217;t test the method putContents() again since it was tested before (tests are performed in the order they had been written in).<br />
We use a new assertion method that is assertWantedPattern() which will try to match the regular expression pattern in the first argument against the second argument.<br />
We want to make sure that the word &#8220;NeverMind&#8221; is found at the end of the file so the $ sign in regexp will help us.</p>
<p>And finally, our last test:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code> <strong>function</strong> testDelete()<br />
{<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;delete());<br />
$this-&gt;assertFalse(<strong>file_exists</strong>($this-&gt;filename));<br />
}</code></td>
</tr>
</tbody>
</table>
<p>There is no new assertion type used here and what I want to test is clear, so I need not say anything here, do I? It&#8217;s pretty obvious <img src='http://www.hotscripts.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2 id="toc-running-the-test-case">Running The Test Case</h2>
<p>So now all our tests are ready. We then instantiate the test case by:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code>$test = <strong>new</strong> fileTest('test.txt');</code></td>
</tr>
</tbody>
</table>
<p>Now try running this script….<br />
Nothing appeared, right? Remember when we talked about the line $this-&gt;UnitTestCase(&#8216;File Manipulation Test&#8217;) and how it&#8217;s optional and it will only create a header in the reporter? Yes, We have to use the reporter to show how the tests went!</p>
<p>To use the reporter, we have to include the file <strong>reporter.php</strong> (at the top for convenience) so our file top should look like this:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code><strong>include_once</strong> 'simpletest/unit_tester.php';<br />
include_once 'simpletest/reporter.php';</code></p>
<p><strong>include_once</strong> &#8216;file.class.php&#8217;;</td>
</tr>
</tbody>
</table>
<p>and then create the reporter and run it by the test case object by adding this line at the end:</p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code>$test = <strong>new</strong> fileTest('test.txt');<br />
$test-&gt;run(new HtmlReporter());</code></td>
</tr>
</tbody>
</table>
<p>Finally, our test case script should be like this:<br />
<strong>[fileTest.php]</strong></p>
<table border="1" cellspacing="1" width="100%" bgcolor="#f5f5f5" bordercolor="#c0c0c0">
<tbody>
<tr>
<td><code>&lt;?php<br />
<strong>include_once</strong> 'simpletest/unit_tester.php';<br />
<strong>include_once</strong> 'simpletest/reporter.php';</code></p>
<p><strong>include_once</strong> &#8216;file.class.php&#8217;;</p>
<p><strong>class</strong> fileTest <strong>extends</strong> UnitTestCase<br />
{<br />
<strong>var</strong> $file;<br />
<strong>var</strong> $filename;</p>
<p><strong>function</strong> fileTest($filename)<br />
{<br />
$this-&gt;filename = $filename;<br />
$this-&gt;<strong>file</strong> = <strong>new</strong> <strong>file</strong>($this-&gt;filename);<br />
$this-&gt;UnitTestCase(&#8216;File Manipulation Test&#8217;);<br />
}</p>
<p><strong>function</strong> setUp()<br />
{<br />
$fp = @<strong>fopen</strong>($this-&gt;filename, &#8216;x&#8217;);<br />
<strong>if</strong> (!($fp === <strong>false</strong>)) {<br />
<strong>fwrite</strong>($fp, &#8221;);<br />
<strong>fclose</strong>($fp);<br />
}<br />
}</p>
<p><strong>function</strong> tearDown()<br />
{<br />
@unlink($this-&gt;filename);<br />
}</p>
<p><strong>function</strong> testFileExists()<br />
{<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;exists());<br />
clearstatcache();<br />
$this-&gt;assertTrue(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
}</p>
<p><strong>function</strong> testCreate()<br />
{<br />
$this-&gt;tearDown();<br />
$this-&gt;assertFalse(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
clearstatcache();</p>
<p>$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;create());<br />
$this-&gt;assertTrue(<strong>file_exists</strong>($this-&gt;<strong>file</strong>-&gt;filename));<br />
}</p>
<p><strong>function</strong> testReadWrite()<br />
{<br />
$contents = &#8216;contents&#8217;;<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;putContents($contents));<br />
$this-&gt;assertEqual($this-&gt;<strong>file</strong>-&gt;getContents(), $contents);<br />
}</p>
<p><strong>function</strong> testAppend()<br />
{<br />
$this-&gt;<strong>file</strong>-&gt;putContents(&#8220;SimpleTest&#8221;);<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;append(&#8220;NeverMind&#8221;));<br />
$this-&gt;assertWantedPattern(&#8216;~nevermind$~i&#8217;, $this-&gt;<strong>file</strong>-&gt;getContents());<br />
}</p>
<p><strong>function</strong> testDelete()<br />
{<br />
$this-&gt;assertTrue($this-&gt;<strong>file</strong>-&gt;delete());<br />
$this-&gt;assertFalse(<strong>file_exists</strong>($this-&gt;filename));<br />
}<br />
}<br />
$test = <strong>new</strong> fileTest(&#8216;test.txt&#8217;);<br />
$test-&gt;run(<strong>new</strong> HtmlReporter());<br />
?&gt;</td>
</tr>
</tbody>
</table>
<p>Now run the script again and if everything goes fine you should see something similar to this if all tests passed:</p>
<table border="1" cellspacing="1" width="100%" bordercolor="#f5f5f5">
<tbody>
<tr>
<td>
<h1 id="toc-file-manipulation-test">File Manipulation Test</h1>
<p>1/1 test cases complete: <strong>11</strong> passes, <strong>0</strong> fails and <strong>0</strong> exceptions.</td>
</tr>
</tbody>
</table>
<p>In case we had any failure, you will see something similar to:</p>
<table border="1" cellspacing="1" width="100%" bordercolor="#f5f5f5">
<tbody>
<tr>
<td>
<h1 id="toc-file-manipulation-test1">File Manipulation Test</h1>
<p>Fail: testAppend -&gt; Pattern [~^nevermind$~i] not detected in [String: SimpleTestNeverMind] at line [61]</p>
<p>1/1 test cases complete: <strong>10</strong> passes, <strong>1</strong> fails and <strong>0</strong> exceptions.</td>
</tr>
</tbody>
</table>
<p>As you can see, there was a failure in the method testAppend() and the error message has clearly stated what and where the error is.<br />
Note that this test failed because I edited the pattern and forced the contents of the file to be &#8220;NeverMind&#8221; only in order to pass (case-insensitive) which, of course, made the test fails.</p>
<p>In case you had any failures, the script will continue and will not terminate until all tests are performed.<br />
If any PHP errors occurred, such as warnings or notices, they will be caught and reported as exceptions.</p>
<h2 id="toc-conclusion">Conclusion</h2>
<p>Now after all this effort, you might ask: &#8220;Why bother writing all these tests?&#8221; I tell you it&#8217;s much better than debugging with nasty ways such as var_dump()&#8217;s and difficult investigations to find if there were any typos or null statments or whatever might be causing the problem. With unit testing, the test case will report were exactly is the problem.<br />
With unit testing, if you ever change your class implementation, all you have to do is run the test case and it will report if everything is functioning correctly or not and give details about any failures, if any.<br />
Another advantage is that you are separating the debugging code from the original code! No need to clean up after debugging or anything.</p>
<p>A final remark, SimpleTest has great potential and many other features like mock objects and web tester which could make your debugging process easier than ever! for example, the web tester can navigate your website, follow links, click buttons, submit forms and much more!<br />
In this article, we were demonstrating the most basic use of unit testing. It is just a kick off to infect you with the Test-infection <img src='http://www.hotscripts.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><br />
If you want to learn more about this great framework, read the docs at <a href="http://www.lastcraft.com/simple_test.php">LastCraft</a>.</p>
<div class="hotlist"><strong>Author: Saleh Jamal</strong></div>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/unittesting-using-simpletest/">UnitTesting in PHP using SimpleTest</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/php-error-log-file-archive/' rel='bookmark' title='Create Own PHP Error Log File Archive'>Create Own PHP Error Log File Archive</a></li>
<li><a href='http://www.hotscripts.com/blog/creating-an-image-with-phps-gd/' rel='bookmark' title='Creating an Image with PHP&#8217;s GD'>Creating an Image with PHP&#8217;s GD</a></li>
<li><a href='http://www.hotscripts.com/blog/track-your-visitors-using-php/' rel='bookmark' title='Track Your Visitors, Using PHP'>Track Your Visitors, Using PHP</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/unittesting-using-simpletest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create Own PHP Error Log File Archive</title>
		<link>http://www.hotscripts.com/blog/php-error-log-file-archive/</link>
		<comments>http://www.hotscripts.com/blog/php-error-log-file-archive/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 03:01:23 +0000</pubDate>
		<dc:creator>DEVpapers</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hotscripts.com/blog/?p=675</guid>
		<description><![CDATA[Create your own error logs for debugging PHP scripts and save them in a log file for archival.<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-error-log-file-archive/">Create Own PHP Error Log File Archive</a></p>

Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/creating-an-image-with-phps-gd/' rel='bookmark' title='Creating an Image with PHP&#8217;s GD'>Creating an Image with PHP&#8217;s GD</a></li>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/phps-header-function/' rel='bookmark' title='PHP&#8217;s Header Function'>PHP&#8217;s Header Function</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><span><span style="font-family: Verdana; ">Since most hosters don&#8217;t provide access to Apache error logs on shared hosting packages for technical reasons, you can create your own error logs for debugging PHP Scripts. (See the <strong>demo</strong> at <a href="http://programmabilities.com/error_log.php">http://programmabilities.com/error_log.php</a>.)</span></span></p>
<p>Insert the following code in your PHP script. (Or create separate file and add the code in it. Include the file using <span style="font-family: Courier New;">include()</span>.)</p>
<pre><span style="font-family: Verdana; ">/* we will do our own error handling. */
error_reporting(0); // Turns off all error reporting.

/* user defined error handling function. */
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
    // timestamp for the error entry.
    $dt = date('Y-m-d H:i:s (T)');

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING and E_USER_NOTICE.
    $errortype = array (
                E_ERROR =&gt; 'Error',
                E_WARNING =&gt; 'Warning',
                E_PARSE =&gt; 'Parsing Error',
                E_NOTICE =&gt; 'Notice',
                E_CORE_ERROR =&gt; 'Core Error',
                E_CORE_WARNING =&gt; 'Core Warning',
                E_COMPILE_ERROR =&gt; 'Compile Error',
                E_COMPILE_WARNING =&gt; 'Compile Warning',
                E_USER_ERROR =&gt; 'User Error',
                E_USER_WARNING =&gt; 'User Warning',
                E_USER_NOTICE =&gt; 'User Notice',
                E_STRICT =&gt; 'Runtime Notice'
                );
    // set of errors for which a var trace will be saved.
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err = "&lt;errorentry&gt;\n";
    $err .= "\t&lt;datetime&gt;" .$dt. "&lt;/datetime&gt;\n";
    $err .= "\t&lt;errornum&gt;" .$errno. "&lt;/errornum&gt;\n";
    $err .= "\t&lt;errortype&gt;" .$errortype[$errno]. "&lt;/errortype&gt;\n";
    $err .= "\t&lt;errormsg&gt;" .$errmsg. "&lt;/errormsg&gt;\n";
    $err .= "\t&lt;scriptname&gt;" .$filename. "&lt;/scriptname&gt;\n";
    $err .= "\t&lt;scriptlinenum&gt;" .$linenum. "&lt;/scriptlinenum&gt;\n";

    if (in_array($errno, $user_errors)) {
        $err .= "\t&lt;vartrace&gt;" .wddx_serialize_value($vars, 'Variables'). "&lt;/vartrace&gt;\n";
    }
    $err .= "&lt;/errorentry&gt;\n\n";

    // save to the error log file, and e-mail me if there is a critical user error.
    error_log($err, 3, '../error_log.log');
    if ($errno == E_USER_ERROR) {
        mail('bgates@gmail.com', 'Critical User Error', $err);
    }
}
$old_error_handler = set_error_handler('userErrorHandler');</span></pre>
<p><span style="font-family: Verdana; "><br />
PHP&#8217;s <span style="font-family: Courier New;"><a href="http://us3.php.net/manual/en/function.error-reporting.php" target="_blank">error_reporting()</a></span> function sets which PHP errors are reported. The <span style="font-family: Courier New;">error_reporting()</span> function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script. The script&#8217;s <span style="font-family: Courier New;">error_reporting(0)</span> turns off all error reporting so the script can catch and save the errors to a file.</span></p>
<p>PHP&#8217;s <span style="font-family: Courier New;"><a href="http://us3.php.net/manual/en/function.error-log.php" target="_blank">error_log()</a></span> function sends an error message somewhere. This script uses it to send the error message to a file (option <span style="font-family: Courier New;">3</span>).</p>
<p>Now you have your own error log archives file that you can link to and look at! (See the <strong>demo</strong> at <a href="http://programmabilities.com/error_log.php">http://programmabilities.com/error_log.php</a>.)</p>
<hr id="null" /><span style="font-family: Verdana; "><br />
Chief Programmabilities<br />
</span><a href="http://programmabilities.com/" target="_blank"><span style="font-family: Verdana; ">Programmabilities.com</span></a></p>
<p>Post from: <a href="http://www.hotscripts.com/blog">Hot Scripts Blog</a><br/><br/><a href="http://www.hotscripts.com/blog/php-error-log-file-archive/">Create Own PHP Error Log File Archive</a></p>
<p>Related posts:<ol>
<li><a href='http://www.hotscripts.com/blog/creating-an-image-with-phps-gd/' rel='bookmark' title='Creating an Image with PHP&#8217;s GD'>Creating an Image with PHP&#8217;s GD</a></li>
<li><a href='http://www.hotscripts.com/blog/mysql-database-handling-in-php/' rel='bookmark' title='MySQL Database Handling in PHP'>MySQL Database Handling in PHP</a></li>
<li><a href='http://www.hotscripts.com/blog/phps-header-function/' rel='bookmark' title='PHP&#8217;s Header Function'>PHP&#8217;s Header Function</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.hotscripts.com/blog/php-error-log-file-archive/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

