<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
	<channel>
			<title>Tagged with "php"</title>
			<link>http://www.addedbytes.com/feeds/tag-feed/</link>
			<description></description>
			<language>en</language>
			<copyright>Added Bytes - Brighton Web Application Development 2006</copyright>
			<ttl>120</ttl>
			<item>
				<title>If PHP Were British</title>
				<link>http://www.addedbytes.com/blog/if-php-were-british/</link>
				<description><![CDATA[ <p>When <a href="http://toys.lerdorf.com/">Rasmus Lerdorf</a> first put <a href="http://www.php.net/">PHP</a> together, he - quite sensibly, despite his heritage - chose not to write it in Greenlandic or Danish. Good job too - that would have been rather unpleasant to work with.</p> <p>When <a href="http://toys.lerdorf.com/">Rasmus Lerdorf</a> first put <a href="http://www.php.net/">PHP</a> together, he - quite sensibly, despite his heritage - chose not to write it in Greenlandic or Danish. Good job too - that would have been rather unpleasant to work with. He opted instead, being in Canada at the time, for the local tongue. No, not French - that bastard dialect of the Queen's English commonly referred to as "US English"<sup><a href="blog/if-php-were-british/#note1" id="notelink1">1</a></sup>.</p>

<p>PHP developers in Britain have been grumpy about this ever since. What was he thinking? And more importantly, how do we undo this travesty? How do we developers ensure the traditions of the British Empire continue to be upheld, even in the digital age?</p>

<h3>A Slap in the Face</h3>

<pre class="php">$variable_name</pre>

<p>The first, but maybe the most important, of many changes that will allow PHP to achieve a more elegant feel is to remove that symbol so beloved by the US and replace it with something altogether more refined. More solid. More ... sterling.</p>

<pre class="php">£variable_name</pre>

<h3>Getting Started</h3>

<pre class="php">&lt;?php
    echo 'Hello World!';
?&gt;</pre>

<p>How many of today's British programmers have been put off at the outset by the brazen informality of this simple yet obscenely Americanised program, colloquially referred to as "Hello World"? A more Imperial, formal introduction might encourage a greater proportion of young British talent to remain with the language and thus give the broader community a more urbane air.</p>

<pre class="php">&lt;?php
    announce 'Good morrow, fellow subjects of the Crown.';
?&gt;</pre>

<h3>Abbreviations</h3>

<p>Few things are more abhorrent to the British than unnecessary abbreviations. "Text speak" is unheard of on the streets of London, as the natural ingrained British grammarian simply refuses to stoop to sending messages of the "c u soon traffic kthxbye" variety, instead proferring something altogether more elegant: "Dear Sir/Madam. I will arrive as soon as time allows, which I expect to be within the hour. I assure you the horses shall not be spared. Yours respectfully." (slower to type, yes, but we do not like to be rushed).</p>

<p>PHP, on the other hand, is full to bursting with abbreviations and acronyms which are entirely unnecessary:</p>

<pre class="php">str_replace()
is_int()
var_dump()
preg_match()
json_encode()
mysql_connect()</pre>

<p>The following changes should improve things:</p>

<pre class="php">string_replace()
is_integer()
variable_dump()
perl_regular_expression_match()
javascript_object_notation_encode()
my_structured_query_language_connect()</pre>

<p><em>Edit: I have corrected the expansion of "preg_match" - thanks to those who pointed it out.</em></p>

<h3>Eloquence</h3>

<pre class="php">if ($condition) {
    // Code here
} else {
    // Code here
}</pre>

<p>Shakespeare would be ashamed to see his native tongue twisted into this monstrosity. Brevity is to be applauded in the right context - in some dark corner, where it shall be seldom seen - but not here. The if ... else block is the most used conditional code in all of PHP, so it must be made as inoffensive as possible. There are many options for its replacement, but this may be the strongest:</p>

<pre class="php">perchance (£condition) {
    // Code here
} otherwise {
    // Code here
}</pre>

<p>The same naturally applies to the Americanised switch ... case construct, which one can only describe as clunky and unpleasant:</p>

<pre class="php">switch ($variable) {
    case $option1:
        //Code here
        break;
    case $option2:
        //Code here
        break;
    default:
        //Code here
        break;
}</pre>

<p>Words such as "switch", "break" and "default" are hard on the reader and lack context. The Right Honorable <a href="http://www.reddit.com/r/proper/comments/jp1yf/for_the_consideration_of_my_most_respectable/c2dz9zc">biggerthancheeses</a> was kind enough to contribute a more gentrified suggestion (and has some interesting ideas, particularly around replacement of "include()" with something like "i_might_be_partial_to()", demonstrating a natural talent for the Imperialisation of programming languages):</p>

<pre class="php">what_about (£variable) {
    perhaps £possibility:
        //Code here
        splendid;
    perhaps £other_possibility:
        //Code here
        splendid;
    on_the_off_chance:
        //Code here
        splendid;
}</pre>

<h3>Spelling</h3>

<pre class="php">imagecolorallocate()
serialize()
newt_centered_window()
connection_status()</pre>

<p>Words fail me at this point. How is any self-respecting gentleman expected to make head or tail of these "words". It beggars belief that anyone could allow such distortions of words to be entered into a programming language. They, along with the cornucopia of similar errors, should be reverted to their proper forms immediately:</p>

<pre class="php">imagecolourallocate()
serialise()
newt_centred_window()
connexion_status()<sup><a href="blog/if-php-were-british/#note2" id="notelink2">2</a></sup></pre>

<h3>Manners</h3>

<pre class="php">try {
    // Code here
} catch (Exception $e) {
    // Handle exception
    die('Message');
}</pre>

<p>The try ... catch block is an excellent example of PHP's lack of manners. Far too direct to be allowed in the new PHP. Additionally, the word "die" is so very depressing. This new block, although more verbose, is vastly more polite and upbeat:</p>

<pre class="php">would_you_mind {
    // Code here
} actually_i_do_mind (Exception £e) {
    // Politely move on
    cheerio('Message');
}</pre>

<h3>Class</h3>

<p>Perhaps nothing is as important and ingrained in the British psyche as the notion of class and, while there are few opportunities for change within this part of PHP, the changes that there are to be made here are important.</p>

<pre class="php">class Republic {
    public $a;
    private $b;
    protected $c;
}
$example = new Republic;</pre>

<p>To begin with, the current system has no place for class hierarchy and this is unacceptable. So we shall begin by giving classes specific levels - upper, middle, working - and no class can access the methods of one of a higher level without the explicit permission of the higher order class (of course, though it might then have access, it would not be a true member of the higher order and could not itself grant higher order access to other lower order classes). "Public" and "Private", in the British class system, are often synonymous (see, for example, school system nomenclature), so these must be adjusted, as should the "Protected" property visibility. The word "new", while passable, has a much more appropriate replacement in matters of class.</p>

<pre class="php">upper_class Empire {
    state £a;
    private £b;
    hereditary £c;
}
£example = nouveau Empire;</pre>

<h3>The Sun Never Sets ...</h3>

<p>It is hoped that these few simple changes will improve the reputation and status of PHP among other languages. No longer will it be the poor American cousin - instead it can take its rightful place as the - British - King of the scripting languages.</p>

<h3>Thanks</h3>

<p>Many thanks to <a href="https://twitter.com/#!/markwallman">Mark</a> and <a href="https://twitter.com/#!/bluevurt">Pat</a>, colleagues at <a href="http://www.gsba.co.uk/">GSBA</a>, who started this resurrection of the British Empire in the pub on Friday.</p>

<p><a href="blog/if-php-were-british/#notelink1" id="note1">1</a>. Ok, the neighbouring local tongue.</p>

<p><a href="blog/if-php-were-british/#notelink2" id="note2">2</a>. Yes, <a href="http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences#-xion.2C_-ction">connexion</a>.</p> <br><br>]]></description>
				<pubDate>Sat, 20 Aug 2011 06:28:21 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/blog/if-php-were-british/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=development&amp;start=0" class="ditto_tag" rel="tag">development</a>,<a href="/feeds/tag-feed/?tags=empire&amp;start=0" class="ditto_tag" rel="tag">empire</a>,<a href="/feeds/tag-feed/?tags=humour&amp;start=0" class="ditto_tag" rel="tag">humour</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>
			</item>

			<item>
				<title>Writing Secure PHP, Part 4</title>
				<link>http://www.addedbytes.com/writing-secure-php/writing-secure-php-4/</link>
				<description><![CDATA[ The fourth part of the <a href="http://www.addedbytes.com/writing-secure-php/">Writing Secure PHP</a> series, covering cross-site scripting, cross-site request forgery and character encoding security issues. <p>In <a href="http://www.addedbytes.com/php/writing-secure-php/">Writing Secure PHP</a>, <a href="http://www.addedbytes.com/security/writing-secure-php-2/">Writing Secure PHP, Part 2</a> and <a href="http://www.addedbytes.com/security/writing-secure-php-3/">Writing Secure PHP, Part 3</a> I covered many of the common mistakes PHP developers make, and how to avoid some potential security problems. This article covers some of the more advanced security problems common to PHP on the web.</p>

<h3>Cross-Site Scripting (XSS)</h3>

<p>Cross-site scripting (often abbreviated to XSS) is a form of injection, where an attacker finds a way to have the target site display code they control. In its most basic form, this can be as simple as a site that allows HTML characters in usernames, where someone can specify a username like:</p>

<pre class="php">DaveChild&lt;script type="text/javascript" src="http://www.example.com/my_script.js"&gt;&lt;/script&gt;</pre>

<p>Now, whenever someone sees my username on the target site, the script I've added to my username will run. I could potentially use this to grab the person's login information, log their keystrokes - any number of nefarious activities.</p>

<p>As a developer, you can combat this type of attack by encoding or removing HTML characters (watch out for character encoding issues, as outlined next). Even better than stripping out unwanted characters is to allow a whitelist of safe characters in usernames and other fields. Be especially careful with e-commerce sites where you are listing orders in a CMS - an XSS vulnerability may allow an attacker to gain administrative access to your CMS. It is also important to turn off TRACE and TRACK support on the server, as if there is a vulnerability (and always assume that despite your best efforts there will be) these potentially allow an attacker to steal a user's cookie.</p>

<p>As a user you are also vulnerable to this sort of attack, and it is very difficult, at the moment, to make yourself safe against it. Vigilance is key, and to that end I have released a <a href="http://www.addedbytes.com/tools/xss-alarm-userscript/">userscript that warns you about third party scripts</a> (for users of GreaseMonkey, Opera or Chrome).</p>

<h3>Cross-Site Request Forgery (CSRF)</h3>

<p>Despite the similar name, CSRF is unconnected to XSS. CSRF is a form of attack where an authenticated user performs an action on a site without knowing it.</p>

<p>Let's assume that Jack is logged in to his bank, and has a cookie stored on his computer. Each time he sends an HTTP request to the bank (i.e., views a page or an image on a page) his browser sends the cookie along with the request so that the bank knows that it's him making the request.</p>

<p>Jill, meanwhile, runs a different website and has managed to get Jack to visit it. One of the items on the page is in fact loaded from the bank, for example in an iframe. The URL of the iframe or request contains instructions to the bank to transfer money from Jack's account to Jill's. Because the request is coming from Jack's computer, and includes his cookie, the bank assumes it is a legitimate request and the money is transferred.</p>

<p>This type of attack is extremely dangerous and virtually untracable. As a developer, your job is to protect against it, and the best way to do that is to remember <a href="http://www.addedbytes.com/php/writing-secure-php/">Rule Number One: Never, Ever Trust Your Users</a>. No matter how authenticated they are, do not assume every request was intended.</p>

<p>In practical PHP terms, you can combat CSRF with several relatively simple coding habits. Never let the user do anything with a GET request - always use POST. Confirm actions before performing them with a confirmation dialog on a separate page - and make sure <em>both</em> the original action button or link <em>and</em> the confirmation were clicked. Even better, have the user enter information like letters from their password on the confirmation page.</p>

<p>Add a randomly generated token to forms and verify its presence when a request is made. Use <a href="http://javascript.internet.com/page-details/break-frames.html">frame-breaking JavaScript</a>. Time-out sessions with a short timespan (think minutes, not hours). Encourage the user to log out when they've finished. Check the HTTP_REFERER header (it can be hidden, but is still worth checking as if it is a different domain to that expected it is definitely a CSRF request).</p>

<h3>Character Encoding</h3>

<p>Character encoding in PHP and associated database systems is worthy of its own series. In any one request, there may be more different character encodings in use than you might think.</p>

<p>For example, a single request and response (uploading a file to a server and writing information to a database) may involve all of the following differently items with different character encodings: the HTTP request headers, post data, PHP's default encoding, the PHP MySQL module, MySQL's default set, the set of each table being used, a file being opened and read, a new file being created and written, the response headers and the response body.</p>

<p>English-speaking developers generally don't have much cause to get embroiled in character encoding issues, and that results in a lot of developers with a serious lack of understanding of how character encodings work and fit together. For those that do have a reason to look at character encodings, usually that interest ends with the setting of the response's character set.</p>

<p>However, character sets are a fundamental part of all web development. English alone can exist in any one of a wide variety of sets, and developers are usually familiar with the most common two: ISO-8859-1 and UTF-8. Fewer are familiar with UCS-2, UTF-16 or windows-1252. Still fewer are familiar with commonly used alternative language sets (e.g, GB2312 for Chinese).</p>

<p>Which, in a very roundabout way, brings me on to the security pitfalls of character encodings. Where data is processed by PHP using one character set, but a database server uses a different character set, a character (or series of characters) deemed safe by PHP may in fact allow SQL injection against the database.</p>

<p>PHP security expert Chris Shiflett <a href="http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string">has written about this issue</a> and included an example of how it can be exploited to allow SQL injection even where input is sanitized using addslashes().</p>

<p>The solution is to always <em>always</em> use mysql_real_escape_string() rather than addslashes() (or use prepared statements / stored procedures), and to explicitly state character sets at all stages of interaction. Ideally, use the same character set throughout your system (UTF-8 is recommended) and where PHP allows you to specify a character encoding for a function (e.g., htmlspecialchars() or htmlentities()), make use of it.</p>

<p>It's not just SQL that's vulnerable as a result of character encoding bugs. Cross-site scripting is possible even where HTML characters are escaped if character sets are not handled properly. Fortunately, once again that is simple to avoid by properly setting character encodings at all stages of the process and specifying character encoding for functions where possible.</p> <br><br>]]></description>
				<pubDate>Thu, 11 Sep 2008 12:11:14 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/writing-secure-php/writing-secure-php-4/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=code&amp;start=0" class="ditto_tag" rel="tag">code</a>,<a href="/feeds/tag-feed/?tags=coding&amp;start=0" class="ditto_tag" rel="tag">coding</a>,<a href="/feeds/tag-feed/?tags=development&amp;start=0" class="ditto_tag" rel="tag">development</a>,<a href="/feeds/tag-feed/?tags=mysql&amp;start=0" class="ditto_tag" rel="tag">mysql</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=programming&amp;start=0" class="ditto_tag" rel="tag">programming</a>,<a href="/feeds/tag-feed/?tags=security&amp;start=0" class="ditto_tag" rel="tag">security</a>,<a href="/feeds/tag-feed/?tags=tips&amp;start=0" class="ditto_tag" rel="tag">tips</a>,<a href="/feeds/tag-feed/?tags=tutorial&amp;start=0" class="ditto_tag" rel="tag">tutorial</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdesign&amp;start=0" class="ditto_tag" rel="tag">webdesign</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>
			</item>

			<item>
				<title>RSS to iCal</title>
				<link>http://www.addedbytes.com/blog/rss-to-ical/</link>
				<description><![CDATA[ <p>I have been looking for a way to convert the BBC weather feed for my area to iCal, so I can subscribe to it. It's date-based, after all, and RSS never seemed to me to be an appropriate format for subscribing to weather information. iCal always struck me as being "better" for that purpose.</p> <p>I have been looking for a way to convert the BBC weather feed for my area to iCal, so I can subscribe to it. It's date-based, after all, and RSS never seemed to me to be an appropriate format for subscribing to weather information. iCal always struck me as being "better" for that purpose. Of course, the BBC only have an RSS feed for local weather. What I needed was a converter.</p>

<p>After some hunting, I discovered that Dean Sanvitale had written a PHP script to convert RSS feeds to iCal format. However, his site (codent.com) appears to be long since abandoned and the script is no longer available from there. Fortunately, the Wayback Machine did have a copy. Dean originally released the script under a <a href="http://creativecommons.org/licenses/by-sa/1.0/">Creative Commons License</a> which, fortunately, allows me to make the script available to download from this site (note: the script is available from this site under the same license).</p>

<p>So, if you're looking for a way to convert an RSS feed to iCal, this PHP script will do the job. Thanks Dean!</p>

<p>Source: <a href="http://www.addedbytes.com/rss2ical.txt">rss2ical.txt</a></p> <br><br>]]></description>
				<pubDate>Thu, 19 Oct 2006 11:14:16 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/blog/rss-to-ical/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=bbc&amp;start=0" class="ditto_tag" rel="tag">bbc</a>,<a href="/feeds/tag-feed/?tags=code&amp;start=0" class="ditto_tag" rel="tag">code</a>,<a href="/feeds/tag-feed/?tags=convert&amp;start=0" class="ditto_tag" rel="tag">convert</a>,<a href="/feeds/tag-feed/?tags=ical&amp;start=0" class="ditto_tag" rel="tag">ical</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=rss&amp;start=0" class="ditto_tag" rel="tag">rss</a>,<a href="/feeds/tag-feed/?tags=rss2ical&amp;start=0" class="ditto_tag" rel="tag">rss2ical</a>,<a href="/feeds/tag-feed/?tags=tools&amp;start=0" class="ditto_tag" rel="tag">tools</a>,<a href="/feeds/tag-feed/?tags=weather&amp;start=0" class="ditto_tag" rel="tag">weather</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>
			</item>

			<item>
				<title>Writing Secure PHP, Part 3</title>
				<link>http://www.addedbytes.com/writing-secure-php/writing-secure-php-3/</link>
				<description><![CDATA[ The third part of the Writing Secure PHP series, covering weak passwords, clients and more advanced topics. <p>In <a href="http://www.addedbytes.com/php/writing-secure-php/">Writing Secure PHP</a> and <a href="http://www.addedbytes.com/security/writing-secure-php-2/">Writing Secure PHP, Part 2</a> I covered many of the basic mistakes PHP developers make, and how to avoid common security problems. It is time to get a little deeper into security though, and begin to tackle some more advanced issues.</p>

<p>[Writing Secure PHP is a series. <a href="http://www.addedbytes.com/php/writing-secure-php/">Part 1</a>, <a href="http://www.addedbytes.com/php/writing-secure-php-2/">Part 2</a> and <a href="http://www.addedbytes.com/php/writing-secure-php-4/">Part 4</a> are currently also available.]</p>

<h3>Context</h3>

<p>Before I start, it is worth mentioning at this point in this series that much of what is to come is highly dependant on context. If you are running a small personal site and are regularly backing it up, the chances are that there is no real benefit to you spending weeks on advanced security issues. If an attacker can gain nothing (and cause no harm) by compromising your site, and it would only take you ten minutes to restore it, should something go wrong, then it would be a waste to spend too long on security concerns. At the other end of the scale, if you are managing an ecommerce site that processes thousands of credit cards a day, then it is negligent not to spend a lot of time researching and improving your site's security.</p>

<h3>Database Field Lengths</h3>

<p>Database (we're going to talk about <a href="http://www.mysql.com">MySQL</a> here, but this is applicable to any database) fields are always of a specific type, and every type has its limits. You can as well, in MySQL, limit field lengths further than they are already limited by their types.</p>

<p>However, to the inexperienced developer, this can present problems. If you are allowing users to post an article on your site, and adding that to a database field with type "blob", then the longest article you can store in the database is 65,535 characters. For most articles that will be fine, but what is going to happen when a user posts an article of 100,000 characters? At best, if you have set up your site so errors are not displayed, their article will simply vanish without being added to the site.</p>

<p>Remember that for an attacker to be able to compromise your system, they need information about it. They need to find weaknesses. Error messages are a very powerful part of that and if you are displaying errors, then an attacker can make use of this to find out information about your database.</p>

<p>To fix this, simply check the lengths of data input through forms and querystrings and ensure that before you launch a site you check forms will not cause errors to be displayed when too many characters are entered.</p>

<h3>Weak Passwords</h3>

<p>Dictionaries are a useful tool for an attacker. If you have a site with a login system and your database were compromised (and there is no harm in assuming that at some point it will be), an attacker can grab a list of hashed passwords. It is difficult (practically impossible) to directly translate a hash back into a password.</p>

<p>However, most attackers will have databases containing lists of words and their matching hashes in common formats (eg a database with all words in English and their MD5 hashes). It is fairly easy, should someone gain access to your database, for them to compare a hashed password to this list of pre-hashed passwords. If a match is found in the list, the attacker then knows what the un-hashed password is.</p>

<p>There are ways to avoid this problem, and the best of those is to ensure that only strong passwords are ever used. Some people find guaging the strength of passwords tricky, but the general rule of thumb is: a password like "password", "admin", "god", "sex", "qwerty", "123456" or similar (i.e. easily guessable) is extremely weak; a password made up only of a word in the dictionary is weak; a password made of letters, numbers and making use of upper and lower case is strong (there is a strong usability case to be made for not using case-sensitive passwords - if you wish to use case-insensitve ones, simply perform checks to ensure people do not pick passwords like "password12345").</p>

<h3>Clients</h3>

<p>Clients are a huge security risk, believe it or not. Some will hire a cheaper developer to make small changes six months after you're finished. Some will give out FTP details to anyone who phones and asks for them. [Out of curiosity, I decided to see how easy it is to get FTP details over the phone. I visited the site of a local company (who shall remain nameless) and found the name of their design company (who shall also remain nameless). I then phoned the local company and told them I was with the design company and needed them to send me the site's FTP details. They agreed without question or hesitation. Scary. (I told them what I was doing before they sent any sensitive data to me and they are now better educated and suitably paranoid about people asking for details over the phone).]</p>

<p>Some will ignore emails from people pointing out security problems (in the process of writing the previous article in this series, I found a large selection of sites with publically available database connection scripts. I emailed the owners explaining why they are at risk, and only one has replied and had the problem fixed at the time of writing). Admitedly, many of the emails and calls they receive will be misinformation or sales pitches, but it is still worth them having someone check this out - they do not know enough to distinguish a genuine problem from the rest.</p>

<p>Unfortunately, this is one security problem that cannot be solved with code. This one requires education. For this reason, I have created an unbranded copy of the sheet I give to my clients, with a selection of security tips on. When we launch the site, I sit down with them and tell them how they need to treat their site, and what to consider when making decisions regarding it.</p>

<p><a href="content/writing-secure-php-3/client_security.png">Client Security Handout</a> (PNG, 74KB)</p>

<h3>Code Injection (a.k.a. "Cross-Site Scripting")</h3>

<p>Unlike SQL Injection, which relies on the use of delimiters in user-input text to take control of database queries, code injection relies on mistakes in the treatment of text before it is output. Or, to put it in simpler terms, code injection is where a malicious user uses a text box to add HTML that they've written to your webpage.</p>

<p>Let's say you have a system that allows users to register as members to your site and that they are allowed to create their own username. They fill out a form, and you insert the data they enter, once you've made it safe to use in a SQL query, into a database. Your members listing page fetches all the usernames from the database and lists them, outputting exactly what is in the database to anyone that views that page.</p>

<p>Now, let's say you've not added a limit to username lengths. Someone could, if they wanted, create a user with the following username:</p>

<pre class="php">Username&lt;script type="text/javascript" src="http://www.website.com/malicious.js"&gt;&lt;/script&gt;</pre>

<p>Anyone that then views a page with that username on it will see a normal username, but a JavaScript has been loaded from another site invisibly to the user.</p>

<p>There are plenty of uses for this. First and foremost, it allows attackers to add keyloggers, tracking scripts or porn banners on your site, or just stop your site working altogether. There are several ways to ensure this doesn't happen. First, you could encode HTML in usernames. If you wanted to allow people to use greater-then and less-than signs in their usernames, that is. If not, you can strip these characters out, or strip out HTML tags altogether.</p>

<p>Another, better way to approach this is to limit the character set that can be used in usernames. If you only allow letters and numbers, for example, you could simply use a regular expression in the signup process to validate the username and force the user to pick another if they have disallowed characters in their username. Obviously the problem is not just applicable to usernames - however, as with most other security concerns, being quite paranoid will ensure that you always check data coming from a user before outputting it, and sanitising it in an appropriate way.</p>

<h3>Aftermath</h3>

<p>Part of a good security strategy is the assumption that at some point everything (and I mean everything) will be deleted or destroyed. It is wise to assume that at some point any security measure you have in place will be compromised. All data may be taken (which is one reason why it is important to encrypt things like passwords and credit card numbers in databases), all files deleted and so on.</p>

<p>One part of PHP development, though perhaps not directly about PHP security, is ensuring that after a catastrophic failure a site can be brought back online quickly. While downtime of four hours maybe acceptable with a low-traffic point-of-presence site, any ecommerce retailer is going to erupt with fury at the thought of that much lost revenue.</p>

<p>Dealing with the client under these circumstances is the first step. Often, your first inkling of a problem with a site may actually come from the client. They may have phoned you and could be angry, worried, or a myriad of other emotions. At moments like this, you would be very glad to have a clear contigency plan in place. Many developers panic when the client phones saying their front page has been defaced. Stick to your action plan and to your client you will seem confident and unphased. That will relax them. The plan will also allow you to resolve the problem far faster.</p>

<p>First, find out what happened. Are you dealing with a security breach or has someone at the host company tripped over a power lead? Was the database compromised, or deleted, as a result of an attack or was your server simply unable to cope with too much traffic? You need to know what has happened in order to deal with it - a site going offline could be down to too many factors to just assume it is a security problem.</p>

<p>Assuming this is a security problem, the next step is to reassure the client. Let them know what has happened. If someone got into the database, no problem - all sensitive data is encrypted. If they've uploaded files to your server (quite possible), you'll have to delete all files and restore from a backup.</p>

<p>You've got to find out how the attacker broke into your system. Check log files, if you have access to them. Also, have a look at hacker and cracker web sites - many of them will list successful attacks against servers by various groups (these are often what are sometimes known as "script kiddies" - not hackers as such, but usually exploiting vulnerabilities found by others). You may well find your site listed and that listing will give you invaluable information. Look at other sites brought down by the same group at around the same time - you will often spot a theme (e.g. all sites that have been attacked were running the same version of <a href="http://www.microsoft.com/WindowsServer2003/iis/default.mspx">IIS</a> or <a href="http://www.apache.org">Apache</a>, were all running <a href="http://www.phpbb.com">phpBB</a>, or all are file repositories running on <a href="http://www.macromedia.com/v1/cfdocs/cfml_language_reference/contents.htm">CFML</a>).</p>

<p>If you are running any third party software on the site, check the distribution site and if necessary get in touch with them, especially if other sites running the same software appear to have been compromised.</p>

<p>It is very important that you fix any hole there may be before you restore the site. It would be wise to add a "We are currently undergoing essential maintenance" page, but do not fully restore the site before you have found out and fixed whatever the problem was - you'll be wasting your time.</p>

<h3>Shared Hosting</h3>

<p>Shared hosting is much cheaper than dedicated hosting, and is where several sites are all hosted on the same server. Most sites are hosted this way, and this brings with it its own set of security issues.</p>

<p>First and foremost, the security of your site is, in these circumstances, almost entirely out of your hands. It is dependant on the hosting company you are with. They may be excellent, or they may be crooks. Check reviews of a company before you select them, as they will have access to all the data you store with them. There is no harm in being automatically suspicious of your hosting company.</p>

<p>If they are completely above board (and most are), you are still not necessarily secure with shared hosting. The security measures they put in place are generally pretty simple. Shared hosting servers should always use PHP's safe mode (which disables many of the more advanced and dangerous features of PHP). That is what it is there for. However, many don't.</p>

<p>Vulnerabilities associated with shared hosting are, for the most part, out of your hands. A badly set up server will allow any site on that server to access files like /etc/passwd and httpd.conf, often giving them access to all other sites on the same server. It is possible to secure yourself to some degree against the effects of this vulnerability. Storing information in a database is recommended. Of course, if you then store your database login in a file, an attacked could access this information. In order to make this inaccessible to others on the same server, you could set database login information within the httpd.conf file, using environmental variables (you will need to ask your host company to add the lines to the httpd.conf file).</p>

<p>Better yet is to ensure that your host, if shared, uses safe mode. While this is still not 100% secure (nothing is), it does help make these attacks more difficult. A dedicated server is another, far better, option, but the expense may be prohibitive.</p>

<p><em>Ready for more? Try <a href="http://www.addedbytes.com/security/writing-secure-php-4/">Writing Secure PHP, Part 4</a>.</em></p> <br><br>]]></description>
				<pubDate>Wed, 27 Jul 2005 08:58:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/writing-secure-php/writing-secure-php-3/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=guide&amp;start=0" class="ditto_tag" rel="tag">guide</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=programming&amp;start=0" class="ditto_tag" rel="tag">programming</a>,<a href="/feeds/tag-feed/?tags=security&amp;start=0" class="ditto_tag" rel="tag">security</a>,<a href="/feeds/tag-feed/?tags=tips&amp;start=0" class="ditto_tag" rel="tag">tips</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>,<a href="/feeds/tag-feed/?tags=work&amp;start=0" class="ditto_tag" rel="tag">work</a>
			</item>

			<item>
				<title>PDF Cheat Sheets</title>
				<link>http://www.addedbytes.com/blog/pdf-cheat-sheets/</link>
				<description><![CDATA[ <p>As requested by everyone, PDF versions of the <a href="http://www.addedbytes.com/php/php-cheat-sheet/">PHP</a>, <a href="http://www.addedbytes.com/css/css-cheat-sheet/">CSS</a> and <a href="http://www.addedbytes.com/cheat-sheets/mod_rewrite-cheat-sheet/">mod_rewrite</a> cheat sheets are now online. Enjoy!</p> <p>As requested by everyone, PDF versions of the <a href="http://www.addedbytes.com/php/php-cheat-sheet/">PHP</a>, <a href="http://www.addedbytes.com/css/css-cheat-sheet/">CSS</a> and <a href="http://www.addedbytes.com/cheat-sheets/mod_rewrite-cheat-sheet/">mod_rewrite</a> cheat sheets are now online. Enjoy!</p> <br><br>]]></description>
				<pubDate>Fri, 13 May 2005 15:49:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/blog/pdf-cheat-sheets/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=css&amp;start=0" class="ditto_tag" rel="tag">css</a>,<a href="/feeds/tag-feed/?tags=pdf&amp;start=0" class="ditto_tag" rel="tag">pdf</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>
			</item>

			<item>
				<title>Block Prefetching</title>
				<link>http://www.addedbytes.com/blog/block-prefetching/</link>
				<description><![CDATA[ <p>Mozilla and Google's prefetching functions are a nice addition to browser technology in many ways. Unsurprisingly, they are not very well thought through.</p> <p>Mozilla and Google's prefetching functions are a nice addition to browser technology in many ways. Unsurprisingly, they are not very well thought through. The main two problems with the prefetching idea are that it messes with log files and it means every link on a page could potentially be followed despite the consequences (dangerous in a site administration context).</p>

<p>It appears from the FAQ that Google only intends their accelerator to prefetch specific pages, that have been specified with the &lt;link&gt; tag. However, many people are claiming that normal links have been prefetched.</p>

<p>To prevent prefetching of a page is simple: add the following PHP to the page you do not want prefetched:</p>

<pre class="php">if ((isset($_SERVER['HTTP_X_MOZ'])) && ($_SERVER['HTTP_X_MOZ'] == 'prefetch')) {
    // This is a prefetch request. Block it.
    header('HTTP/1.0 403 Forbidden');
    echo '403: Forbidden&lt;br&gt;&lt;br&gt;Prefetching not allowed here.';
    die();
}</pre>

<p>This will serve a "forbidden" header to the prefetcher. Normal browsing should be unaffected.</p> <br><br>]]></description>
				<pubDate>Wed, 20 Apr 2005 15:16:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/blog/block-prefetching/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=block&amp;start=0" class="ditto_tag" rel="tag">block</a>,<a href="/feeds/tag-feed/?tags=google&amp;start=0" class="ditto_tag" rel="tag">google</a>,<a href="/feeds/tag-feed/?tags=mozilla&amp;start=0" class="ditto_tag" rel="tag">mozilla</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=prefetching&amp;start=0" class="ditto_tag" rel="tag">prefetching</a>,<a href="/feeds/tag-feed/?tags=reference&amp;start=0" class="ditto_tag" rel="tag">reference</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>
			</item>

			<item>
				<title>Writing Secure PHP, Part 2</title>
				<link>http://www.addedbytes.com/writing-secure-php/writing-secure-php-2/</link>
				<description><![CDATA[ Learn how to improve your security a little further with the second part of this PHP tutorial. <p>In <a href="http://www.addedbytes.com/php/writing-secure-php/">Writing Secure PHP</a>, I covered a few of the most common security holes in websites. It's time to move on, though, to a few more advanced techniques for securing a website. As techniques for 'breaking into' a site or crashing a site become more advanced, so must the methods used to stop those attacks.</p>

<p>[Writing Secure PHP is a series. <a href="http://www.addedbytes.com/php/writing-secure-php/">Part 1</a>, <a href="http://www.addedbytes.com/php/writing-secure-php-3/">Part 3</a> and <a href="http://www.addedbytes.com/php/writing-secure-php-4/">Part 4</a> are currently also available.]</p>

<h3>File Systems</h3>

<p>Most hosting environments are very similar, and rather predictable. Many web developers are also very predictable. It doesn't take a genius to guess that a site's includes (and most dynamic sites use an includes directory for common files) is an www.website.com/includes/. If the site owner has allowed directory listing on the server, anyone can navigate to that folder and browse files.</p>

<p>Imagine for a second that you have a database connection script, and you want to connect to the database from every page on your site. You might well place that in your includes folder, and call it something like connect.inc. However, this is very predictable - many people do exactly this. Worst of all, a file with the extension ".inc" is usually rendered as text and output to the browser, rather than processed as a PHP script - meaning if someone were to visit that file in a browser, they'll be given your database login information.</p>

<p>Placing important files in predictable places with predictable names is a recipe for disaster. Placing them outside the web root can help to lessen the risk, but is not a foolproof solution. The best way to protect your important files from vulnerabilities is to place them outside the web root, in an unusually-named folder, and to make sure that error reporting is set to off (which should make life difficult for anyone hoping to find out where your important files are kept). You should also make sure directory listing is not allowed, and that all folders have a file named "index.html" in (at least), so that nobody can ever see the contents of a folder.</p>

<p>Never, ever, give a file the extension ".inc". If you must have ".inc" in the extension, use the extension ".inc.php", as that will ensure the file is processed by the PHP engine (meaning that anything like a username and password is not sent to the user). Always make sure your includes folder is outside your web root, and not named something obvious. Always make sure you add a blank file named "index.html" to all folders like include or image folders - even if you deny directory listing yourself, you may one day change hosts, or someone else may alter your server configuration - if directory listing is allowed, then your index.html file will make sure the user always receives a blank page rather than the directory listing. As well, always make sure directory listing is denied on your web server (easily done with .htaccess or httpd.conf).</p>

<p>------</p>

<p>Out of sheer curiosity, shortly after writing this section of this tutorial, I decided to see how many sites I could find in a few minutes vulnerable to this type of attack. Using <a href="http://www.google.com">Google</a> and a few obvious search phrases, I found about 30 database connection scripts, complete with usernames and passwords. A little more hunting turned up plenty more open include directories, with plenty more database connections and even FTP details. All in, it took about ten minutes to find enough information to cause serious damage to around 50 sites, without even using these vulnerabilities to see if it were possible to cause problems for other sites sharing the same server.</p>

<p>-----</p>

<h3>Login Systems</h3>

<p>Most site owners now require an online administration area or CMS (content management system), so that they can make changes to their site without needing to know how to use an <a href="http://filezilla.sourceforge.net/">FTP client</a>. Often, these are placed in predictable locations (as covered in the last article), however placing an administration area in a hard-to-find location isn't enough to protect it.</p>

<p>Most CMSes allow users to change their password to anything they choose. Many users will pick an easy-to-remember word, often the name of a loved one or something similar with special significance to them. Attackers will use something called a "dictionary attack" (or "brute force attack") to break this kind of protection. A dictionary attack involves entering each word from the dictionary in turn as the password until the correct one is found.</p>

<p>The best way to protect against this is threefold. First, you should add a turing test to a login page. Have a randomly generated series of letters and numbers on the page that the user must enter to login. Make sure this series changes each time the user tries to login, that it is an image (rather than simple text), and that it cannot be identified by an optical character recognition script.</p>

<p>Second, add in a simple counter. If you detect a certain number of failed logins in a row, disable logging in to the administration area until it is reactivated by someone responsible. If you only allow each potential attacker a small number of attempts to guess a password, they will have to be very lucky indeed to gain access to the protected area. This might be inconvenient for authentic users, however is usually a price worth paying.</p>

<p>Finally, make sure you track IP addresses of both those users who successfully login and those who don't. If you spot repeated attempts from a single IP address to access the site, you may consider blocking access from that IP address altogether.</p>

<h3>Database Users</h3>

<p>One excellent way to make sure that even if you have a problem with someone accessing your database who shouldn't be able to, you can limit the damage they can cause. Modern databases like MySQL and SQL Server allow you to control what a user can and cannot do. You can give users (or not) permission to create data, edit, delete, and more using these permissions. Usually, I try and ensure that I only allow users to add and edit data.</p>

<p>If a site requires an item be deleted, I will usually set the front end of the site to only appear to delete the item. For example, you could have a numeric field called "item_deleted", and set it to 1 when an item is deleted. You can then use that to prevent users seeing these items. You can then purge these later if required, yourself, while not giving your users "delete" permissions for the database. If a user cannot delete or drop tables, neither can someone who finds out the user login to the database (though obviously they can still do damage).</p>

<h3>Powerful Commands</h3>

<p>PHP contains a variety of commands with access to the operating system of the server, and that can interact with other programs. Unless you need access to these specific commands, it is highly recommended that you disable them entirely.</p>

<p>For example, the <a href="http://www.php.net/eval">eval()</a> function allows you to treat a string as PHP code and execute it. This can be a useful tool on occasion. However, if using the <a href="http://www.php.net/eval">eval()</a> function on any input from the user, the user could cause all sorts of problems. You could be, without careful input validation, giving the user free reign to execute whatever commands he or she wants.</p>

<p>There are ways to get around this. Not using <a href="http://www.php.net/eval">eval()</a> is a good start. However, the php.ini file gives you a way to completely disable certain functions in PHP - "disable_functions". This directive of the php.ini file takes a comma-separated list of function names, and will completely disable these in PHP. Commonly disabled functions include <a href="http://www.php.net/ini_set">ini_set()</a>, <a href="http://www.php.net/exec">exec()</a>, <a href="http://www.php.net/fopen">fopen()</a>, <a href="http://www.php.net/popen">popen()</a>, <a href="http://www.php.net/passthru">passthru()</a>, <a href="http://www.php.net/readfile">readfile()</a>, <a href="http://www.php.net/file">file()</a>, <a href="http://www.php.net/shell_exec">shell_exec()</a> and <a href="http://www.php.net/system">system()</a>.</p>

<p>It may be (it usually is) worth enabling safe_mode on your server. This instructs PHP to limit the use of functions and operators that can be used to cause problems. If it is possible to enable safe_mode and still have your scripts function, it is usually best to do so.</p>

<h3>Finally, Be Completely and Utterly Paranoid</h3>

<p>Much as I hate to bring this point up again, it still holds true (and always will). Most of the above problems can be avoided through careful input validation. Some become obvious points to address when you assume everyone is out to destroy your site. If you are prepared for the worst, you should be able to deal with anything.</p>

<p><em>Ready for more? Try <a href="http://www.addedbytes.com/security/writing-secure-php-3/">Writing Secure PHP, Part 3</a>.</em></p> <br><br>]]></description>
				<pubDate>Tue, 22 Mar 2005 16:53:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/writing-secure-php/writing-secure-php-2/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=development&amp;start=0" class="ditto_tag" rel="tag">development</a>,<a href="/feeds/tag-feed/?tags=imported&amp;start=0" class="ditto_tag" rel="tag">imported</a>,<a href="/feeds/tag-feed/?tags=mysql&amp;start=0" class="ditto_tag" rel="tag">mysql</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=programming&amp;start=0" class="ditto_tag" rel="tag">programming</a>,<a href="/feeds/tag-feed/?tags=security&amp;start=0" class="ditto_tag" rel="tag">security</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>,<a href="/feeds/tag-feed/?tags=work&amp;start=0" class="ditto_tag" rel="tag">work</a>
			</item>

			<item>
				<title>SQL Server, PHP and Truncating Text</title>
				<link>http://www.addedbytes.com/blog/sql-server-php-truncating-text/</link>
				<description><![CDATA[ PHP and SQL Server are a powerful combination, however sometimes data stored in a text type column is truncated for no apparent reason after 4096 characters. Here's how to fix the problem. <p>PHP can work with a large number of database systems, most common of which is MySQL. However, SQL Server is a very poweful alternative to MySQL, and well worth considering for larger projects.</p>

<p>However, settings for the mssql extension in PHP can easily be overlooked, resulting in strange behaviour. One of the most unusual problems I encountered on a recent project was that every time text was pulled from a column of type "text", it was truncated at around 4000 characters.</p>

<p>If you are experiencing a similar problem, there are a few ways to work around it.</p>

<p>You need to increase the maximum size of a text column to be returned from SQL Server by PHP. You can do this with a simple SQL query:</p>

<code>SET TEXTSIZE 2147483647</code>

<p>Which you can run with the following PHP (best run just after you make a connection).</p>

<code>mssql_query("SET TEXTSIZE 2147483647");</code>

<p>A better way to work around the issue is to change the "textlimit" and "textsize" settings within php.ini, like so:</p>

<code>mssql.textlimit = 2147483647
mssql.textsize = 2147483647</code>

<p>In the above examples, I have used "2147483647" (number of bytes) for the value. You don't need to set it this high necessarily, however there is no real harm in doing so.</p>

<p>And why does this not happen with ASP? When you use Microsoft's SQL Server ODBC driver and OLE DB Provider, textsize is automatically set to 2147483647 when a connection is made.</p> <br><br>]]></description>
				<pubDate>Wed, 22 Dec 2004 10:40:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/blog/sql-server-php-truncating-text/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=mssql&amp;start=0" class="ditto_tag" rel="tag">mssql</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=server&amp;start=0" class="ditto_tag" rel="tag">server</a>,<a href="/feeds/tag-feed/?tags=sql&amp;start=0" class="ditto_tag" rel="tag">sql</a>,<a href="/feeds/tag-feed/?tags=text&amp;start=0" class="ditto_tag" rel="tag">text</a>
			</item>

			<item>
				<title>Writing Secure PHP, Part 1</title>
				<link>http://www.addedbytes.com/writing-secure-php/writing-secure-php-1/</link>
				<description><![CDATA[ Learn how to avoid some of the most common mistakes in PHP, and so make your sites more secure. <p><a href="http://www.php.net">PHP</a> is a very easy language to learn, and many people without any sort of background in programming learn it as a way to add interactivity to their web sites. Unfortunately, that often means PHP programmers, especially those newer to web development, are unaware of the potential security risks their web applications can contain. Here are a few of the more common security problems and how to avoid them.</p>

<p>[Writing Secure PHP is a series. <a href="http://www.addedbytes.com/php/writing-secure-php-2/">Part 2</a>, <a href="http://www.addedbytes.com/php/writing-secure-php-3/">Part 3</a> and <a href="http://www.addedbytes.com/php/writing-secure-php-4/">Part 4</a> are currently also available.]</p>

<h3>Rule Number One: Never, Ever, Trust Your Users</h3>

<p>It can never be said enough times, you should never, ever, ever trust your users to send you the data you expect. I have heard many people respond to that with something like "Oh, nobody malicious would be interested in my site". Leaving aside that that could not be more wrong, it is not always a malicious user who can exploit a security hole - problems can just as easily arise because of a user unintentionally doing something wrong.</p>

<p>So the cardinal rule of all web development, and I can't stress it enough, is: <strong>Never, Ever, Trust Your Users</strong>. Assume every single piece of data your site collects from a user contains malicious code. Always. That includes data you think you have checked with client-side validation, for example using JavaScript. If you can manage that, you'll be off to a good start. If PHP security is important to you, this single point is the most important to learn. Personally, I have a "PHP Security" sheet next to my desk with major points on, and this is in large bold text, right at the top.</p>

<h3>Global Variables</h3>

<p>In many languages you must explicitly create a variable in order to use it. In PHP, there is an option, "register_globals", that you can set in php.ini that allows you to use global variables, ones you do not need to explicitly create. </p>

<p>Consider the following code:</p>

<pre class="php">if ($password == "my_password") {
    $authorized = 1;
}

if ($authorized == 1) {
    echo "Lots of important stuff.";
}</pre>

<p>To many that may look fine, and in fact this exact type of code is in use all over the web. However, if a server has "register_globals" set to on, then simply adding "?authorized=1" to the URL will give anyone free access to exactly what you do not want everyone to see. This is one of the most common PHP security problems.</p>

<p>Fortunately, this has a couple of possible simple solutions. The first, and perhaps the best, is to set "register_globals" to off. The second is to ensure that you only use variables that you have explicitly set yourself. In the above example, that would mean adding "$authorized = 0;" at the beginning of the script:</p>

<pre class="php">$authorized = 0;
if ($password == "my_password") {
    $authorized = 1;
}

if ($authorized == 1) {
    echo "Lots of important stuff.";
}</pre>

<h3>Error Messages</h3>

<p>Errors are a very useful tool for both programmer and hacker. A developer needs them in order to fix bugs. A hacker can use them to find out all sorts of information about a site, from the directory structure of the server to database login information. If possible, it is best to turn off all error reporting in a live application. PHP can be told to do this through .htaccess or php.ini, by setting "error_reporting" to "0". If you have a development environment, you can set a different error reporting level for that.</p>

<h3>SQL Injection</h3>

<p>One of PHP's greatest strengths is the ease with which it can communicate with databases, most notably <a href="http://www.mysql.com">MySQL</a>. Many people make extensive use of this, and a great many sites, including this one, rely on databases to function.</p>

<p>However, as you would expect, with that much power there are potentially huge security problems you can face. Fortunately, there are plenty of solutions. The most common security hazard faced when interacting with a database is that of SQL Injection - when a user uses a security glitch to run SQL queries on your database.</p>

<p>Let's use a common example. Many login systems feature a line that looks a lot like this when checking the username and password entered into a form by a user against a database of valid username and password combinations, for example to control access to an administration area:</p>

<pre class="php">$check = mysql_query("SELECT Username, Password, UserLevel FROM Users WHERE Username = '".$_POST['username']."' and Password = '".$_POST['password']."'");</pre>

<p>Look familiar? It may well do. And on the face of it, the above does not look like it could do much damage. But let's say for a moment that I enter the following into the "username" input box in the form and submit it:</p>

<pre class="php">' OR 1=1 #</pre>

<p>The query that is going to be executed will now look like this:</p>

<pre class="sql">SELECT Username, Password FROM Users WHERE Username = '' OR 1=1 #' and Password = ''</pre>

<p>The hash symbol (#) tells MySQL that everything following it is a comment and to ignore it. So it will actually only execute the SQL up to that point. As 1 always equals 1, the SQL will return all of the usernames and passwords from the database. And as the first username and password combination in most user login databases is the admin user, the person who simply entered a few symbols in a username box is now logged in as your website administrator, with the same powers they would have if they actually knew the username and password.</p>

<p>With a little creativity, the above can be exploited further, allowing a user to create their own login account, read credit card numbers or even wipe a database clean.</p>

<p>Fortunately, this type of vulnerability is easy enough to work around. By checking for apostrophes in the items we enter into the database, and removing or neutralising them, we can prevent anyone from running their own SQL code on our database. The function below would do the trick:</p>

<pre class="php">function make_safe($variable) {
    $variable = mysql_real_escape_string(trim($variable));
    return $variable;
}</pre>

<p>Now, to modify our query. Instead of using _POST variables as in the query above, we now run all user data through the make_safe function, resulting in the following code:</p>

<pre class="php">$username = make_safe($_POST['username']);
$password = make_safe($_POST['password']);
$check = mysql_query("SELECT Username, Password, UserLevel FROM Users WHERE Username = '".$username."' and Password = '".$password."'");</pre>

<p>Now, if a user entered the malicious data above, the query will look like the following, which is perfectly harmless. The following query will select from a database where the username is equal to "\' OR 1=1 #".</p>

<pre class="sql">SELECT Username, Password, UserLevel FROM Users WHERE Username = '\' OR 1=1 #' and Password = ''</pre>

<p>Now, unless you happen to have a user with a very unusual username and a blank password, your malicious attacker will not be able to do any damage at all. It is important to check all data passed to your database like this, however secure you think it is. HTTP Headers sent from the user can be faked. Their referral address can be faked. Their browsers User Agent string can be faked. Do not trust a single piece of data sent by the user, though, and you will be fine.</p>

<h3>File Manipulation</h3>

<p>Some sites currently running on the web today have URLs that look like this:</p>

<pre class="php">index.php?page=contactus.html</pre>

<p>The "index.php" file then simply includes the "contactus.html" file, and the site appears to work. However, the user can very easily change the "contactus.html" bit to anything they like. For example, if you are using <a href="http://www.apache.org/">Apache</a>'s mod_auth to protect files and have saved your password in a file named ".htpasswd" (the conventional name), then if a user were to visit the following address, the script would output your username and password:</p>

<pre class="php">index.php?page=.htpasswd</pre>

<p>By changing the URL, on some systems, to reference a file on another server, they could even run PHP that they have written on your site. Scared? You should be. Fortunately, again, this is reasonably easy to protect against. First, make sure you have correctly set "open_basedir" in your php.ini file, and have set "allow_url_fopen" to "off". That will prevent most of these kinds of attacks by preventing the inclusion of remote files and system files. Next, if you can, check the file requested against a list of valid files. If you limit the files that can be accessed using this script, you will save yourself a lot of aggravation later.</p>

<h3>Using Defaults</h3>

<p>When MySQL is installed, it uses a default username of "root" and blank password. SQL Server uses "sa" as the default user with a blank password. If someone finds the address of your database server and wants to try to log in, these are the first combinations they will try. If you have not set a different password (and ideally username as well) than the default, then you may well wake up one morning to find your database has been wiped and all your customers' credit card numbers stolen. The same applies to all software you use - if software comes with default username or password, change them.</p>

<h3>Leaving Installation Files Online</h3>

<p>Many PHP programs come with installation files. Many of these are self-deleting once run, and many applications will refuse to run until you delete the installation files. Many however, will not pay the blindest bit of attention if the install files are still online. If they are still online, they may still be usable, and someone may be able to use them to overwrite your entire site.</p>

<h3>Predictability</h3>

<p>Let us imagine for a second that your site has attracted the attention of a Bad Person. This Bad Person wants to break in to your administration area, and change all of your product descriptions to "This Product Sucks". I would hazard a guess that their first step will be to go to http://www.yoursite.com/admin/ - just in case it exists. Placing your sensitive files and folders somewhere predictable like that makes life for potential hackers that little bit easier.</p>

<p>With this in mind, make sure you name your sensitive files and folders so that they are tough to guess. Placing your admin area at http://www.yoursite.com/jsfh8sfsifuhsi8392/ might make it harder to just type in quickly, but it adds an extra layer of security to your site. Pick something memorable by all means if you need an address you can remember quickly, but don't pick "admin" or "administration" (or your username or password). Pick something unusual.</p>

<p>The same applies to usernames and passwords. If you have an admin area, do not use "admin" as the username and "password" as the password. Pick something unusual, ideally with both letters and numbers (some hackers use something called a "dictionary attack", trying every word in a dictionary as a password until they find a word that works - adding a couple of digits to the end of a password renders this type of attack useless). It is also wise to change your password fairly regularly (every month or two).</p>

<p>Finally, make sure that your error messages give nothing away. If your admin area gives an error message saying "Unknown Username" when a bad username is entered and "Wrong Password" when the wrong password is entered, a malicious user will know when they've managed to guess a valid username. Using a generic "Login Error" error message for both of the above means that a malicious user will have no idea if it is the username or password he has entered that is wrong.</p>

<h3>Finally, Be Completely and Utterly Paranoid</h3>

<p>If you assume your site will never come under attack, or face any problems of any sort, then when something eventually does go wrong, you will be in massive amounts of trouble. If, on the other hand, you assume every single visitor to your site is out to get you and you are permanently at war, you will help yourself to keep your site secure, and be prepared in case things should go wrong.</p>

<p><em>Ready for more? Try <a href="http://www.addedbytes.com/security/writing-secure-php-2/">Writing Secure PHP, Part 2</a>.</em></p> <br><br>]]></description>
				<pubDate>Fri, 16 Jul 2004 09:07:15 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/writing-secure-php/writing-secure-php-1/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=code&amp;start=0" class="ditto_tag" rel="tag">code</a>,<a href="/feeds/tag-feed/?tags=coding&amp;start=0" class="ditto_tag" rel="tag">coding</a>,<a href="/feeds/tag-feed/?tags=development&amp;start=0" class="ditto_tag" rel="tag">development</a>,<a href="/feeds/tag-feed/?tags=mysql&amp;start=0" class="ditto_tag" rel="tag">mysql</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=programming&amp;start=0" class="ditto_tag" rel="tag">programming</a>,<a href="/feeds/tag-feed/?tags=security&amp;start=0" class="ditto_tag" rel="tag">security</a>,<a href="/feeds/tag-feed/?tags=tips&amp;start=0" class="ditto_tag" rel="tag">tips</a>,<a href="/feeds/tag-feed/?tags=tutorial&amp;start=0" class="ditto_tag" rel="tag">tutorial</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdesign&amp;start=0" class="ditto_tag" rel="tag">webdesign</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>
			</item>

			<item>
				<title>Output Caching for Beginners</title>
				<link>http://www.addedbytes.com/for-beginners/output-caching-for-beginners/</link>
				<description><![CDATA[ High-traffic sites can often benefit from caching of pages, to save processing of the same data over and over again. This caching tutorial runs through the basics of file caching in PHP. <p>Caching of output in PHP is made easier by the use of the output buffering functions built in to PHP 4 and above.</p>

<p>You'll need to use two files to set up a caching system for your site. The first, "begin_caching.php" in this case, will run before any other PHP on your site. The second, "end_caching.php" in this case, runs after normal scripts have run. The two scripts effectively wrap around your current site.</p>

<p>You can achieve this wrapping effect one of two ways. The first way is to simply use the include() function and add them manually to every script you run. Unfortunately, this method can take some time, but is arguably more portable than the alternative.</p>

<p>The alternative relies on adding the following two lines of code (modified to reflect the correct path to the two PHP files needed) to your htaccess file. This is my preferred method, just because it requires no modification to existing scripts, and can very easily and quickly be turned off (just by commenting out the relevant lines in the htaccess file).</p>

<pre class="php">php_value auto_prepend_file /full/path/to/begin_caching.php
php_value auto_append_file /full/path/to/end_caching.php</pre>

<p>Next, we move on to the scripts that do the work. There are several stages to caching a document:</p>

<ol><li>Receive request for page</li><li>Check for the existence of a cached version of that page</li><li>Check the cached copy is still valid<ul><li>If it is, send the cached copy</li><li>If not, create a new cached copy and send it</li></ul></li></ol>

<p>To begin with, the script below contains a few basic settings. Here, you can set the directory you want to save cached files to (I would recommend keeping that directory outside your web root directory or at least protecting it from view through a normal browser). This script will need to be able to create files in this directory, and you need to allow this by setting the permissions of the directory. The permissions depend upon your server set up, so you may want to start by setting them to 777 while testing the script, and then reduce them to the lowest levels possible once the script is working.</p>

<p>You can also set the time, in seconds, a cached file should be considered valid for after creation, and set the file extension for saved files. It would be wise to not name them ".php", just for safety's sake.</p>

<pre class="php">&lt;?php

    // Settings
    $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)
    $cachetime = 600; // Seconds to cache files for
    $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)

    // Ignore List
    $ignore_list = array(
        'addedbytes.com/rss.php',
        'addedbytes.com/search/'
    );

    // Script
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
    $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create

    $ignore_page = false;
    for ($i = 0; $i &lt; count($ignore_list); $i++) {
        $ignore_page = (strpos($page, $ignore_list[$i]) !== false) ? true : $ignore_page;
    }

    $cachefile_created = ((@file_exists($cachefile)) and ($ignore_page === false)) ? @filemtime($cachefile) : 0;
    @clearstatcache();

    // Show file from cache if still valid
    if (time() - $cachetime &lt; $cachefile_created) {

        <em>//ob_start('ob_gzhandler');</em>
        @readfile($cachefile);
        <em>//ob_end_flush();</em>
        exit();

    }

    // If we're still here, we need to generate a cache file

    ob_start();

?&gt;</pre>

<p>The file starts by generating an MD5 hash of the page that has been requested. It will use the complete requested URL, and the MD5 hash will be a 32 digit number, unique for each file. It then checks for the existence of this file.</p>

<p>If the file exists, it checks to see when it was last updated. If the file is older than the allowed time, it acts as though no cache existed (carrying on and generating a new file). If the file is still valid, it simply displays it.</p>

<p>There is also, in the settings, a list of pages to ignore when caching. This can be search results, comments pages, a news page or news feed - anything that should always be up to date. Simply add anything you do not want cached into here, and it will not be cached. You can add directories, or parts of URLs - the above simply searches for a text string. In the example above, I have left out the "http://www" portion of the URL, as this can be missed out by some visitors.</p>

<p>Finally, the two lines in italics above are both commented out. You can, if you like, uncomment these, and that will use outbut buffering to gzip your content before sending it to users, making your site even faster for them. Please note, though, that output buffering with gz encoding is not available in versions of PHP previous to 4.0.5.</p>

<p>Which brings us to the second file, "end_caching.php". At the end of the first file, if no cache exists, we start output buffering. This means that rather than send the page to the user, we are saving it for use later. In the second script below, we take the contents of the output buffer, and write it to a file.</p>

<pre class="php">&lt;?php

    // Now the script has run, generate a new cache file
    $fp = @fopen($cachefile, 'w'); 

    // save the contents of output buffer to the file
    @fwrite($fp, ob_get_contents());
    @fclose($fp); 

    ob_end_flush(); 

?&gt;</pre>

<p><strong>Important:</strong> If you do not have "register_globals" set to off in php.ini, make sure you add the following to the beginning of "end_caching.php" (straight after the "&lt;?php" line) to aid security. This will ensure that an attacker cannot visit "end_caching.php" directly and overwrite an important file on your site (or read its contents).</p>

<pre class="php">    $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)
    $cacheext = 'cache'; // Extension to give cached files (usually cache, htm, txt)
    $page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; // Requested page
    $cachefile = $cachedir . md5($page) . '.' . $cacheext; // Cache file to either load or create</pre>

<p>And there we have it. If a cached document exists, it is shown to the user, and if not, one is created.</p>

<p>Finally, you need to make sure the cache remains reasonably clean. Over time, out of date or redundant files could build up, and these should be removed regularly. For this reason, I usually set up an automated script to delete all cache files once a week (or less often, depending on the traffic of the site), but this will depend greatly upon the server software you are using.</p>

<p>The script below is one example of a script to delete all cache files. You will need to set the cache directory at the beginning before running the script. You can either use this manually, visiting the page through your browser whenever you want to empty the cache, or run it automatically. An example of a CRON job used to run this script automatically is below the script (the " &gt;/dev/null 2&gt;&amp;1" bit at the end of the crontab prevents the server emailing me every time the script runs). Please note that this last script will be cached too, unless you specify otherwise!</p>

<pre class="php">&lt;?php

    // Settings
    $cachedir = '../cache/'; // Directory to cache files in (keep outside web root)

    if ($handle = @opendir($cachedir)) {
        while (false !== ($file = @readdir($handle))) {
            if ($file != '.' and $file != '..') {
                echo $file . ' deleted.&lt;br&gt;';
                @unlink($cachedir . '/' . $file);
            }
        }
        @closedir($handle);
    }

?&gt;</pre>

<pre class="php">curl http://www.your_domain.com/empty_caching.php &gt;/dev/null 2&gt;&amp;1</pre> <br><br>]]></description>
				<pubDate>Wed, 09 Jun 2004 15:13:00 +0000</pubDate>
				<guid isPermaLink="false">http://www.addedbytes.com/for-beginners/output-caching-for-beginners/</guid>
				<dc:creator>Dave Child</dc:creator>
				<a href="/feeds/tag-feed/?tags=article&amp;start=0" class="ditto_tag" rel="tag">article</a>,<a href="/feeds/tag-feed/?tags=cache&amp;start=0" class="ditto_tag" rel="tag">cache</a>,<a href="/feeds/tag-feed/?tags=caching&amp;start=0" class="ditto_tag" rel="tag">caching</a>,<a href="/feeds/tag-feed/?tags=code&amp;start=0" class="ditto_tag" rel="tag">code</a>,<a href="/feeds/tag-feed/?tags=development&amp;start=0" class="ditto_tag" rel="tag">development</a>,<a href="/feeds/tag-feed/?tags=performance&amp;start=0" class="ditto_tag" rel="tag">performance</a>,<a href="/feeds/tag-feed/?tags=php&amp;start=0" class="ditto_tag" rel="tag">php</a>,<a href="/feeds/tag-feed/?tags=programming&amp;start=0" class="ditto_tag" rel="tag">programming</a>,<a href="/feeds/tag-feed/?tags=tutorial&amp;start=0" class="ditto_tag" rel="tag">tutorial</a>,<a href="/feeds/tag-feed/?tags=web&amp;start=0" class="ditto_tag" rel="tag">web</a>,<a href="/feeds/tag-feed/?tags=webdev&amp;start=0" class="ditto_tag" rel="tag">webdev</a>
			</item>
	</channel>
</rss>
