<?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>Stuff by Sarah &#187; Learn PHP</title>
	<atom:link href="http://www.stuffbysarah.net/category/learn-php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stuffbysarah.net</link>
	<description>PHP, WordPress and Business Ramblings</description>
	<lastBuildDate>Thu, 02 Feb 2012 20:19:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PHP Contact Form Dissected, Part 1</title>
		<link>http://www.stuffbysarah.net/2008/04/17/php-contact-form-dissected-part-1/</link>
		<comments>http://www.stuffbysarah.net/2008/04/17/php-contact-form-dissected-part-1/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 19:37:39 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/?p=692</guid>
		<description><![CDATA[For those who want to understand the secure PHP contact form that I wrote and released last month, here is part 1 of the dissection of the code with the whys and hows. I was planning to just do one post with a complete dissection but I&#039;ve had this sitting here for a couple of ...]]></description>
			<content:encoded><![CDATA[<p>For those who want to understand the <a href="http://www.stuffbysarah.net/blog/2008/03/19/secure-php-contact-form/" class="internal">secure PHP contact form</a> that I wrote and released last month, here is part 1 of the dissection of the code with the whys and hows.</p>
<p>I was planning to just do one post with a complete dissection but I&#039;ve had this sitting here for a couple of weeks and am just a little pushed for time right now, so I&#039;ll get the parts out as and when I&#039;ve got a chance! I&#039;ll link all of the posts together once they&#039;re all done.</p>
<p><span id="more-692"></span></p>
<p>If you haven&#039;t already got it, download the <a href="http://www.stuffbysarah.net/plugins/contact-form.zip" class="zip">Contact Form</a> and open up the PHP 4.4 version in your own text editor, ideally with line numbers as I&#039;ll be referring to them.</p>
<h3>Setting the variables</h3>
<p>First off is the code to set the variables. This makes it easier for those who don&#039;t want to poke around in the PHP to find what to change.</p>
<dl class="code">
<dt>Code Excerpt</dt>
<dd>
<ol>
<li value="11">// Change the $to_email to the address you want the email to be sent to</li>
<li>$to_email = &#034;you@yourdomain.com&#034;;</li>
<li>&nbsp;</li>
<li>// Change $redirect to where you want the user to be redirected to, usually a thankyou page</li>
<li>$redirect = &#034;thankyou.html&#034;;</li>
<li>&nbsp;</li>
<li>// Change the $subject to the subject of the email that you what</li>
<li>$subject  = &#034;Online contact form from your site&#034;;</li>
<li>&nbsp;</li>
<li>// Specify the required fields</li>
<li>$req_fields = array(&#034;cfname&#034;, &#034;cfemail&#034;, &#034;cfmessage&#034;);</li>
</ol>
</dd>
</dl>
<p>The first 3 variables, $to_email, $redirect and $subject, should be straightforward. The final variable is the array $req_fields. This is an array of fieldnames used in the form, which need to be checked to ensure content has been entered into each form field specified. By listing them in an array it makes it easy for the user to add more fields without having to edit the PHP lower down.</p>
<h3>The Processing Script</h3>
<p>The processing script is above the start of the HTML output so that if a successful email is sent the header redirect can run and redirect the user to a thank you page. The first line of the processing script checks to make sure that the form has been submitted to the page (else there&#039;s no point running the script at this point). The if statement below checks to see if the submit button has been pressed and also checks that it has a value (as the isset() function will be true if the variable tested has been created, regardless of being empty or not).</p>
<dl class="code">
<dt>Code Excerpt</dt>
<dd>
<ol>
<li value="23">// this bit does the mailing</li>
<li>if (isset($_POST['cfsubmit']) &#038;&#038; trim($_POST['cfsubmit']) != &#034;&#034;) :</li>
</ol>
</dd>
</dl>
<p>Then we specify a few functions to validate the email address supplied to ensure that it&#039;s safe and secure (I&#039;ve written in the past about <a href="http://www.stuffbysarah.net/blog/2006/02/14/php-secure-form-mailing/" class="internal">email header injections</a>).</p>
<dl class="code">
<dt>Code Excerpt</dt>
<dd>
<ol>
<li value="30">// check no additional lines have been added to the email field</li>
<li>function has_newlines($text) {</li>
<li class="indent1">return preg_match(&#034;/(%0A|%0D|\n+|\r+)/i&#034;, $text);</li>
<li>}</li>
<li>&nbsp;</li>
<li>// Check that additional headers haven&#039;t been added</li>
<li>function has_emailheaders($text) {</li>
<li class="indent1">return preg_match(&#034;/(%0A|%0D|\n+|\r+)(content-type:|to:<span>|c</span>c:<span>|bc</span>c:)/i&#034;, $text);</li>
<li>}</li>
<li>// check the email is of a valid form</li>
<li>function is_valid($text) {</li>
<li class="indent1">return preg_match(&#034;/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix&#034;,$text);</li>
<li>}</li>
</ol>
</dd>
</dl>
<p>To briefly explain these functions, the first, has_newlines, checks to see if the email address supplied spans more than one line, by detecting a \n or \r in it. It returns TRUE if any instance of a new line is found. The second, has_emailheaders, checks for the instance of a header injection and returns TRUE if anything is found. The final function checks the validity of the email address, it checks that it follows the format of how an email address should be constructed and returns TRUE if the email address provided is valid.</p>
<p>Next is a <a href="http://www.php.net/foreach" class="external">foreach()</a> statement that cleans up the form data. It uses the foreach() loop as to allow this form to be flexible, ie. allowing extra fields, we cannot predetermine the fieldnames in use, so this runs through every key in the $_POST array, ie. every fieldname used in the form. On line 45 the code checks to see if the <a href="http://uk.php.net/magic_quotes" class="external">Magic Quotes</a> setting in the php.ini file is set to on (most hosts have this on to try and combat insecure scripts, let&#039;s not get started on that debate though!), if it is then it will have had all the form content run through the <a href="http://www.php.net/addslashes" class="external">addslashes()</a> function, so we reverse that work using <a href="http://www.php.net/stripslashes" class="external">stripslashes()</a>. For those asking why, first off this is a form that&#039;s going to be emailed through, so the &#039;security&#039; that magic_quotes gives isn&#039;t needed in this instance, and if it was going into a database then I&#039;d use a more <a href="http://www.stuffbysarah.net/blog/2006/03/18/secure-php-and-sql-injections/" class="internal">secure escape method</a>. Then on line 49 we also run the <a href="http://www.php.net/strip_tags" class="external">strip_tags()</a> function, which will strip away any additional HTML added to the form. The final result is saved in an associative array called $formstuff with the key being the same as the key in the $_POST array ie. the fieldname.</p>
<dl class="code">
<dt>Clean up the Form Content</dt>
<dd>
<ol>
<li value="44">foreach ($_POST AS $key => $value) :</li>
<li class="indent1">if (get_magic_quotes_gpc()) :</li>
<li class="indent2">$value = stripslashes($value);</li>
<li class="indent1">endif;</li>
<li>&nbsp;</li>
<li class="indent1">$formstuff[$key] = strip_tags($value);</li>
<li>endforeach;</li>
</ol>
</dd>
</dl>
<p>Then, in another foreach() loop, we have the code which checks that the required fields (specified in the array on line 21) contain data, this runs through the required fields array, taking each fieldname one at a time. First it trims all excess white space off the field input, then it checks to see if the field&#039;s value is empty. If it is then the variable $formerror is set to TRUE and the rest of the processing won&#039;t run as per the if statement on line 61, instead the user is returned to the form to try again.</p>
<dl class="code">
<dt>Check required fields are complete.</dt>
<dd>
<ol>
<li value="53">$formerror = FALSE;</li>
<li>foreach ($req_fields AS $formlabel) :</li>
<li class="indent1">$value = trim($formstuff[$formlabel]);</li>
<li class="indent1">if (empty($value)) :</li>
<li class="indent2">$formerror = TRUE;</li>
<li class="indent1">endif;</li>
<li>endforeach;</li>
<li>&nbsp;</li>
<li>if (!$formerror) :</li>
</ol>
</dd>
</dl>
<p>Part 2 coming soon!</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2008/04/17/php-contact-form-dissected-part-1/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2008/04/17/php-contact-form-dissected-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure PHP Contact Form</title>
		<link>http://www.stuffbysarah.net/2008/03/19/secure-php-contact-form/</link>
		<comments>http://www.stuffbysarah.net/2008/03/19/secure-php-contact-form/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 12:05:18 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2008/03/19/secure-php-contact-form/</guid>
		<description><![CDATA[I&#039;ve written up an easy to use, secure, accessible and XHTML Strict compliant contact form, originally for someone to use on their site, but figured I&#039;d post it up here as a bit of a PHP tutorial for anyone who wants to understand what&#039;s going on, or for others to just download, follow the instructions ...]]></description>
			<content:encoded><![CDATA[<p>I&#039;ve written up an easy to use, secure, accessible and XHTML Strict compliant contact form, originally for someone to use on their site, but figured I&#039;d post it up here as a bit of a PHP tutorial for anyone who wants to understand what&#039;s going on, or for others to just download, follow the instructions and use. I&#039;ll explain its usage today and then dissect the form for any PHP learners later in the week.</p>
<p>First off, <a href="/plugins/contact-form.zip" class="zip">download the contact form</a>, unzip it and open it in your favourite coding editor. The best version of this form requires PHP 4.4+ however I&#039;ve altered the line that depends on this version so that you can use it down to version 4.0 however foreign characters will not be checked in the name. Both are contained in the download file.</p>
<p><span id="more-691"></span></p>
<p>This won&#039;t work straight out of the box. You&#039;ll need to edit a few lines first plus add in your surrounding HTML markup.</p>
<h3>Edit the Basics</h3>
<p>To get this up and running with minimal effort you need to do the following (from top down in the file).</p>
<ol>
<li>Edit the <strong>$to_email</strong> variable to contain your email address. So replace &#039;you@yourdomain.com&#039; with your own email address, ensuring the double quotes are still kept around the email address.</li>
<li>Edit the <strong>$redirect</strong> variable to contain the address, relative to the root, of your thank you page. So if your thank you page is found at http://www.yourdomain.com/contact/thankyou.html this value will become &#034;contact/thankyou.html&#034;.</li>
<li>Edit the <strong>$subject</strong> variable to contain the text you want to appear in your email subject when you receive an email from the form.</li>
<li>Locate the line &gt;!&#8211; Your Header HTML code or include goes here &#8211;&lt; and replace it with your standard site header markup. This could be a PHP include to include the header file, or plain HTML markup.</li>
<li>Locate the line &gt;!&#8211; Your footer HTML code or include goes here &#8211;&lt; and replace it with your standard site footer markup. Again, this can be a PHP include or the plain HTML markup.</li>
</ol>
<p>This should then leave you with a file that has the following sections:</p>
<ul>
<li>PHP Script</li>
<li>HTML Header markup</li>
<li>Form in the content area</li>
<li>HTML Footer markup</li>
</ul>
<p>At this point you should be able to upload this file to any PHP enabled server, view the file, complete the form and submit it. An email should then come through to your specified email account.</p>
<h3>Advanced Options</h3>
<p>There&#039;s two advanced options in this form. The first is to add additional fields into the form, and they&#039;ll still be picked up in the email. To do this, edit the form to include your additional form fields (checkboxes and file uploads are not supported in this form) using the following method (if you&#039;re not sure on working with forms, read up on <a href="http://www.ap4a.co.uk/archives/2006/stylephreaks-standard-form-layout-revisited/" class="external">accessible form layouts</a>):</p>
<dl class="code">
<dt>Form Code Excerpt</dt>
<dd>
<ol>
<li>&lt;div&gt;</li>
<li class="indent1">&lt;label for=&quot;cf<span class="red">text</span>&quot;&gt;<span class="red">Title</span>: &lt;/label&gt;</li>
<li class="indent1">&lt;input type=&quot;text&quot; name=&quot;cf<span class="red">text</span>&quot; id=&quot;cf<span class="red">text</span>&quot; size=&quot;30&quot; value=&quot;&lt;?php get_value(&apos;cf<span class="red">text</span>&apos;) ?&gt;&quot; /&gt;</li>
<li>&lt;/div&gt;</li>
</ol>
</dd>
</dl>
<p>Where <span class="red">text</span> makes up your input&#039;s fieldname. I would recommend keeping &#039;cf&#039; at the start of all of your fieldnames as this means there is less potential for variables to clash in the PHP and it can help to reduce spam as spammers will often assume your field names are the general ones of &#039;name&#039;, &#039;email&#039;, message&#039; etc. <span class="red">Title</span> is then the value displayed on the page, so the form label.</p>
<p>The second advanced option is to also control your required fields. Near the top of the script there is a line:</p>
<dl class="code">
<dt>PHP Code Excerpt</dt>
<dd>
<ol>
<li>// Specify the required fields</li>
<li>$req_fields = array(&quot;cfname&quot;, &quot;cfemail&quot;, &quot;cfmessage&quot;);</li>
</ol>
</dd>
</dl>
<p>This array lists the fields that are required to contain content. So if you added 3 extra fields, eg. cfurl, cftelephone and cfaddress and you want to make the telephone and address field required, but not the url field, then you can add these in by adding them to the end of the comma delimited list i.e.</p>
<dl class="code">
<dt>PHP Code Excerpt</dt>
<dd>
<ol>
<li>$req_fields = array(&quot;cfname&quot;, &quot;cfemail&quot;, &quot;cfmessage&quot;, &quot;cftelephone&quot;, &quot;cfaddress&quot;);</li>
</ol>
</dd>
</dl>
<p>This will then check that both the telephone and address fields have content in them, however the URL field can be left blank. Of course it will be wise to add</p>
<dl class="code">
<dt>HTML Code Excerpt</dt>
<dd>
<ol>
<li>&lt;em&gt;Required&lt;/em&gt;</li>
</ol>
</dd>
</dl>
<p>After the label title and before the closing label tag, as I&#039;ve done with the other required fields.</p>
<h3>Guarantees</h3>
<p>There are none! The form is secure to the best of my abilities. It checks against email header injection, it removes all html tags that may have been entered into the form, it checks the name entered contains just typical characters that a name would contain (including foreign characters)*, it checks your required fields contain content and it will email all details plus the user&#039;s given IP address and browser details through to your specified email address. By using less than general field names, spam should be reduced to human spam (I use this method elsewhere and rarely get any spam off my forms that&#039;s not human generated).</p>
<p>The form is accessible in that when you click a label title the cursor will be placed in the input box or textarea. It uses the correct markup of a fieldset and legends, and if you choose to extend the form I recommend you continue with these standards. Suggested <abbr title="Cascading Style Sheets">CSS</abbr> for the styling of a form and error warning is below.</p>
<dl class="code">
<dt>Suggested CSS Code</dt>
<dd>
<ol>
<li>ul.warning {</li>
<li class="indent1">color: #c00;</li>
<li class="indent1">font-weight: bold;</li>
<li>}</li>
<li>&nbsp;</li>
<li>fieldset {</li>
<li class="indent1">width: 500px;</li>
<li class="indent1">border:none;</li>
<li class="indent1">border-top: 1px solid #999;</li>
<li class="indent1">padding: 10px;</li>
<li class="indent1">margin-top: 10px;</li>
<li>}</li>
<li>&nbsp;</li>
<li>legend {</li>
<li class="indent1">font-weight: bold;</li>
<li class="indent1">padding: 0 5px;</li>
<li>}</li>
<li>&nbsp;</li>
<li>label {</li>
<li class="indent1">width: 125px;</li>
<li class="indent1">float: left;</li>
<li class="indent1">text-align: right;</li>
<li class="indent1">margin-right: 5px;</li>
<li>}</li>
<li>&nbsp;</li>
<li>form div {</li>
<li class="indent1">clear: both;</li>
<li class="indent1">margin-bottom: 10px;</li>
<li>}</li>
</ol>
</dd>
</dl>
<p>So give it a go and let me know what you think. Any problems or comments, post them below and I&#039;ll do my best to help out or accommodate you <img src='http://www.stuffbysarah.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>* Only in the PHP 4.4+ version.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2008/03/19/secure-php-contact-form/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2008/03/19/secure-php-contact-form/feed/</wfw:commentRss>
		<slash:comments>70</slash:comments>
		</item>
		<item>
		<title>Learn PHP and MySQL SitePoint Book</title>
		<link>http://www.stuffbysarah.net/2007/11/15/learn-php-and-mysql-sitepoint-book/</link>
		<comments>http://www.stuffbysarah.net/2007/11/15/learn-php-and-mysql-sitepoint-book/#comments</comments>
		<pubDate>Thu, 15 Nov 2007 17:06:01 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2007/11/15/learn-php-and-mysql-sitepoint-book/</guid>
		<description><![CDATA[Anyone who&#039;s wanting to learn PHP and MySQL should be considering SitePoint&#039;s Build Your Own Database Driven Website Using PHP &#038; MySQL by Kevin Yank. I&#039;ve just finished reading this book and have to admit, I wish I had this book to learn from when I first learnt PHP a few years back. You may ...]]></description>
			<content:encoded><![CDATA[<p>Anyone who&#039;s wanting to learn PHP and MySQL should be considering SitePoint&#039;s <a href="http://www.sitepoint.com/books/phpmysql1/" class="external">Build Your Own Database Driven Website Using PHP &#038; MySQL</a> by Kevin Yank. I&#039;ve just finished reading this book and have to admit, I wish I had this book to learn from when I first learnt PHP a few years back.</p>
<p>You may be wondering why I&#039;ve been reading a book that&#039;s clearly for beginners. Couple of reasons. I learnt PHP when version 4 had just been released. The book I learnt from was out of date within weeks simply because of the major changes that happened, default settings etc. Whilst it was a great book to learn from there were parts that I&#039;d either skipped (Object Oriented Programming for a start!) or just parts I&#039;d never really grasped. Knowing how well SitePoint books are written, I decided to buy this book to give me a chance to refresh my knowledge, pick up on any changes for PHP 5 and also have an up-to-date PHP book on my shelf.</p>
<p>So what will this book teach you? It will teach you the basics of PHP and using MySQL. It explains how to use PHP to create dynamic webpages, how to store the content of a site in a database and retrieve that information and display it on the site. How to allow people to add to and update that content. It goes into regular expressions, the basics of PHP&#039;s file access methods, good structure using includes and more.</p>
<p>I recently had a chat about this book with someone who wanted to learn the basics a bit better but had looked at the free chapters of this book and got completely confused by its complexity. If anyone else has been or finds themselves in the same situation then I know where you&#039;re at. Ignore the first 2 chapters initially! The first chapter goes into how to set up PHP and MySQL on your computer. Whilst I used to do this myself now I recommend using <a href="http://www.apachefriends.org/en/xampp.html" class="external">Xampp</a>. It&#039;s easy to install, comes with everything you need and can also be run off an external drive or USB pen drive, so you don&#039;t even need to put it on your computer! Then the second chapter of the book goes into MySQL. Again, not something you need to concern yourself with at first. So skip to chapter 3 and things shouldn&#039;t be as complex and scary!</p>
<p>So if you want to learn PHP then I highly recommend this book for the basics. You can get 4 free chapters from the <a href="http://www.sitepoint.com/books/phpmysql1/" class="external">SitePoint page</a> or you can buy the book cheaper with free delivery from <a href="http://www.stuffbysarah.net/amazon.php?id=0975240218" class="internal">Amazon UK</a>.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2007/11/15/learn-php-and-mysql-sitepoint-book/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2007/11/15/learn-php-and-mysql-sitepoint-book/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>SitePoint PHP Anthology Out</title>
		<link>http://www.stuffbysarah.net/2007/11/01/sitepoint-php-anthology-out/</link>
		<comments>http://www.stuffbysarah.net/2007/11/01/sitepoint-php-anthology-out/#comments</comments>
		<pubDate>Thu, 01 Nov 2007 13:35:16 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2007/11/01/sitepoint-php-anthology-out/</guid>
		<description><![CDATA[SitePoint have released the 2nd Edition of their PHP Anthology: Tips, Tricks and Hacks. Not that I can ever remember seeing a 1st Edition of this book (else it would have been on my bookshelves!). It looks to be a pretty good book, I&#039;ve just grabbed the free chapters to have a look through. For ...]]></description>
			<content:encoded><![CDATA[<p>SitePoint have released the 2nd Edition of their <a href="http://www.sitepoint.com/books/phpant2/" class="external">PHP Anthology: Tips, Tricks and Hacks</a>. Not that I can ever remember seeing a 1st Edition of this book (else it would have been on my bookshelves!). It looks to be a pretty good book, I&#039;ve just grabbed the free chapters to have a look through.</p>
<p>For anyone who&#039;s learnt the basics then this book is probably a good intermediate level book before stepping into the advanced stuff. The free chapters are available from their site and worth a look if nothing else. Alternatively it&#039;s available at <a href="http://www.stuffbysarah.net/amazon.php?id=0975841998" class="internal">Amazon UK</a> as well (although for once the SitePoint price is cheaper with the current exchange rate!).</p>
<p>Alternatively, on <a href="">this SitePoint post</a> you have a link where you can get $10 off the book, plus a free (usually $10) PHP Reference Poster. So that would be £20 for the lot including delivery. Ack it&#039;s tempting&#8230;!</p>
<p><strong>Update:</strong> The First Edition of this was the <a href="http://www.sitepoint.com/books/phpant1/" class="external">PHP Anthology Vol 1 and 2</a> &#8211; two books written by Harry Fuecks. SitePoint have now merged these two into one and brought on a load of new authors. I&#039;m guessing it could be quite different in the way it&#039;s written compared to the first edition, however I&#039;d have to compare the sample chapters to the books I have. However, if you&#039;ve learnt PHP and want to progress then it&#039;s the best next step you could take <img src='http://www.stuffbysarah.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2007/11/01/sitepoint-php-anthology-out/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2007/11/01/sitepoint-php-anthology-out/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Creating Arrays</title>
		<link>http://www.stuffbysarah.net/2007/06/27/creating-arrays/</link>
		<comments>http://www.stuffbysarah.net/2007/06/27/creating-arrays/#comments</comments>
		<pubDate>Wed, 27 Jun 2007 17:10:12 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2007/06/27/creating-arrays/</guid>
		<description><![CDATA[Arrays are such a useful part of PHP. It&#039;s a way to store multiple pieces of information in one variable, and they can be very powerful and timesaving when used in the right way. There are a couple of ways to create an array. The first is writing the whole array out in one go ...]]></description>
			<content:encoded><![CDATA[<p>Arrays are such a useful part of PHP. It&#039;s a way to store multiple pieces of information in one variable, and they can be very powerful and timesaving when used in the right way.</p>
<p>There are a couple of ways to create an array. The first is writing the whole array out in one go eg.</p>
<dl class="code">
<dt>Array Code</dt>
<dd>
<ol>
<li>$testarr = array(&#034;Bob&#034;, &#034;Sally&#034;, &#034;John&#034;, &#034;Pete&#034;, &#034;David&#034;, &#034;Jane&#034;);</li>
</ol>
</dd>
</dl>
<p>This is fine if you can create the array with one line, however as your PHP progresses you&#039;ll find you use an array to capture data from say a form submission. So an efficient way of doing this, and another way which you can create an array, looping or otherwise, is</p>
<dl class="code">
<dt>Array Code</dt>
<dd>
<ol>
<li>$testarr = array();</li>
<li>$testarr[] = &#034;Bob&#034;;</li>
<li>$testarr[] = &#034;Sally&#034;;</li>
<li>$testarr[] = &#034;John&#034;;</li>
<li>$testarr[] = &#034;Pete&#034;;</li>
<li>$testarr[] = &#034;David&#034;;</li>
<li>$testarr[] = &#034;Jane&#034;;</li>
</ol>
</dd>
</dl>
<p>Note the first line initialises the array. This is for security to ensure that nothing has been passed into the array eg. via the URL, that we don&#039;t want in there.</p>
<p>With this array you can use it in a variety of functions and uses. For a full list of the functions available read the <a href="http://www.php.net/arrays" class="external">Arrays</a> page on <a href="http://www.php.net" class="external">PHP.net</a>. Examples of usage are</p>
<ul>
<li>Re-sort the list and display in alphabetical order.</li>
<li>Compare a variable to the array to see if the variable exists within the array.</li>
</ul>
<p>To simply list the content of an array you can either do the quick and easy method using print_r()</p>
<dl class="code">
<dt>Array Code</dt>
<dd>
<ol>
<li>print_r($testarr);</li>
</ol>
</dd>
</dl>
<p>Or you could do it a little neater using the foreach loop.</p>
<dl class="code">
<dt>Foreach Loop Code</dt>
<dd>
<ol>
<li>foreach ($testarr AS $key => $value) :</li>
<li class="indent1">echo &#034;Item &#034;.$key.&#034;: &#034;.$value;</li>
<li>endforeach;</li>
</ol>
</dd>
</dl>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2007/06/27/creating-arrays/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2007/06/27/creating-arrays/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Manipulating Strings</title>
		<link>http://www.stuffbysarah.net/2006/09/09/manipulating-strings/</link>
		<comments>http://www.stuffbysarah.net/2006/09/09/manipulating-strings/#comments</comments>
		<pubDate>Sat, 09 Sep 2006 13:10:10 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2006/09/09/manipulating-strings/</guid>
		<description><![CDATA[There are many string functions that come in so useful with PHP work. All of the string functions can be found in the PHP Manual however I&#039;ll cover the two I use the most below, and then obviously others as time goes on. substr() &#8211; This returns a section of the string which you control ...]]></description>
			<content:encoded><![CDATA[<p>There are many string functions that come in so useful with PHP work. All of the string functions can be found in the<br />
PHP Manual however I&#039;ll cover the two I use the most below, and then obviously others as time goes on.</p>
<p><a href="http://www.php.net/substr" class="external">substr()</a> &#8211; This returns a section of the string which you control with the start and length or end values. This is handy if<br />
you just want to display a short excerpt of a longer description. There are many uses of this but without going into too<br />
much detail they won&#039;t necessarily make sense at present.</p>
<p>For using the function you have several options:<br />
1. substr(&#034;abcdef&#034;, 2) &#8211; this would output &#039;cdef&#039; ie. it outputs everything after the first 2 characters.<br />
2. substr(&#034;abcdef&#034;, 1, 3) &#8211; this would output &#039;bcd&#039; ie. the pointer starts at position 1 (bearing in mind the letter &#039;a&#039; is<br />
currently in position 0) and then print 3 characters.<br />
3. substr(&#034;abcdef&#034;, 0, -1) &#8211; this would output &#039;abcde&#039; ie. the pointer starts at position 0 and outputs all until the pointer<br />
is minus one character from the end.<br />
4. substr(&#034;abcdef&#034;, -2) &#8211; this would output &#039;ef&#039; ie. the last two characters regardless of knowing the length of the string</p>
<p><a href="http://www.php.net/str_replace" class="external">str_replace()</a> &#8211; This takes an existing character or string, along with the replacement string and searches the given string<br />
for any existance of the string to replace. Okay that sounded confusing! Much easier with a few examples:</p>
<dl class="code">
<dt>Array Code</dt>
<dd>
<ol>
<li>str_replace(&#034;a&#034;, &#034;b&#034;, &#034;Mary had a little lamb&#034;); // would produce &#039;Mbry hbd b little lbmb&#039;</li>
<li>str_replace(&#034; &#038; &#034;, &#034; &amp;amp; &#034;, &#034;You &#038; I&#034;); // would produce &#039;You &amp; I&#039; which is valid markup for XHTML Strict</li>
<li>str_replace(&#034; &#034;, &#034;%20&#034;, &#034;http://www.domain.com/contact us.htm&#034;); // unfortunately a lot of people believe that spaces in urls are fine to use when they really aren&#039;t. This is one way to clean them up in your links.</li>
</ol>
</dd>
</dl>
<p><a href="http://www.php.net/explode" class="external">explode()</a> &#8211; This allows you to choose a character in a string and split the string up into an array, where each bit in the<br />
original string started and/or ended with the chosen character. For example</p>
<dl class="code">
<dt>Array Code</dt>
<dd>
<ol>
<li>$string = explode(&#034;-&#034;, &#034;Item 1-Item 2-Item 3&#034;);</li>
<li>&nbsp;</li>
<li>// $string now contains 3 items</li>
<li>print $string[0]; // would give &#039;Item 1&#039;</li>
<li>print $string[1]; // would give &#039;Item 2&#039;</li>
<li>print $string[2]; // would give &#039;Item 3&#039;</li>
</ol>
</dd>
</dl>
<p>So those are the 3 functions I use day in day out. Mainly they&#039;re used on their own but at times can be combined to produce the desired output for a string.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2006/09/09/manipulating-strings/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2006/09/09/manipulating-strings/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PHP References</title>
		<link>http://www.stuffbysarah.net/2006/07/27/php-references/</link>
		<comments>http://www.stuffbysarah.net/2006/07/27/php-references/#comments</comments>
		<pubDate>Thu, 27 Jul 2006 16:33:57 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2006/07/27/php-references/</guid>
		<description><![CDATA[No, this isn&#039;t about using references in PHP. Even I don&#039;t fully understand them yet! I figured that I write it so often on forums to people wanting to learn PHP that I&#039;d list out some recommended reading (including free stuff) here, with the low down on each. They&#039;re mainly free chapters but my argument ...]]></description>
			<content:encoded><![CDATA[<p>No, this isn&#039;t about using references in PHP. Even I don&#039;t fully understand them yet!</p>
<p>I figured that I write it so often on forums to people wanting to learn PHP that I&#039;d list out some recommended reading (including free stuff) here, with the low down on each. They&#039;re mainly free chapters but my argument is to get the free chapters and surely anyone can make up their mind after 150+ pages as to whether the book&#039;s worthwhile to buy!! I&#039;ve linked to the full book on Amazon as well, in case anyone takes my review for granted and just wants to buy the book <img src='http://www.stuffbysarah.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h3>Build Your Own Database Driven Website Using PHP &#038; MySQL &#8211; Kevin Yank</h3>
<p>This book is from SitePoint which I have to say produces some of the best books out there and offers 4 free chapters on virtually all of their books for you to download. That&#039;s over 150 pages for free! The free chapters are very worthwhile for anyone who wants to get PHP up and running on their own computer. It devotes the first chapter to installing Apache, PHP and MySQL for Windows, Linux and Mac OS X. It then teaches you how to develop your own content management system whilst explaining the various parts of PHP and MySQL as you go along. I own this book myself and find it very easy to read. The current release is also updated to work for PHP 5 as well.<br />
<a href="http://www.sitepoint.com/books/phpmysql1/" class="external">Free Chapters from SitePoint</a><br />
<a href="/amazon.php?id=0975240218" class="internal">Buy from Amazon UK</a></p>
<h3>PHP and MySQL Web Development</h3>
<p>This is a later version of the book I learnt from. It starts with the basics of PHP and doesn&#039;t jump straight into MySQL until you have a good understanding of PHP basics which I think is a good way to learn. I sat and read 500 pages of this book in a week and haven&#039;t looked back. Whilst the version I have now is outdated and not really used, they have since released 2 further versions so the current Version 3 is most likely up to date, but still a worthwhile book to try.<br />
<a href="http://www.samspublishing.com/articles/article.asp?p=340878" class="external">Sample Chapter</a><br />
<a href="http://www.amazon.co.uk/exec/obidos/redirect?link_code=as2&#038;path=ASIN/0672326728&#038;tag=webtekdesigns&#038;camp=1634&#038;creative=6738" class="external">Buy from Amazon UK</a></p>
<h3>The PHP Anthology: Object Oriented PHP Solutions &#8211; Harry Fuecks</h3>
<p>Another book from SitePoint, this PHP book is for the more advanced user that already has an understanding of PHP and MySQL. The subject goes into the world of Object Oriented Programming, explaining about classes, how to use them and how they can speed up your scripts and let you write more efficient code. The books also explore more advanced programming methods and requirements such as parsing, generating bar charts and graphs, watermarking images, creating more efficient error handling methods and much more. I own both of these books however I&#039;m still on Vol 1 at present. It is definitely for the advanced user and must be read without distractions!<br />
<a href="http://www.sitepoint.com/books/phpant1" class="external">Free Chapters from SitePoint</a><br />
<a href="/amazon.php?id=0975841998" class="internal">Buy from Amazon UK</a></p>
<h3>Php|architect&#039;s Guide to PHP Security</h3>
<p>Anyone who&#039;s seriously considering creating PHP sites and possibly working as a PHP developer professionally, and even for their own projects, needs to be reading this book. Explaining about security, how to prevent injections, attacks and hacks on your code it&#039;s a must for anyone who wants to ensure their site is absolutely secure. I&#039;ve seen (and secured) a lot of code that people naively assumed would be safe when in fact it isn&#039;t. If you don&#039;t want your sites compromised then I recommend this book for reading and keeping for reference.<br />
<a href="http://www.amazon.co.uk/exec/obidos/redirect?link_code=as2&#038;path=ASIN/0973862106&#038;tag=webtekdesigns&#038;camp=1634&#038;creative=6738" class="external">Buy from Amazon UK</a></p>
<h3>Sample Chapters</h3>
<p>The following are just links to sample chapters from various bookstores. I&#039;ve not read any of these books and so cannot offer a review, but for anyone who can&#039;t neccessarily afford to pay out for a book right now, these sample chapters between them may give you a reasonable amount of information and help too.</p>
<p><a href="http://www.oreilly.com/catalog/learnphpmysql/chapter/index.html" class="external">Learning PHP and MySQL</a><br />
<a href="http://www.oreilly.com/catalog/phpnut/chapter/index.html" class="external">PHP in a Nutshell</a><br />
<a href="http://www.oreilly.com/catalog/learnphp5/chapter/index.html" class="external">Learn PHP 5</a><br />
<a href="http://www.oreilly.com/catalog/phpckbk/chapter/index.html" class="external">PHP Cookbook</a><br />
<a href="http://www.oreilly.com/catalog/webdbapps2/chapter/index.html" class="external">Web Database Applications with PHP and MySQL</a><br />
<a href="http://www.oreilly.com/catalog/progphp2/chapter/index.html" class="external">Programming PHP</a><br />
<a href="http://www.samspublishing.com/articles/article.asp?p=170294" class="external">Advanced PHP Programming Sample 1</a><br />
<a href="http://www.samspublishing.com/articles/article.asp?p=170279" class="external">Advanced PHP Programming Sample 2</a></p>
<h3>Online Resources</h3>
<p><a href="http://hudzilla.org/phpwiki/index.php?title=Main_Page" class="external">Practical PHP Programming</a> &#8211; by Paul Hudson</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2006/07/27/php-references/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2006/07/27/php-references/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Portable PHP</title>
		<link>http://www.stuffbysarah.net/2006/07/15/portable-php/</link>
		<comments>http://www.stuffbysarah.net/2006/07/15/portable-php/#comments</comments>
		<pubDate>Sat, 15 Jul 2006 12:16:14 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2006/07/15/portable-php/</guid>
		<description><![CDATA[I had a call yesterday off someone I&#039;ve done some PHP work for. He had set up a site with an eCard on it and just found an eCard script to deal with the mailing. Quite fine you&#039;d assume. He had it working on his server fine. Then he moved it to the client&#039;s server ...]]></description>
			<content:encoded><![CDATA[<p>I had a call yesterday off someone I&#039;ve done some PHP work for. He had set up a site with an eCard on it and just found an eCard script to deal with the mailing. Quite fine you&#039;d assume. He had it working on his server fine. Then he moved it to the client&#039;s server and it stopped working. Over the phone I made a few obvious suggestions, does the mail() function work? Try a simple test of a hardcoded straightforward mail:</p>
<dl class="code">
<dt>Email Code</dt>
<dd>
<ol>
<li>&lt;?php mail(&#034;test@yourdomain.com&#034;, &#034;This is a quick test&#034;, &#034;testing 1 2 3&#034;, &#034;From: test@yourdomain.com&#034;); ?&gt;</li>
</ol>
</dd>
</dl>
<p>I also suggested the from address must be a valid email address on the server, as the server may have security in place to prevent it being sent from a non server address. Also, after this morning, I&#039;ve discovered that even a valid email address could have DNS issues with some servers, so if one doesn&#039;t work, try another too!</p>
<p>Anyhow, he came back to me and said the mail function worked fine, so I FTP&#039;d in and took a look at the code. At first glance it seemed fine enough. Pretty shabby PHP but nothing giving a reason for it not to work. I took a look at the web page again and then noticed it wasn&#039;t picking up the to and from email addresses. A second, more serious look made me notice the script assumed that <a href="http://uk.php.net/manual/en/security.globals.php" class="external">Registered Globals</a> were on, a major no no as a lot of servers have the default installation of PHP which switches them off, or servers deliberately ensure they&#039;re off for security. So I ran through, updated the variables to use the $_POST array and voila, it worked.</p>
<p>So for future reference, if you want to write PHP code, write it properly from the beginning! Don&#039;t assume options such as registered globals are available to you. Using $_GET, $_POST, $_FILE etc will work fine regardless of whether registered globals are on or off, and it&#039;s far more secure to use this method.</p>
<p>Also whilst talking about portable PHP&#8230;</p>
<p>Use proper opening tags ie. <strong>&lt;?php</strong> and not just <strong>&lt;?</strong>.</p>
<p>Don&#039;t assume <a href="http://uk2.php.net/magic_quotes" class="external">Magic Quotes</a> are on, and to be honest, if they are, reverse their work and use a more <a href="/blog/2006/03/18/secure-php-and-sql-injections/" class="internal">secure method</a>.</p>
<p>At least if you cover these portability issues, then when things don&#039;t work as planned you can rule them out as issues and turn to other options.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2006/07/15/portable-php/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2006/07/15/portable-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure PHP and SQL Injections</title>
		<link>http://www.stuffbysarah.net/2006/03/18/secure-php-and-sql-injections/</link>
		<comments>http://www.stuffbysarah.net/2006/03/18/secure-php-and-sql-injections/#comments</comments>
		<pubDate>Sat, 18 Mar 2006 21:48:05 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>
		<category><![CDATA[PHP Security]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2006/03/18/secure-php-and-sql-injections/</guid>
		<description><![CDATA[I spent the last 1-2 weeks upgrading a site for a client and also securing it. How are a lot of PHP sites compromised? Well the point I&#039;m looking it in this post is via forms and user entered data. There are many other security issues as well, this is just one of them. More ...]]></description>
			<content:encoded><![CDATA[<p>I spent the last 1-2 weeks upgrading a site for a client and also securing it. How are a lot of PHP sites compromised? Well the point I&#039;m looking it in this post is via forms and user entered data. There are many other security issues as well, this is just one of them. More commonly known as SQL Injections. <a href="http://www.php.net" class="external">PHP.net</a> has a good page on this subject explaining <a href="http://www.php.net/manual/en/security.database.sql-injection.php" class="external">SQL Injection</a> giving real life examples. As per their description:</p>
<blockquote><p>Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query.</p></blockquote>
<p>So what does this mean? When you have a form on a page requesting user input and then use this input in MySQL queries you must not rely on what the user has entered. 99% of the time when you ask a user for their username and password, they will enter this. However along comes someone who wants to crack your system, suddenly you won&#039;t be receiving a username and password through the form but most likely code aimed to inject extra operations into your MySQL query. Perhaps it&#039;s easier to understand by way of example.  My own logins usually accept a username and password from a form. The usual method is to accept a username and password and then run a SELECT statement to count the number of records that contain both the username and password. If the result is zero then the username and/or password is of course incorrect. A loosely written PHP script could be:</p>
<dl class="code">
<dt>Insecure code to control user login</dt>
<dd>
<ol>
<li>$sql = mysql_query(&#034;SELECT COUNT(*) FROM users WHERE username = &#039;&#034;.<strong>$_POST['username']</strong>.&#034;&#039; AND password = &#039;&#034;.<strong>$_POST['password']</strong>.&#034;&#039;&#034;);</li>
<li>$count = mysql_fetch_row($sql);</li>
<li>if ($count[0] == 0) {</li>
<li class="indent1">// user/password combo incorrect</li>
<li class="indent1">$errormsg = &#034;Your Username and/or Password are incorrect. Please try again&#034;;</li>
<li>} else {</li>
<li class="indent1">// user/password combo correct proceed with login</li>
<li class="indent1">header(&#034;Location:http://www.domain.com/secret/logged-in.php&#034;);</li>
<li class="indent1">exit;</li>
<li>}</li>
</ol>
</dd>
</dl>
<p>As you can see from the above, the user input from the $_POST array is entered straight into the query. Oh and</p>
<dl class="code">
<dt>Insecure code to control user login</dt>
<dd>
<ol>
<li>$username = $_POST['username'];</li>
<li>$password = $_POST['password'];</li>
<li>$sql = mysql_query(&#034;SELECT COUNT(*) FROM users WHERE username = &#039;&#034;.<strong>$username</strong>.&#034;&#039; AND password = &#039;&#034;.<strong>$password</strong>.&#034;&#039;&#034;);</li>
<li>&#8230;</li>
</ol>
</dd>
</dl>
<p>is no different <img src='http://www.stuffbysarah.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>So how can this be an issue? Well, all of your registered users will most likely enter their username and password. No issue there. Your MySQL statement would look like this:</p>
<dl class="code">
<dt>SQL Statement</dt>
<dd>
<ol>
<li>SELECT COUNT(*) FROM users WHERE username = &#039;sarah&#039; AND password = &#039;sunshine&#039;</li>
</ol>
</dd>
</dl>
<p>However, a visitor wanting to crack your system could enter the following information:</p>
<blockquote><p>
username: sarah<br />
password: &#039; or &#039;1&#039;=&#039;1
</p></blockquote>
<p>Which would give:</p>
<dl class="code">
<dt>SQL Injection Code</dt>
<dd>
<ol>
<li>SELECT COUNT(*) FROM users WHERE username = &#039;sarah&#039; AND password = &#034; or &#039;1&#039; = &#039;1&#039;</li>
</ol>
</dd>
</dl>
<p>The above would return the total number of records in the table. So going by the very loosely written PHP script above, the if statement of</p>
<dl class="code">
<dt>IF Statement</dt>
<dd>
<ol>
<li>if ($count[0] == 0) {</li>
<li class="indent1">&#8230;</li>
<li>} else {</li>
<li class="indent1">&#8230;</li>
<li>}</li>
</ol>
</dd>
</dl>
<p>would provide a value from $count[0] to be above zero (providing there were records in the table), thus giving someone a login without a proper username or password.</p>
<p>Okay so yes, the example is a highly unsecure example, but it does happen. Plenty of people believe that providing there is no direct link to a file on a server, it won&#039;t be found out. Trouble is it can be. So pulling the above example apart the first steps security would be</p>
<p>1. Ensure all restricted pages check that the member is logged in by using cookies or sessions or both.<br />
2. Switch the if statement to ensure that only one record is found and allow the user to log in from that, otherwise assume the username/password is wrong and prevent the login.<br />
3. Escape the user entered data.</p>
<p>At this point I&#039;ll briefly mention <a href="http://www.php.net/magic_quotes" class="external">Magic Quotes</a> which is a setting in the php configuration file that can be set to on or off. If set to on then it will escape all user entered data, using the same method as the function <a href="http://www.php.net/addslashes" class="external">addslashes()</a>. It was introduced due to the amount of people who don&#039;t escape their user entered data, however it causes nightmares for most PHP developers and is even stated on the PHP.net site that most developers will choose to turn it off, preferring to escape the data when required. However on most shared hosting it&#039;s not necessarily easy to do this as you have no control over the php.ini file, so the best way is to check to see if Magic Quotes are on, clean the variable if they are (using <a href="http://www.php.net/stripslashes" class="external">stripslashes()</a> function) and then escape the variable. The function that I use (courtesey of <a href="http://www.jellyandcustard.com" class="external">Khalid</a> is:</p>
<dl class="code">
<dt>escapeString Function</dt>
<dd>
<ol>
<li>function escapeString($string) {</li>
<li class="indent1">if (get_magic_quotes_gpc()) $string = stripslashes($string);</li>
<li class="indent1">return mysql_real_escape_string($string);</li>
<li>}</li>
</ol>
</dd>
</dl>
<p>Here this function uses the <a href="http://www.php.net/mysql_real_escape_string" class="external">mysql_real_escape_string()</a> built in function. The function will add a backslashes to the beginning of any of the characters \x00, \n, \r, \, &#039;, &#034; and \x1a. This will protect you from any SQL injections thus protecting your database.</p>
<p>However don&#039;t be fooled into thinking that when I say &#034;user entered data&#034; that I just mean text inputs. Going back to the site I secured last week the original developers had not thought about a couple of issues, which could be have been used in conjunction with one another and allowed someone to wreak havoc on the site or in the database. Considering the site accepted money this is even more important to ensure its security. What was wrong?</p>
<p>Firstly they were storing the user&#039;s id and password in cookies. Not necessarily a problem however they were then taking the raw data from the cookies and using it to query the database. Cookies can be edited therefore must be escaped. Then some user entered data was being escaped (but not as securely as the function above will do) but other data wasn&#039;t. The site had even had a security update before me and there was still an emerging pattern. When a page had some secured data on it, the unsecured data wasn&#039;t secured because the form variables were from checkboxes, radio buttons or a select list. I admit, when I first start out writing PHP I figured that this information couldn&#039;t be tampered with therefore didn&#039;t require securing. However take a normal form that&#039;s there for people to complete and the details go into a database. A questionnaire for example. Plenty of input boxes, radio buttons, check boxes and select lists. The form is submitted to perhaps the same page or another page. We know full well that another completely unrelated site could submit to that php script as well. Take the same form names, which are plain to see in the HTML source, but then instead of a radio button having a prespecified value suddenly someone could submit to the processing script a radio button with their own value.</p>
<p>The simple rule is, never trust data that could have been tampered with. If it&#039;s coming from $_GET, $_POST, $_COOKIE or even $_SERVER (after all if the user agent or http referrer can be altered who knows what it would be altered to?) then escape it. These are the 4 I deal with, if there are any further global arrays that should be escaped feel free to add to this list.</p>
<p>For people who use ASP, this <a href="http://www.sitepoint.com/article/sql-injection-attacks-safe" class="external">Site Point article</a> will be of use.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2006/03/18/secure-php-and-sql-injections/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2006/03/18/secure-php-and-sql-injections/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Learn PHP: Selecting from a Database</title>
		<link>http://www.stuffbysarah.net/2006/02/26/learn-php-selecting-from-a-database/</link>
		<comments>http://www.stuffbysarah.net/2006/02/26/learn-php-selecting-from-a-database/#comments</comments>
		<pubDate>Sun, 26 Feb 2006 20:30:12 +0000</pubDate>
		<dc:creator>Sarah</dc:creator>
				<category><![CDATA[Learn PHP]]></category>

		<guid isPermaLink="false">http://www.stuffbysarah.net/2006/02/26/learn-php-selecting-from-a-database/</guid>
		<description><![CDATA[Probably one of the most used MySQL commands is SELECT. This lets you select information out of a database table. If you take the table created in the previous post, and use phpMyAdmin to insert a few records to give us something to play with. So to get PHP to work with MySQL you need ...]]></description>
			<content:encoded><![CDATA[<p>Probably one of the most used MySQL commands is <a href="http://dev.mysql.com/doc/refman/4.1/en/retrieving-data.html" class="external">SELECT</a>. This lets you select information out of a database table. If you take the table created in the previous post, and use phpMyAdmin to insert a few records to give us something to play with.</p>
<p>So to get PHP to work with MySQL you need to first of all tell PHP how to connect to it. In configuring phpMyAdmin (alternatively if you&#039;re using it online) you should have a username and password. 9/10 times you&#039;ll connect as well to the host &#034;localhost&#034;. Unless you&#039;re running MySQL on a different server this should be fine for you. So to test your connection details create a file with the following code:<br />
<span id="more-292"></span><br />
[source:php]< ?php<br />
// first we need to connect to the database<br />
mysql_connect("localhost", "username", "password") or die("Error connecting to MySQL: ".mysql_error());<br />
?><br />
[/source]</p>
<p>This is a simple connection to test your host, username and password. You need to run mysql_connect() once on a page, when you need to connect to a database. I say once on a page as it doesn&#039;t have to be at the start of the page, it can be run when it&#039;s first needed, however I seriously advise against running the function more than once in a page else your visitors will start to use up the MySQL connections allowed and you will overload the MySQL server (and your host won&#039;t be too happy!). I tend to run the connection at the top of any page that requires it so that I know it&#039;s run and I don&#039;t have to run it again during the page code. Of course in the code above you need to replace username and password with your own preset username and password for MySQL.</p>
<p>To explain the die() function. This will run if there is an error. If the first function is not successful then it will kill the script dead in its tracks. I&#039;ve added in a short string so you realise where the error occurs (on a page with many mysql queries etc it can be like finding a need in a haystack!) along with the use of another function mysql_error(). This function prints out the error returned by MySQL to help you debug your code.</p>
<p>If the host, username and password are correct then you shouldn&#039;t see an error. In fact you shouldn&#039;t see anything if it works, just a blank screen. If you do get an error then you will have to check the username and password are correct and that your host is correct too. MySQL connections are automatically closed when the page has been parsed, executed and displayed, so don&#039;t worry, there&#039;s no connections being left open here <img src='http://www.stuffbysarah.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Once that&#039;s working you want to ensure you can select a database and query a table, so to expand on the above:</p>
<p>[source:php]< ?php<br />
// first we need to connect to the database<br />
mysql_connect("localhost", "username", "password") or die("Error connecting to MySQL: ".mysql_error());<br />
// then select the database<br />
mysql_select_db("mydb") or die("Error selecting database: ".mysql_error());<br />
// now query the database<br />
$sql = mysql_query("SELECT * FROM content") or die("Error connecting to table: ".mysql_error());<br />
?><br />
[/source]</p>
<p>So the above, as the comments say, first connects to MySQL, then it selects which database to use using the mysql_select_db() function. Finally it uses the mysql_query() function with the most basic form of the SELECT statement to retrieve all content from the database and store it in the variable $sql. At this point the script doesn&#039;t really do anything productive so what you need to do is extend it further.</p>
<p>We know that the database has the fields rowid, firstname, surname, address and postcode. So we use these to retrieve data from the result in the $sql variable as below:</p>
<p>[source:php]< ?php<br />
// first we need to connect to the database<br />
mysql_connect("localhost", "username", "password") or die("Error connecting to MySQL: ".mysql_error());<br />
// then select the database<br />
mysql_select_db("mydb") or die("Error selecting database: ".mysql_error());<br />
// now query the database<br />
$sql = mysql_query("SELECT * FROM content") or die("Error connecting to table: ".mysql_error());<br />
// now display the information using a while loop<br />
while ($rowdetail = mysql_fetch_array($sql)) {<br />
       print "
<p>Name: &#034;.$rowdetail['firstname'].&#034; &#034;.$rowdetail['surname'].&#034;<br />\n&#034;;<br />
       print &#034;Address: &#034;.$rowdetail['address'].&#034;<br />\n&#034;;<br />
       print &#034;Postcode: &#034;.$rowdetail['postcode'].&#034;\n&#034;;<br />
       print &#034;<br />
<hr />\n&#034;;<br />
}<br />
?><br />
[/source]</p>
<p>This will then produce a list of results along the lines of</p>
<blockquote><p>
Name: John Smith<br />
Address: 1 New Street, Any Town, Some County, England<br />
Postcode: NS1 3FG</p>
<hr />
Name: Mary Jones<br />
Address: 22 Wood Road, London, Greater London<br />
Postcode: W4 3KF</p>
<hr /></blockquote>
<p>So how does it work? The while loop, as explained <a href="http://www.sarahfreelance.co.uk/2006/01/28/the-php-while-loop/" class="external">previously</a>, runs whilst the condition is true. So in this instance it is saying whilst there is a row to &#039;fetch&#039; then run the following set of statements. To retrieve the table row details I&#039;ve used this line:</p>
<p>[source:php]$rowdetail = mysql_fetch_array($sql)[/source]</p>
<p>As explained on the PHP.net site, <a href="http://uk2.php.net/mysql_fetch_array" class="external">mysql_fetch_array()</a> <em>Returns an array that corresponds to the fetched row and moves the internal data pointer ahead</em>. It stores the details into the array variable $rowdetail. The array indexes are then defined by the fieldnames of the table. As you can see the print statements then just print the information out using each index. Once all statements are executed it then repeats until all rows have been displayed.</p>
<p>This is the most straightforward method of database retrieval. You can display the information and also choose which information you like as you like (in this case I didn&#039;t bother using the rowid). It can be displayed in an XHTML table, a list or however you wish.</p>
<p>So what else can you do with the SELECT statement? Well there are plenty of options available. I&#039;ll only touch on the basics and advance as and when required. So options available at this point are:</p>
<p>[source:sql]<br />
// select all rows and details with no conditions<br />
SELECT * FROM content<br />
// select just the firstname and surname<br />
SELECT firstname, surname FROM content<br />
// select all rows where the surname is Jones<br />
SELECT * FROM content WHERE surname LIKE &#039;Jones&#039;<br />
// select all rows where the surname contains &#034;Mac&#034; &#8211; here we use the wildcard % to match part of a string<br />
SELECT * FROM content WHERE surname LIKE &#039;%Mac%&#039;<br />
// select all rows and put in alphabetical order of the surname<br />
SELECT * FROM content ORDER BY surname ASC<br />
// select just the first 5 rows of the table<br />
SELECT * FROM content LIMIT 5<br />
// select just the first 3 rows of the table after the first 2 (so rows 3-5)<br />
SELECT * FROM content LIMIT 2, 3<br />
// select rows where the firstname contains sam and the surname contains mac<br />
SELECT * FROM content WHERE firstname LIKE &#039;%sam%&#039; AND surname LIKE &#039;%mac%&#039;<br />
// now put a whole select statement together<br />
SELECT firstname, surname FROM content WHERE surname LIKE &#039;%mac%&#039; ORDER BY firstname ASC LIMIT 30<br />
[/source]</p>
<p>using the previous PHP example, if you only want to retrieve one record from the table then you do not need to use the while loop but just the mysql_fetch_array() function on it&#039;s own ie.</p>
<p>[source:php]<br />
< ?php<br />
// first we need to connect to the database<br />
mysql_connect("localhost", "username", "password") or die("Error connecting to MySQL: ".mysql_error());<br />
// then select the database<br />
mysql_select_db("mydb") or die("Error selecting database: ".mysql_error());<br />
// now query the database<br />
$sql = mysql_query("SELECT * FROM content WHERE surname LIKE '%mac%' LIMIT 1") or die("Error connecting to table: ".mysql_error());<br />
// save information into the array $rowdetail<br />
$rowdetail = mysql_fetch_array($sql);<br />
// print the information out on the page<br />
print "
<p>Name: &#034;.$rowdetail['firstname'].&#034; &#034;.$rowdetail['surname'].&#034;<br />\n&#034;;<br />
print &#034;Address: &#034;.$rowdetail['address'].&#034;<br />\n&#034;;<br />
print &#034;Postcode: &#034;.$rowdetail['postcode'].&#034;\n&#034;;<br />
?><br />
[/source]</p>
<p>As you can see the above is virtually the same except that you only need to retrieve an array once so there is no requirement for the While loop.</p>
<p>That&#039;s probably the most used MySQL statement in web page development. It may not seem like it now but that statement is all you usually need to use on a typical database driven web site.</p>

<script src="http://feeds.feedburner.com/~s/StuffBySarah?i=http://www.stuffbysarah.net/2006/02/26/learn-php-selecting-from-a-database/" type="text/javascript" charset="utf-8"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.stuffbysarah.net/2006/02/26/learn-php-selecting-from-a-database/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

