<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>PHP HTML CSS Tutorials</title>
	
	<link>http://php-html.net/tutorials</link>
	<description>Tutorials, Resources and Snippets</description>
	<lastBuildDate>Thu, 19 Jan 2012 15:51:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PhpHtmlCssTutorials" /><feedburner:info uri="phphtmlcsstutorials" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>HTML5 Local Storage – Complete Guide</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/ITqbmBpHztU/</link>
		<comments>http://php-html.net/tutorials/html5-local-storage-guide/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 10:15:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[local storage]]></category>
		<category><![CDATA[web storage]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=356</guid>
		<description><![CDATA[HTML5 is one of the most fashionable topics in today’s web programming world. HTML5 contains lots of new features that allege to change the web face, big players like Google and Apple are pushing for it and browsers competes to implement more and more html5 features. In this conditions there is no surprise that everyone [...]]]></description>
			<content:encoded><![CDATA[<p>HTML5 is one of the most fashionable topics in today’s web programming world. HTML5 contains lots of new features that allege to change the web face, big players like Google and Apple are pushing for it and browsers competes to implement more and more html5 features. In this conditions there is no surprise that everyone is talking about it.</p>
<p>In this post we are going to analyse exhaustively an HTML5 simple feature which is already implemented in all the modern browsers: local storage. Local Storage is just a part of the <a href="http://dev.w3.org/html5/webstorage/">Web Storage</a> api. It is already <a href="http://dev.w3.org/html5/webstorage/#the-localstorage-attribute">defined in the HTML5 specifications</a> and it&#8217;s implemented in all the modern browsers:<br />
<span id="more-356"></span></p>
<table>
<tr>
<td>IE</td>
<td>Firefox</td>
<td>Safari</td>
<td>Chrome</td>
<td>Opera</td>
<td>IPhone</td>
<td>Android</td>
</tr>
<tr>
<td><a href="http://msdn.microsoft.com/en-us/library/cc197062(v=VS.85).aspx">8+</a></td>
<td><a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">3.5</a></td>
<td><a href="">4.0+</a></td>
<td><a href="http://chrome.blogspot.com/2010/01/over-1500-new-features-for-google.html">4.0+</a></td>
<td><a href="">10.5+</a></td>
<td><a href="">2.0+</a></td>
<td><a href="">2.0+</a></td>
</tr>
</table>
<p><br/></p>
<p>Local Storage is intended to be used for storing and retrieving data in html pages from the same domain. The data can be retrieved from all the windows in the same domain even if the browser is restarted. The Session Storage is the other Web Storage option and the data is available only in the window it was stored in and is lost when the browser window is closed.</p>
<p>Local Storage along with Session Storage aims to be a replacement of the cookies, defining a more consistent API. There are a few differences from the cookies:<br />
- While the cookies are accessible from both client and server side, Web Storage in general and Local Storage in particular is accessible only from client side.<br />
- Enhanced capacity(official for cookies is 4 kbytes) to more than 5Mb per domain(Firefox, Google Chrome, and Opera and 10MB in IE).</p>
<p>The local storage is a simple javascript api that you can use inside html5 pages if it&#8217;s supported by the browser. The Local Storage implements the same interface that can be used for Session Storage as well. Here is the interface as it is defined by :</p>
<pre name="code" class="js">
interface Storage {
  readonly attribute unsigned long length;
  getter DOMString key(in unsigned long index);
  getter any getItem(in DOMString key);
  setter creator void setItem(in DOMString key, in any value);
  deleter void removeItem(in DOMString key);
  void clear();
};
</pre>
<h2>Testing if the browser supports Local Storage</h2>
<p>When you intend to use Local Storage you have to take in consideration that it is not supported by all the browsers. If the correct run of your application depends on the local storage functionality you have find other features to rely if it&#8217;s not supported, or to inform the user that the application doesn&#8217;t run properly on his browser. In order to check if it&#8217;s supported you have to check if the localStorage instance exists.</p>
<pre name="code" class="js">
	function testSupport()
	{
		if (localStorage)
			return "Local Storage: Supported";
		else
			return "Local Storage: Unsupported";
	}
</pre>
<h2>How to Store a Value</h2>
<p>Storing values is very simple, all you have to do is to invoke the setItem method, providing a key and a value, or to use use the localStorage object as an associative array: </p>
<pre name="code" class="js">
	localStorage.setItem("key1", "value1");
	localStorage["key1"] = "value1";
</pre>
<h2>How to Retrieve a Value</h2>
<p>Retrieving stored values is as simple as possible:</p>
<pre name="code" class="js">
	alert(localStorage.getItem("key1"));
	alert(localStorage["key1"]);
</pre>
<h2>List all stored values</h2>
<p>If you need to check all the values stored in local storage you can iterate through the keys, listing the values accordingly.</p>
<pre name="code" class="js">
function listAllItems(){
	for (i=0; i<=localStorage.length-1; i++)
	{
		key = localStorage.key(i);
		val = localStorage.getItem(key);
	}
}
</pre>
<h2>Remove a Value</h2>
<p>Compared to cookies, html5 local storage has a much bigger capacity. However, it doesn't mean it's unlimited. If you application uses intensively the local storage, you have to take care to remove the objects you don't need anymore.</p>
<pre name="code" class="js">
    void removeItem("key1");
</pre>
<h2>Clear all the values</h2>
<p>When the web application is "closed" or "started" you can clean all the stored values:</p>
<pre name="code" class="js">
	localStorage.clear();
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/html5-local-storage-guide/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/html5-local-storage-guide/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/ITqbmBpHztU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/html5-local-storage-guide/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/html5-local-storage-guide/</feedburner:origLink></item>
		<item>
		<title>How to write a simple scraper in PHP without Regex</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/Jad0XT0O1H4/</link>
		<comments>http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/#comments</comments>
		<pubDate>Tue, 15 Jun 2010 14:19:41 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[Util]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[scraper]]></category>
		<category><![CDATA[scrapper]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=330</guid>
		<description><![CDATA[Web scrappers are simple programs that are used to extract certain data from the web. Usually the structure of the the pages is known so scrappers have reduced complexity compared to parsers and crawlers. In this tutorial we are going to create a simple parser that extract the title and favicon from any html page. [...]]]></description>
			<content:encoded><![CDATA[<p>Web scrappers are simple programs that are used to extract certain data from the web. Usually the structure of the the pages is known so scrappers have reduced complexity compared to parsers and crawlers.</p>
<p>In this tutorial we are going to create a simple parser that extract the title and favicon from any html page.</p>
<p>Usually scrappers are based on regular expressions but we are going to avoid them because they are difficult to manage and sometimes they have unexpected results. We are going to use simple php string functions instead.<br />
<span id="more-330"></span><br />
Let&#8217;s assume all the pages we are scrapping have the following structure. </p>
<pre name="code" class="html">
&lt;html&gt;
&lt;title&gt;Page Tile | Site Name&lt;/title&gt;
&lt;link rel=&quot;shortcut icon&quot; href=&quot;http://www.site.com/favicon.ico&quot;/&gt;
...
&lt;body&gt;
...
&lt;h1&gt;Title&lt;/h1&gt;
...
&lt;/body&gt;

&lt;/html&gt;
</pre>
<p>We are going to retrieve the title and the favicon from the meta section and if the title is not populated we are going to search for the title inside the body. Those operations can be covered using only 2 simple functions:</p>
<pre name="code" class="php">
function strInBetween($text,
                               $separatorStart,
                               $separatorEnd,
                               &#038;$positionOut = null,
                               $after = null,
                               $afterIndex = 0)
{
	$CYCLE_LIMIT = 500;

	$stop = false;
	$pos = 0;
	$current = strInBetween($text, $separatorStart, $separatorEnd, $pos);
	$matching = strpos($current, $containing);
	$i = 0;
	$afterIndex = 0;
	while ($pos >= 0 &#038;&#038; $matching === false &#038;&#038; $i < $CYCLE_LIMIT)
	{
		$afterIndex += $pos + strlen($current);
		$current = strInBetween($text, $separatorStart, $separatorEnd, $pos, null, $afterIndex);
		$matching = strpos($current, $containing);
		$i++;
	}

	if ($matching)
		return $current;
	else
		return null;
}
</pre>
<p>This previous function returns the first substring found inside the input $text, surrounded by 2 string delimiters:  $separatorStart and $separatorEnd. Optionally, another substring or index could be specified to start the search only after it:
<ul>
<li>$text - the text where to search the substring</li>
<li>$separatorStart - the string delimiter in the left</li>
<li>$separatorEnd - the string delimiter in the right</li>
<li>&#038;$positionOut - optional output parameter, contains the position where the string is.</li>
<li>$after - optional parameter, is specified, the result is searched only after $after is encountered</li>
<li>$afterIndex - optional parameter used if $after is null. It indicates the index where the search should start.</li>
</ul>
<pre name="code" class="php">
function strInBetweenContaining($text,
                               $separatorStart,
                               $containing,
                               $separatorEnd,
                               &#038;$pos = null,
                               $after = null,
                               $afterIndex = 0)
{
    if ($after != null)
	{
        $pos = strpos($text, $after);
		if ($pos !== false)
			$afterIndex = $pos;
	}

	$start = -1;
	$pos = strpos($text, $separatorStart, $afterIndex);
	if ($pos !== false)
		$start = $pos;

	$end = -1;
	$pos = strpos($text, $separatorEnd, $start + strlen($separatorStart));
	if ($pos !== false)
		$end = $pos;

	if ($start < 0 &#038;&#038; $end < 0)
	{
		if ($positionOut != null)
			$positionOut = -1;

		return null;
	}
	else
	{
		if ($positionOut != null)
			$positionOut = -1;

		return substr($text, $start + strlen($separatorStart), $end - ($start + strlen($separatorStart)));
	}
}
</pre>
<p>strInBetweenContaining is based on the first function, and returns the string as mentioned in previous function only if it contains the specified string.</p>
<p>Here is the scraping section:</p>
<pre name="code" class="php">
require_once('util/getpage.php');
require_once('util/stringutils.php');

$url = $_GET['u'];
$page = getpage($url);

function getTitle($page) { return strInBetween($page, '&lt;title&gt;', '&lt;/title&gt;'); }
function getH1($page) { return strInBetween($page, '&lt;h1', '&lt;/h1&gt;'); }
function getLink($page)
{
	$block = strInBetweenContaining($page, '&lt;link', 'rel="shortcut icon"', '/>');
	return strInBetween($block, 'href="', '"');
}

echo getTitle($page) . '&lt;br&gt;';
echo strip_tags('&lt;h1' . getH1($page)) . '&lt;br&gt;';

$favicon = getLink($page);
if ($favicon == null)
	$favicon = $url . 'favicon.ico';

//echo $favicon;
echo "&lt;img src='$favicon' /&gt;";
</pre>
<p>The code is pretty much self-explanatory. The title and the first h1 tag is extracted, then the favico. If no favico is found the code returns the default one(according to the convention it should be the "favicon.ico" in the server root).</p>
<p>This example demonstrate how to retrieve a couple of simple values using a simple algorithm. It can be reused and extended to scrap any data from webpages. A regular expression parser would be a more flexible solution but it requires a good regex knowledge.</p>
<p>If you have question, requests or new ideas just use the comments section to submit them.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/Jad0XT0O1H4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/how-to-write-a-simple-scrapper-in-php-without-regex/</feedburner:origLink></item>
		<item>
		<title>Creating a Simple PHP Cache Script</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/jmL-6-b0314/</link>
		<comments>http://php-html.net/tutorials/creating-a-simple-php-cache-script/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 09:42:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[api]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[Util]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[cache mechanism]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=287</guid>
		<description><![CDATA[Caching is a simple method based on storing computed resources that are time consuming or cpu consuming to obtain for a later use. In this tutorial we'll cover the creation of a simple script that stores simple string resources in files. It is very simple, 100% functional and it can be fitted very well, but not only for web crawlers and spiders.]]></description>
			<content:encoded><![CDATA[<p>Cache is a programming concept that can be used in a various range of applications and for various purposes. A cache library can be used for storing database queries for later use, to store rendered pages to be served again without generating them again, or to save indexed pages in a crawler application to be processed by multiple modules.</p>
<ul>A cache mechanism is more simple that it might sound. It&#8217;s just a simple module that should implement 2 actions:
<li>to store a value(identified by a key).</li>
<li>to retrieve a value if it&#8217;s not expired.</li>
<li>additionally it can offer a mechanism to invalidate a set of values or the entire cache.</li>
</ul>
<p>In this tutorial we are going to create a disk cache script. It stores the string values in files, each value is stored in a file and it contains an additional file to store the expiration date. Performance wise, this is not the best approach, but the script is designed like that with a clear purpose: the additional file can be used to store additional attributes, beside the expiration date. Imagine an application that crawls pages, with different modules. Each time a module crawls the page, it adds it&#8217;s result to the additional file.<br />
<span id="more-287"></span><br />
The cache library in our tutorial is based only on a few functions grouped in a single class. Let&#8217;s start with the skeleton of the SimpleCache class:</p>
<pre name="code" class="php">
class SimpleCache
{
	public function exists($key)
	{
	}

	public function get($key)
	{
	}

	public function put($key, $content)
	{
	}
}
</pre>
<p>Once we have the skeleton class, we create a test class:</p>
<pre name="code" class="php">
// SimpleCacheTest.php - file to test the class
require_once "SimpleCache.php";

// instantiate the class
$cache = new SimpleCache();

// cache a value
$cache->put('key', 'this value');

// retrieved the cached value by key
$val = $cache->get('key');

// assert the retrieved value
if ($val != 'this value')
     echo 'Something went wrong!';
else
     echo 'Value as expected. Cache Test Passed';
</pre>
<ul>
In the next step we add variables to the class, for configuration:</p>
<li>the location where the cache files are stored. The location can be an absolute one or relative to the starting point of the script(in the code above is the cache subdirectory, located in the same directory where index.php is invoked from).
</li>
<li>the expiry interval in which the cache values expire.</li>
</ul>
<pre name="code" class="php">
class SimpleCache
{
	private $cacheDir = 'cache';
	private $expiryInterval = 2592000; //30*24*60*60;

	public function setCacheDir($val) {  $this->cacheDir = $val; }
	public function setExpiryInterval($val) {  $this->expiryInterval = $val; }
	...
}
</pre>
<p>Then we implement the put function. The code is very simple: we create the path if it doesn&#8217;t exist, then we we write the data in the main cache file and the expiration interval in the additional file:</p>
<pre name="code" class="php">
	public function put($key, $content)
	{
		$time = time(); //Current Time

		if (! file_exists($this->cacheDir))
			mkdir($this->cacheDir);

		$filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename
		$filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info

		file_put_contents ($filename_cache ,  $content); // save the content
		file_put_contents ($filename_info , $time); // save the time of last cache update
	}
</pre>
<p>The method to retrieve the code is pretty simple. We try to read the expiry time from the additional file. If it exists and the data is not expired we read the content of the cache file and return it:</p>
<pre name="code" class="php">
	public function get($key)
	{
		$filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename
		$filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info

		if (file_exists($filename_cache) &#038;&#038; file_exists($filename_info))
		{
			$cache_time = file_get_contents ($filename_info) + (int)$this->expiryInterval; //Last update time of the cache file
			$time = time(); //Current Time

			$expiry_time = (int)$time; //Expiry time for the cache

			if ((int)$cache_time >= (int)$expiry_time) //Compare last updated and current time
			{
				return file_get_contents ($filename_cache);   //Get contents from file
			}
		}

		return null;
	}
</pre>
<p>We create an additional function to check the existence of valid data in cache, similar to get function, in case we need to check it without reading it:</p>
<pre name="code" class="php">
	public function exists($key)
	{
		$filename_cache = $this->cacheDir . '/' . $key . '.cache'; //Cache filename
		$filename_info = $this->cacheDir . '/' . $key . '.info'; //Cache info

		if (file_exists($filename_cache) &#038;&#038; file_exists($filename_info))
		{
			$cache_time = file_get_contents ($filename_info) + (int)$this->expiryInterval; //Last update time of the cache file
			$time = time(); //Current Time

			$expiry_time = (int)$time; //Expiry time for the cache

			if ((int)$cache_time >= (int)$expiry_time) //Compare last updated and current time
			{
				return true;
			}
		}

		return false;
	}
</pre>
<p>Now that the code was written it can be testes using the test file. In a next tutorial we are going to rewrite this cache mechanism using the file modify date time instead of the additional time.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/creating-a-simple-php-cache-script/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/creating-a-simple-php-cache-script/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/jmL-6-b0314" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/creating-a-simple-php-cache-script/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/creating-a-simple-php-cache-script/</feedburner:origLink></item>
		<item>
		<title>Php Class to Retrieve Alexa Rank</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/Zq26kUcNsEg/</link>
		<comments>http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 22:46:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[api]]></category>
		<category><![CDATA[parsing]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=298</guid>
		<description><![CDATA[Alexa is a service acquired by Amazon which offers a web traffic report for websites. They retrieve the data from toolbar that can be installed in different browsers, centralize the data and display reports to anyone. The most important indicator is the Alexa Rank. It represents the rank of a webpage in a list of [...]]]></description>
			<content:encoded><![CDATA[<p>Alexa is a service acquired by Amazon which offers a web traffic report for websites. They retrieve the data from toolbar that can be installed in different browsers, centralize the data and display reports to anyone. The most important indicator is the Alexa Rank. It represents the rank of a webpage in a list of all the websites. It&#8217;s not the 100% accurate but it gives a good indication.</p>
<p>Alexa does not offer any free API to obtain Alexa Rank. However there is a simple method to obtain it in the same way the Alexa Toolbar does. All you have to do is to invoke the following url(replacing php-html.net with your domain): http://data.alexa.com/data?cli=10&#038;dat=s&#038;url=php-html.net<br />
<span id="more-298"></span><br />
The response should look like this one:</p>
<pre name="code" class="html">
<ALEXA VER="0.9" URL="php-html.net/" HOME="0" AID="=">
<SD TITLE="A" FLAGS="" HOST="php-html.net">
<LINKSIN NUM="20"/>
</SD>
<SD>
<POPULARITY URL="php-html.net/" TEXT="785463"/>
<REACH RANK="768874"/>
<RANK DELTA="-941784"/>
</SD>
</ALEXA>
</pre>
<p>All we have to do is to take the response and extract the Alexa Rank from it. There are various options, we are just going to use a simple regular expression:</p>
<pre name="code" class="php">
class AlexaRank
{
	public function getRequestUri($domain)
	{
		return 'http://data.alexa.com/data?cli=10&#038;dat=s&#038;url=' . $domain;
	}

	public function parse( $httpResponse )
	{
		preg_match( '#<POPULARITY URL="(.*?)" TEXT="([0-9]+){1,}"/>#si', $httpResponse, $p );
		$res = ( $p[2] ) ? number_format( intval($p[2]) ):0;

		return str_replace(',', '', $res);
	}
}
</pre>
<p>Then we can simply get the alexa rank:</p>
<pre name="code" class="php">
echo $extractor->parse(file_get_contents($extractor->getRequestUri('php-html.net')));
</pre>
<p>The extractor class contains the 2 functions one to build the url to be invoked for a domain and the second one to parse the response. This solution was chosen offer the option to use an external function that retrieve the response content. This is because for some hosting servers the file_get_contents does not work, for other curl does not work&#8230;</p>
<p>Remember the &#8220;use it but not abuse it&#8221; concept. Alexa didn&#8217;t expose this through a public api for some reason. If you use this function zillions times a day you will probably be detected and have the ip banned.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/Zq26kUcNsEg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/php-class-to-retrieve-alexa-rank/</feedburner:origLink></item>
		<item>
		<title>Model View Controller(MVC) in PHP</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/Fv_dljHC8e8/</link>
		<comments>http://php-html.net/tutorials/model-view-controller-in-php/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 08:38:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Model View Controller]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=182</guid>
		<description><![CDATA[The model view controller pattern is the most used pattern for today&#8217;s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern. Despite the fact that the MVC pattern is [...]]]></description>
			<content:encoded><![CDATA[<p>The model view controller pattern is the most used pattern for today&#8217;s world web applications. It has been used for the first time in Smalltalk and then adopted and popularized by Java. At present there are more than a dozen PHP web frameworks based on MVC pattern. </p>
<p>Despite the fact that the MVC pattern is very popular in PHP, is hard to find a proper tutorial accompanied by a simple source code example. That is the purpose of this tutorial.<br />
<span id="more-182"></span></p>
<ul>
The MVC pattern separates an application in 3 modules: Model, View and Controller:</p>
<li>The <strong>model </strong>is responsible to manage the data; it stores and retrieves entities used by an application, usually from a database, and contains the logic implemented by the application. </li>
<li>The <strong>view (presentation)</strong> is responsible to display the data provided by the model in a specific format. It has a similar usage with the template modules present in some popular web applications, like wordpress, joomla, &#8230;</li>
<li>The <strong>controller </strong>handles the model and view layers to work together. The controller receives a request from the client, invoke the model to perform the requested operations and send the data to the View. The view format the data to be presented to the user, in a web application as an html output.  </li>
</ul>
<p>The above figure contains the MVC Collaboration Diagram, where the links and dependencies between figures can be observed:<br />
<img src="http://php-html.net/tutorials/wp-content/uploads/2009/08/mvc-collaboration.png" alt="mvc-collaboration" title="mvc-collaboration" width="500" height="178" class="aligncenter size-full wp-image-183" style="padding:20px;" /></p>
<p>Our short php example has a simple structure, putting each MVC module in one folder:<br />
<img src="http://php-html.net/tutorials/wp-content/uploads/2009/08/mvc-structure.png" alt="mvc-structure" title="mvc-structure" width="202" height="163" class="alignnone size-full wp-image-227" style="padding:20px;" /></p>
<h3>Controller</h3>
<p>The controller is the first thing which takes a request, parse it, initialize and invoke the model and takes the model response and send it to the presentation layer. It&#8217;s practically the liant between the Model and the View, a small framework where Model and View are plugged in. In our naive php implementation the controller is implemented by only one class, named unexpectedly controller. The application entry point will be index.php. The index php file will delegate all the requests to the controller:</p>
<pre name="code" class="php">
	// index.php file
	include_once("controller/Controller.php");

	$controller = new Controller();
	$controller->invoke();
</pre>
<p>Our Controller class has only one function and the constructor. The constructor instantiate a model class and when a request is done, the controller decide which data is required from the model. Then it calls the model class to retrieve the data. After that it calls the corresponding passing the data coming from the model. The code is extremely simple. Note that the controller does not know anything about the database or about how the page is generated. </p>
<pre name="code" class="php">
include_once("model/Model.php");

class Controller {
     public $model;	

     public function __construct()
     {
          $this->model = new Model();
     } 

     public function invoke()
     {
          if (!isset($_GET['book']))
          {
               // no special book is requested, we'll show a list of all available books
               $books = $this->model->getBookList();
               include 'view/booklist.php';
          }
          else
          {
               // show the requested book
               $book = $this->model->getBook($_GET['book']);
               include 'view/viewbook.php';
          }
     }
}
</pre>
<p>In the following MVC Sequence Diagram it can be observed the flow during a http request:<br />
<img src="http://php-html.net/tutorials/wp-content/uploads/2009/08/mvc-sequence1.png" alt="mvc-sequence1" title="mvc-sequence1" width="463" height="284" style="padding-left:20px;" /></p>
<h3>Model and Entity Classes</h3>
<ul>
The Model represents the data and the logic of an application, what many calls business logic. Usually, it&#8217;s responsible for:</p>
<li>storing, deleting, updating the application data. Generally it includes the database operations, but implementing the same operations invoking external web services or APIs is not an unusual at all.</li>
<li>encapsulating the application logic. This is the layer that should implement all the logic of the application. The most common mistakes are to implement application logic operations inside the controller or the view(presentation) layer.</li>
</ul>
<p>In our example the model is represented by 2 classes: the &#8220;Model&#8221; class and a &#8220;Book&#8221; class. The model doesn&#8217;t need any other presentation. The &#8220;Book&#8221; class is an entity class. This class should be exposed to the View layer and represents the format exported by the Model view. In a good implementation of the MVC pattern only entity classes should be exposed by the model and they should not encapsulate any business logic. Their solely purpose is to keep data. Depending on implementation Entity objects can be replaced by xml or json chunk of data. In the above snippet you can notice how Model is returning a specific book, or a list of all available books:</p>
<pre name="code" class="php">
include_once("model/Book.php");

class Model {
	public function getBookList()
	{
		// here goes some hardcoded values to simulate the database
		return array(
			"Jungle Book" => new Book("Jungle Book", "R. Kipling", "A classic book."),
			"Moonwalker" => new Book("Moonwalker", "J. Walker", ""),
			"PHP for Dummies" => new Book("PHP for Dummies", "Some Smart Guy", "")
		);
	}

	public function getBook($title)
	{
		// we use the previous function to get all the books and then we return the requested one.
		// in a real life scenario this will be done through a db select command
		$allBooks = $this->getBookList();
		return $allBooks[$title];
	}

}
</pre>
<p>In our example the model layer includes the Book class. In a real scenario, the model will include all the entities and the classes to persist data into the database, and the classes encapsulating the business logic.</p>
<pre name="code" class="php">
class Book {
	public $title;
	public $author;
	public $description;

	public function __construct($title, $author, $description)
    {
        $this->title = $title;
	    $this->author = $author;
	    $this->description = $description;
    }
}
</pre>
<h3>View (Presentation)</h3>
<p>The view(presentation layer)is responsible for formating the data received from the model in a form accessible to the user. The data can come in different formats from the model: simple objects( sometimes called Value Objects), xml structures, json, &#8230;</p>
<p>The view should not be confused to the template mechanism sometimes they work in the same manner  and address similar issues. Both will reduce the dependency of the presentation layer of from rest of the system and separates the presentation elements(html) from the code. The controller delegate the data from the model to a specific view element, usually associated to the main entity in the model. For example the operation &#8220;display account&#8221; will be associated to a &#8220;display account&#8221; view. The view layer can use a template system to render the html pages. The template mechanism can reuse specific parts of the page: header, menus, footer, lists and tables, &#8230;. Speaking in the context of the MVC pattern</p>
<p>In our example the view contains only 2 files one for displaying one book and the other one for displaying a list of books.</p>
<p><strong>viewbook.php</strong></p>
<pre name="code" class="html">
&lt;html&gt;
&lt;head&gt;&lt;/head&gt;

&lt;body&gt;

	&lt;?php 

		echo 'Title:' . $book-&gt;title . '&lt;br/&gt;';
		echo 'Author:' . $book-&gt;author . '&lt;br/&gt;';
		echo 'Description:' . $book-&gt;description . '&lt;br/&gt;';

	?&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>booklist.php</strong></p>
<pre name="code" class="html">
&lt;html&gt;
&lt;head&gt;&lt;/head&gt;

&lt;body&gt;

	&lt;table&gt;
		&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;Title&lt;/td&gt;&lt;td&gt;Author&lt;/td&gt;&lt;td&gt;Description&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;
		&lt;?php 

			foreach ($books as $title =&gt; $book)
			{
				echo '&lt;tr&gt;&lt;td&gt;&lt;a href=&quot;index.php?book='.$book-&gt;title.'&quot;&gt;'.$book-&gt;title.'&lt;/a&gt;&lt;/td&gt;&lt;td&gt;'.$book-&gt;author.'&lt;/td&gt;&lt;td&gt;'.$book-&gt;description.'&lt;/td&gt;&lt;/tr&gt;';
			}

		?&gt;
	&lt;/table&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The above example is a simplified implementation in PHP. Most of the PHP web frameworks based on MVC have similar implementations, in a much better shape. However, the possibility of MVC pattern are endless. For example different layers can be implemented in different languages or distributed on different machines. AJAX applications can implements the View layer directly in Javascript in the browser, invoking JSON services. The controller can be partially implemented on client, partially on server&#8230;</p>
<ul>
This post should not be ended before enumerating the advantages of Model View Controller pattern:</p>
<li>the Model and View are separated, making the application more flexible.</li>
<li>the Model and view can be changed separately, or replaced. For example a web application can be transformed in a smart client application just by writing a new View module, or an application can use web services in the backend instead of a database, just replacing the model module.</li>
<li>each module can be tested and debugged separately.  </li>
</ul>
<p>The files are available for download as a zip from <a href="http://sourceforge.net/projects/mvc-php/files/mvc.zip/download" rel="nofollow">http://sourceforge.net/projects/mvc-php/files/mvc.zip/download</a><br />
<br/></p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/model-view-controller-in-php/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/model-view-controller-in-php/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/Fv_dljHC8e8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/model-view-controller-in-php/feed/</wfw:commentRss>
		<slash:comments>80</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/model-view-controller-in-php/</feedburner:origLink></item>
		<item>
		<title>How to handle URLs in PHP</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/TaM_Er4nPyg/</link>
		<comments>http://php-html.net/tutorials/how-to-handle-urls-in-php/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 23:15:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[scrapping]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[url]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=166</guid>
		<description><![CDATA[URL handling is one of the tasks you have to do from time to time in PHP. Sometimes you have to do it because you want to record the referral sites, other times because you want to write your own spider or just because you want to retrieve your current URL. PHP is a language [...]]]></description>
			<content:encoded><![CDATA[<p>URL handling is one of the tasks you have to do from time to time in PHP. Sometimes you have to do it because you want to record the referral sites, other times because you want to write your own spider or just because you want to retrieve your current URL.</p>
<p>PHP is a language developed around web for web developers and it contains all the functions you might need in your quests. There is a section in php documentation which groups the <a href="http://www.php.net/manual/en/ref.url.php">URL functions</a>. Along with a few functions used to encode/decode which are rarely used the package contains the functions you can not live without:<br />
<span id="more-166"></span></p>
<h2>parse_url</h2>
<p><a href="http://www.php.net/manual/en/function.parse-url.php">parse_url</a> &#8211; a function that parses a URL and returns an associative array containing all the various components of the URL that are present.</p>
<p>A complete link that is parsed by parse-url should be in the following form: </p>
<pre name="code" class="php">
scheme://username:password@host:port/path/?query#fragment
</pre>
<p>For example the following code:</p>
<pre name="code" class="php">
parse_url('http://username:password@php-html.net:80/tutorials/?arg=value#anchor');
</pre>
<p>will return the following array:</p>
<pre name="code" class="php">
Array
(
    [scheme] => http
    [host] => php-html.net
    [user] => username
    [pass] => password
    [path] => /tutorials
    [port] => /80
    [query] => arg=value
    [fragment] => anchor
)
</pre>
<p>You can provide a second parameter in the function to retrieve only one of the values, as a string. The  possible parameters are: PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY  or PHP_URL_FRAGMENT:</p>
<pre name="code" class="php">
echo parse_url('http://php-html.net/tutorials/', PHP_URL_HOST); // prints php-html.net
echo parse_url('http://php-html.net/tutorials/', PHP_URL_PATH); // prints /tutorials
...
</pre>
<p>You have to keep in mind that:<br />
- This function does not work with relative urls.<br />
- It should not be used for url validation, it only parses urls and splits them in components.<br />
- It works fine on partial urls</p>
<h2>http_build_query</h2>
<p><a href="http://www.php.net/manual/en/function.http-build-query.php">http_build_query</a> &#8211; is a complementary function that builds an url query string based on an associative (or indexed) array:</p>
<pre name="code" class="php">
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data); // foo=bar&#038;baz=boom&#038;cow=milk&#038;php=hypertext+processor
echo http_build_query($data, '', '&amp;'); // foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor
</pre>
<h2>Encoding/Decoding urls</h2>
<h4>Base64 encoding</h4>
<p>The base 64 encoding transforms a string to another string that can be transmitted through transport layers that are not 8-bit clean, such as mail bodies. Basically it means that a string is transformed in another string that uses a limited set of characters(ASCII). The functions base64_encode / base64_decode can be used to encode and decode any string:</p>
<pre name="code" class="php">
$str = 'This is an encoded string';
echo base64_encode($str); // will print VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
echo base64_decode(base64_encode($str)); // will print This is an encoded string
</pre>
<h4>url encoding / url decoding</h4>
<p>There are 2 types of encoding / decoding functions designed especially for urls, with the intent to make them usable in a query part of a URL, as a convenient way to pass variables to the next page. There is a slight difference between them:</p>
<p><a href="http://www.php.net/manual/en/function.urlencode.php">urlencode</a> / <a href="http://www.php.net/manual/en/function.urldecode.php">urldecode</a> &#8211; encodes a string replacing all non-alphanumeric characters except -_.  with a percent (%) sign followed by the 2 hex digits representation. The spaces are encoded as (+) signs. It encodes strings in the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type.<br />
<a href="http://www.php.net/manual/en/function.rawurlencode.php">rawurlencode</a> / <a href="http://www.php.net/manual/en/function.rawurldecode.php">rawurldecode</a> &#8211; It does the same job as the above function, except that it replace the spaces with percent sign followed by the hex representation: %20. This function implements the standard <a href="http://www.faqs.org/rfcs/rfc1738">RFC 1738</a>.</p>
<h2>Getting the Current URL</h2>
<p>There are many cases when you have to retrieve the current url for different reasons. Unfortunately php does not implement a function dedicated to this scenario, but such a function can be easily written to build the current url string from the server variables.</p>
<pre name="code" class="php">
function current_url() {
    $isHTTPS = ( isset($_SERVER["HTTPS"]) &#038;&#038; $_SERVER["HTTPS"] == "on" );
    $isPort = ( isset($_SERVER["SERVER_PORT"]) &#038;&#038; ((!$isHTTPS &#038;&#038; $_SERVER["SERVER_PORT"] != "80")
                 || ($isHTTPS &#038;&#038; $_SERVER["SERVER_PORT"] != "443")));

    $port = ( $isPort ) ? ( ':'.$_SERVER["SERVER_PORT"] ) : '';

    //On some setups like nginx and php-fastcgi, REQUEST_URI include the query string
    if ( ($pos = strpos($_SERVER['REQUEST_URI'], '?')) === false )
    {
        // REQUEST_URI include the query string, it should be appended:

        $isQuery = ( isset($_SERVER["QUERY_STRING"]) &#038;&#038; $_SERVER["QUERY_STRING"] != '');
        $query = ( $isQuery ) ? ( '?'.$_SERVER["QUERY_STRING"] ) : '';

        $url = ( $isHTTPS ? 'https://' : 'http://')
                    .$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"].$query;
    }
    else
    {
        // the query string is already included in $_SERVER["REQUEST_URI"], no need to append it
        $url = ( $isHTTPS ? 'https://' : 'http://')
                    .$_SERVER["SERVER_NAME"].$port.$_SERVER["REQUEST_URI"];
    }

    return $url;
}
</pre>
<p>The function don&#8217;t need further explanations. It uses the $_SERVER variables to construct the url and checks if a port other that the default one is used and if the page is secure or not. The snippet was improved thanks to the comments from Joseph and <a href="http://herdian.ferdianto.com/">ferdhie</a>. </p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/how-to-handle-urls-in-php/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/how-to-handle-urls-in-php/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/TaM_Er4nPyg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/how-to-handle-urls-in-php/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/how-to-handle-urls-in-php/</feedburner:origLink></item>
		<item>
		<title>How to Write a PHP Script to Run Shell Commands from Browser</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/MgJwoHxI0kg/</link>
		<comments>http://php-html.net/tutorials/how-to-write-a-php-script-to-run-shell-commands-from-browser/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 18:44:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=130</guid>
		<description><![CDATA[It happens pretty often for me to have to run shell commands in a hosting environment. I do it all the time via a simple php script. I tested it on godaddy and dreamhost and on other hostings environments and it works fine. Before starting the tutorial you should note that if this script is [...]]]></description>
			<content:encoded><![CDATA[<p>It happens pretty often for me to have to run shell commands in a hosting environment. I do it all the time via a simple php script. I tested it on godaddy and dreamhost and on other hostings environments and it works fine.</p>
<p>Before starting the tutorial you should note that if this script is not handled carefully it can have undesired results. A wrong rm command can delete all the files you have on your hosting, so run the commands with care.<br />
<span id="more-130"></span></p>
<h3>Running Shell Commands from PHP</h3>
<p>In the first part of this tutorial we are going to see how we can run a shell command from php and how to retrieve the command ouput. The php function which is responsible to run a shell command is <a href="http://www.php.net/manual/en/function.proc-open.php">proc_open</a>.</p>
<p>The proc_open function accepts a couple of parameters:</p>
<pre name="code" class="php">
resource proc_open ( string $cmd
                           , array $descriptorspec
                           , array &#038;$pipes
                         [, string $cwd
                         [, array $env
                         [, array $other_options ]]] )
</pre>
<p>We are going to use the first 3 parameters:</p>
<ul>
<li><i>cmd</i> &#8211; the command to execute. The command string will contain the full command as we would write in the shell command line, including the input parameters.</li>
<li><i>descriptorspec</i> &#8211; is an indexed array containing the description of the pipes. The first element should contain the input pipe, the second one should contain the output pipe and the third one the stderr(the pipe where the command will return the error it encounter). Each one can be one of the types &#8220;pipe&#8221; of &#8220;file&#8221;</li>
<li><i>pipes</i> &#8211; is another indexed array that contains the reference to the pipes that are created during process. For example if in the descriptorsspec is specified a pipe for the input, the pipe array will contain the input pipe, which can be used to write to the input stream. The same can happen with the output stream: a pipe can be used to take the output of the command.
<p>If a pipe is not used, a file can be used instead. Usually temporary files are used. In our example we are going to use a pipe for the input and tmp files for the output and for the stderr. Because we don&#8217;t need to pass any input file to the command we are going to close the input pipe immediately, without writing anything in it.</li>
</ul>
<p>The proc_open function will be run slightly different on windows and linux environments. Windows processes don&#8217;t return a stderr, so it can not be used to test the success of a command on and windows environment.  </p>
<p>Here is the function we are going to use to run a command:</p>
<pre name="code" class="php">
function cmd_exec($cmd, &#038;$stdout, &#038;$stderr)
{
   $outfile = tempnam(".", "cmd");
   $errfile = tempnam(".", "cmd");
   $descriptorspec = array(
       0 => array("pipe", "r"),
       1 => array("file", $outfile, "w"),
       2 => array("file", $errfile, "w")
   );
   $proc = proc_open($cmd, $descriptorspec, $pipes);

   if (!is_resource($proc)) return 255;

   fclose($pipes[0]);    //Don't really want to give any input

   $exit = proc_close($proc);
   $stdout = file($outfile);
   $stderr = file($errfile);

   unlink($outfile);
   unlink($errfile);
   return $exit;
}
</pre>
<h3>Adding a Form</h3>
<p>Now that we wrote the function to run a shell command from php, we need to write a html form from where to trigger the execution of the shell commands. First we define an html form:</p>
<pre name="code" class="html">
<form name="signupform" method="post" action="run.php">
<table align="left" valign="top" width="100%" border="0">
<tbody>
<tr>
<td><font class="label2">Command:</font></td>
<td>
<input class="formtext2" type="text" name="command" size="100">
<input class="formbuton" type="submit" value="OK">
		</td>
</tr>
</tbody>
</table>
</form>
</pre>
<p>And finally we add the code to run the command entered in the form:</p>
<pre name="code" class="php">
if (isset($_POST['command']))
{
	echo 'Command: ' . $_POST['command'] . '';
	$exit = cmd_exec($_POST['command'],$stdout, $stderr);

	//print the output
	foreach ($stdout as $line)
	{
		echo "$line";
	}

	//in case there an error is returned
	foreach ($stderr as $line)
	{
		echo "$line";
	}
}
</pre>
<p>Now all you have to do is to put all the snippets described above in a php file. Of you can download it from <a href='http://php-html.net/tutorials/wp-content/uploads/2009/07/simple-run.zip'>here</a>. You have to use with caution and keep in mind that it is not protected by password. In the next tutorial we are going to ad a login form to the script. </p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/how-to-write-a-php-script-to-run-shell-commands-from-browser/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/how-to-write-a-php-script-to-run-shell-commands-from-browser/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/MgJwoHxI0kg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/how-to-write-a-php-script-to-run-shell-commands-from-browser/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/how-to-write-a-php-script-to-run-shell-commands-from-browser/</feedburner:origLink></item>
		<item>
		<title>How to Identify Duplicate and Similar Text in Php</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/gV2WvCPWQVA/</link>
		<comments>http://php-html.net/tutorials/how-to-identify-duplicate-and-similar-text-in-php/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 11:17:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[howto]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[usefull]]></category>

		<guid isPermaLink="false">http://php-html.net/tutorials/?p=96</guid>
		<description><![CDATA[It&#8217;s not a common problem but sometimes you have to check if 2 texts are similar. If you have to aggregate data from multiple sources you might know what I&#8217;m talking about. The most simple thing you can try is to simply compare the 2 strings. A simple comparison will not help if one of [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s not a common problem but sometimes you have to check if 2 texts are similar. If you have to aggregate data from multiple sources you might know what I&#8217;m talking about. </p>
<p>The most simple thing you can try is to simply compare the 2 strings. A simple comparison will not help if one of the strings are contains an extra space. A more serious algorithm should be used for such cases. Fortunately php provides us several functions that can be used.<br />
<span id="more-96"></span><br />
<a href="http://www.php.net/soundex">soundex()</a> &#8211; accepts a string as a parameter and returns a string 4 characters long, starting with a letter. The result is called soundex key and words pronounced similarly produce the same soundex key. It should be used only for single words.<br />
<a href="http://www.php.net/manual/en/function.levenshtein.php">levensthein()</a> &#8211; returns a number based on levenshtein algorithm which describes the similarity between 2 strings. It can be used only for strings with less than 255 characters.<br />
<a href="http://www.php.net/manual/en/function.similar-text.php">similar_text()</a> &#8211; calculates the similarity between two strings and can return the result as a number representing the number of matching chars in both strings or a similarity percentage.</p>
<p>soundex() it&#8217;s a php function which implements the soundex algorithm described by Donald Knuth in &#8220;The Art Of Computer Programming, vol. 3: Sorting And Searching&#8221;. It can be used to find similar words, misspelled words or to create indexes to simplify searches in databases when the pronunciation is known but not the spelling.</p>
<p>levenshtein() &#8211; levenshtein distance represents the minimal number of characters you have to replace, insert or delete to transform one string into another. The complexity of the algorithm is O(m*n). The function can be used only on string with less that 255 characters. If you want to aggregate rss feeds and eliminate duplicates, this function could be just fine if the rss items are truncated.</p>
<p>simple_text() &#8211; calculates the similarity between two strings. It returns the number the number of matching characters in both strings or a percentage of how similar the strings are. The function implements recursively and algorithm and has the complexity of O(N**3). The function is not so efficient as the levenshtein function but it can e used for strings more than 255 characters.</p>
<p>There are a few remarks about similar_text() you should consider:<br />
- if you apply it on 2 texts of which one one is the first half of the other one the similarity would be 50% even if the strings are identically.<br />
- the function might take a few seconds to compare strings of more than 20 000 on a regular computer.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/how-to-identify-duplicate-and-similar-text-in-php/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/how-to-identify-duplicate-and-similar-text-in-php/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/gV2WvCPWQVA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/how-to-identify-duplicate-and-similar-text-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/how-to-identify-duplicate-and-similar-text-in-php/</feedburner:origLink></item>
		<item>
		<title>How to Send Mail From PHP</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/M3VN0T68gN8/</link>
		<comments>http://php-html.net/tutorials/how-to-send-mail-from-php/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 11:49:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Mail]]></category>
		<category><![CDATA[Util]]></category>

		<guid isPermaLink="false">http://www.php-html.net/tutorials/?p=68</guid>
		<description><![CDATA[Sending mails from PHP can raise certain problems. Usually the mail is sent from php through a simple function PHP function: mail(&#8230;). However the function needs a module that should be enabled in the php ini file. Not all the hosting providers enable it and you can not make changes in php admin area in [...]]]></description>
			<content:encoded><![CDATA[<p>Sending mails from PHP can raise certain problems. Usually the mail is sent from php through a simple function PHP function: mail(&#8230;). However the function needs a module that should be enabled in the php ini file. Not all the hosting providers enable it and you can not make changes in php admin area in the php shared hosting. In this case the another alternative should be used. There are 2 php libraries I&#8217;ve tried to send a mail which will be described in this tutorial: <a href="http://phpmailer.codeworxtech.com/">PHPMailer</a> and Mail <a href="http://pear.php.net/package/Mail">PEAR Package</a>.<br />
<span id="more-68"></span></p>
<p>1. Using the php mail() function.<br />
The first alternative you should use if it available is the php mail function.</p>
<p>2 Using PHPMailer<br />
The PHP Mailer is a Object Oriented PHP library that can be used to send mails through SMTP and using the send mail Linux command. It is recommended to use SMTP for sending the emails. Most of the hosting providers offer the option to configure email boxes which can be used to send mails using SMTP protocol.</p>
<p>Here is a piece of code that can be used to send mails through SMTP:</p>
<pre name="code" class="php">
<?php
include_once('./phpmailer/class.phpmailer.php');

$mail    = new PHPMailer();

$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "xxxx@xxxx.com"; // SMTP username
$mail->Password = "xxxxxx"; // SMTP password
$webmaster_email = "xxxx@xxxx.com"; //Reply to this email ID

$email="yyyy@yyyy.com"; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
  echo "Message has been sent";
}
?>
</pre>
<p>The previous piece of code was tested sending emails through gmail accounts and worked fine.</p>
<p>In many cases PHPMailer seems to raise some difficulties when it is used in different accounts. The same code might work for one hosting without working on other hosting accounts and the message errors are not detailed enough to give enough hints to fix the problem.</p>
<p>A frequent problem raised by PHPMailer is the following Exception:<b>Language string failed to load: instantiate</b>. This problem is generated by the fact that the languages files can not be found and appears usually when another error must be reported and when phpmailer is not installed in the root of the application.</p>
<p>3.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/how-to-send-mail-from-php/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/how-to-send-mail-from-php/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/M3VN0T68gN8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/how-to-send-mail-from-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/how-to-send-mail-from-php/</feedburner:origLink></item>
		<item>
		<title>Svn Commands</title>
		<link>http://feedproxy.google.com/~r/PhpHtmlCssTutorials/~3/WUmIai0dDBk/</link>
		<comments>http://php-html.net/tutorials/svn-commands/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 19:27:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Source Control]]></category>
		<category><![CDATA[svn]]></category>

		<guid isPermaLink="false">http://www.php-html.net/tutorials/?p=62</guid>
		<description><![CDATA[1. Svn commands on server Create a repository &#8211; in order to create a svn repository(server) you need access on the server machine. The command can work only locally and it can not work on network paths: // Windows: svn admin c:\\svn\serverfiles\ // Linux: svn admin /svn/serverfiles/ Start the server &#8211; to start a server [...]]]></description>
			<content:encoded><![CDATA[<p>1. Svn commands on server</p>
<p><strong>Create a repository</strong> &#8211; in order to create a svn repository(server) you need access on the server machine. The command can work only locally and it can not work on network paths:</p>
<pre name="code" class="js">
// Windows:
svn admin c:\\svn\serverfiles\

// Linux:
svn admin /svn/serverfiles/
</pre>
<p><strong>Start the server</strong> &#8211; to start a server you must run the following command(if svnserver is not present in the path you can add it or you can use the full pathname).:</p>
<pre name="code" class="js">
//Windows:
svnserve --daemon --root c:\\svn\serverfiles\
<span id="more-62"></span>
//Linux:
svnserve --daemon --root /svn/serverfiles/

//To see all the options:
svnserve --help
</pre>
<p>2. Client Commands</p>
<p>Considering we have a svn server installed with a repository created, and the server is up and running, let&#8217;s add a new project to the repository(the svnserver can run on the same machine, but it&#8217;s still a server). To begin with let&#8217;s create the following structure, putting the files of out project inside the trunk server. </p>
<p><a href="http://php-html.net/tutorials/wp-content/uploads/2009/02/svn-structure.png"><img src="http://php-html.net/tutorials/wp-content/uploads/2009/02/svn-structure.png" alt="" title="Svn File Structure" width="195" height="130" class="alignnone size-full wp-image-410" /></a></p>
<p>Once done run the following command to add the project structure in the new repository on the server and to commit the first version:</p>
<pre name="code" class="js">
//Windows:
svn import project file:///c:/projects/project -m "Initial Version"

//Linux:
svn import project file:///projects/project -m "Initial Version"
</pre>
<p>svn co<br />
svn add &#8211;force .<br />
svn commit -m &#8220;this is a message&#8221;</p>
<p>show changed files:<br />
svn log -r 1:2 -v</p>
<p>Ignore Command:</p>
<p>Ignore a file:<br />
svn propset svn:ignore .project .</p>
<p>Ignore a directory and all the files inside it:<br />
svn propset svn:ignore &#8216;*&#8217; classes/</p>
<p>If the location of the repository is changed you can use the following command to switch the local working copy(checked out from the old location of the repository), to the new one:<br />
svn switch &#8211;relocate svn://oldlocation.com/svn/project/trunk http://newlocation.org/repository/project/trunk </p>
<p>svn switch &#8211;relocate svn://anonsvn.opensource.apple.com/svn/webkit/trunk \</p>
<p>http://svn.webkit.org/repository/webkit/trunk</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://php-html.net/tutorials/svn-commands/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://php-html.net/tutorials/svn-commands/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/PhpHtmlCssTutorials/~4/WUmIai0dDBk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://php-html.net/tutorials/svn-commands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://php-html.net/tutorials/svn-commands/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.809 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-05-16 00:19:49 -->

