<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Official FireBird Blog &#187; PHP Tutorials</title>
	<atom:link href="http://firebird84vn.wordpress.com/category/php-tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://firebird84vn.wordpress.com</link>
	<description>Now and Forever</description>
	<lastBuildDate>Tue, 10 Jul 2007 05:59:51 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='firebird84vn.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/9806f5ba049eb47707b5b13d85d5903d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Official FireBird Blog &#187; PHP Tutorials</title>
		<link>http://firebird84vn.wordpress.com</link>
	</image>
			<item>
		<title>HTTP Headers and the PHP header() Function</title>
		<link>http://firebird84vn.wordpress.com/2007/07/03/http-headers-and-the-php-header-function/</link>
		<comments>http://firebird84vn.wordpress.com/2007/07/03/http-headers-and-the-php-header-function/#comments</comments>
		<pubDate>Tue, 03 Jul 2007 09:02:42 +0000</pubDate>
		<dc:creator>firebird84vn</dc:creator>
				<category><![CDATA[PHP Tutorials]]></category>

		<guid isPermaLink="false">http://firebird84vn.wordpress.com/2007/07/03/http-headers-and-the-php-header-function/</guid>
		<description><![CDATA[Introduction
Many beginning and intermediate PHP programmers seem to think the header() function  is some kind of strange voodoo. They work from examples and code snippets and are able to get things done with it,  but they don&#8217;t know quite how it works. That was certainly the  way I regarded header() the first [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firebird84vn.wordpress.com&blog=1069990&post=17&subd=firebird84vn&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p class="twocol" style="border-width:0;">Many beginning and intermediate PHP programmers seem to think the <code><a href="http://www.php.net/manual/function.header.php">header()</a></code> function  is some kind of strange voodoo. They work from examples and code snippets and are able to get things done with it,  but they don&#8217;t know quite how it works. That was certainly the  way I regarded <code>header()</code> the first time I saw it.</p>
<p>In reality, it&#8217;s  quite simple. In this tutorial, I&#8217;ll explain a little about how HTTP headers work, how they relate to PHP, and a little about their meta tag equivalents.</p>
<p class="twocol">Hopefully by the time you&#8217;re done reading this, you&#8217;ll feel more confident about how to use the <code>header()</code> function, and even have some new ideas about how it can help you. We&#8217;ll also cover some other important topics related to HTTP headers and PHP.  Before we talk about any programming at all, though, we need to quickly (and incompletely) go over how HTTP (<strong>H</strong>yper<strong>T</strong>ext <strong>T</strong>ransfer <strong>P</strong>rotocol) works in general.</p>
<h2><a title="http_overview" name="http_overview" id="http_overview"></a>HTTP Overview</h2>
<p class="fullwidth">&nbsp;</p>
<h3>Headers: words in a conversation</h3>
<p><a href="http://en.wikipedia.org/wiki/HyperText_Transfer_Protocol">HTTP</a> is the protocol (the set of &#8216;rules&#8217;) for transferring data (e.g. HTML in web pages, pictures, files) between web servers and client browsers, and usually takes place on <a href="http://en.wikipedia.org/wiki/Port_%28computing%29#Network_port">port</a> 80. This is where the &#8216;<code>http://</code>&#8216; in website URLs comes from.</p>
<p>The first time most people make a web page, they write the HTML on their computer, view it locally in a browser, upload it to their server, and view it on the web. It might seem like viewing a page locally and viewing it on the server is exactly the same, and that the only data going back and forth between the server and the browser is the HTML and any images included in the page. But there is actually a lot of other information that you do not see when you view a file on the web — the <em>headers</em>.</p>
<p>Headers can be separated into two broad types: <em>Request</em> headers that your browser sends to the server when you request a file, and <em>Response</em> headers that the server sends to the browser when it serves the file. Think of these headers as the words in a conversation taking place between the browser and the server. I like to imagine the server as a librarian, and the browser as a researcher asking for a library resource. The browser walks up to the server at the main desk (port 80) and says something like, &#8220;Hi, my name is Mozilla, and I&#8217;m looking for the resource with the call number &#8216;www.expertsrt.com&#8217;. Can you get it for me?&#8221; The server listens, and responds &#8220;Yes, I found it, let me send it to you. The data in the item is HTML text, and it says &#8216;<code>&lt;html&gt;</code>&#8230;&#8217;&#8221; The browser reads through, and comes to an image tag, and asks the server for item with the location in the <code>src</code> attribute. The server looks, finds the file and says &#8220;This file is a PNG image, and the data is&#8230;.&#8221; You get the idea.</p>
<p>Another conversation might go like this:</p>
<p><em>Browser:</em> Hi, I&#8217;m Mozilla, can I have the file at &#8216;www.expertsrt.com/moved.html&#8217;?<br />
<em>Server:</em> That file is no longer there, it is at &#8216;www.expertsrt.com/newloc.html&#8217;.<br />
<em>Browser:</em> Hi, I&#8217;m Mozilla, can I have the file at &#8216;www.expertsrt.com/newloc.html&#8217;?<br />
<em>Server:</em> I found the file. Look at it for 10 seconds and then ask me again. It&#8217;s HTML text and it reads&#8230;.<br />
&#8230;10 seconds&#8230;<br />
<em>Browser:</em>&gt; Hi, I&#8217;m Mozilla, can I have the file at &#8216;www.expertsrt.com/newloc.html&#8217;?<br />
<em>Server:</em> I found the file. Look at it for 10 seconds and then ask me again. It&#8217;s HTML text and it reads&#8230;.<br />
&#8230;10 seconds&#8230;<br />
<em>Browser:</em> Hi, I&#8217;m Mozilla, can I have the file at &#8216;www.expertsrt.com/newloc.html&#8217;?<br />
<em>Server:</em> I found the file. Look at it for 10 seconds and then ask me again. It&#8217;s HTML text and it reads&#8230;.<br />
&#8230;.and so on, until the browser is redirected by the user&#8230;.</p>
<p>As you can see, there is a lot going on that headers control. Using the <code>header()</code> function, you can make the server send any headers that you need want, which allows you to do some really cool things beyond just sending plain old HTML.</p>
<h3>Seeing the whole conversation</h3>
<p>Before moving ahead, let&#8217;s get a better idea of how HTTP headers work by viewing a webpage <em>without</em> a browser, so we can see the converation in is entirety. Start by opening a command prompt (in windows, go to Start-&gt;Run, type <code>cmd</code>, and click &#8220;OK&#8221;&#8230;if you&#8217;re using linux you probably already know). At the prompt, type:</p>
<p class="codelisting">&nbsp;</p>
<pre><code>telnet expertsrt.com 80</code></pre>
<p>and press Enter. This will connect you to expertsrt.com on port 80. Next, copy and paste just the text below:</p>
<p class="codelisting">&nbsp;</p>
<pre><code>GET / HTTP/1.1
Host: expertsrt.com</code></pre>
<p>Don&#8217;t worry if when you type or paste the text, it does not show up in your command window and all you see is the cursor &#8212; it is indeed being sent to the server. The first line says you are using the <code>GET</code> request method to get the resource <code>/</code> (i.e. the file in the base directory of the host), and that you are using HTTP version 1.1. The second tells the server which host you want to connect to. When you finish typing &#8216;expertsrt.com&#8217;, hit Enter twice (and twice only). You should almost immediately get a response that looks like:</p>
<p class="codelisting">&nbsp;</p>
<pre><code>HTTP/1.1 301 Moved Permanently
Date: Wed, 08 Feb 2006 07:44:07 GMT
Server: Apache/2.0.54 (Debian GNU/Linux) mod_auth_pgsql/2.0.2b1 mod_ssl/2.0.54 OpenSSL/0.9.7e
Location: http://www.expertsrt.com/
Content-Length: 233
Content-Type: text/html; charset=iso-8859-1

&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt;
&lt;html&gt;&lt;head&gt;
&lt;title&gt;301 Moved Permanently&lt;/title&gt;
&lt;/head&gt;&lt;body&gt;
&lt;h1&gt;Moved Permanently&lt;/h1&gt;
&lt;p&gt;The document has moved &lt;a href="http://www.expertsrt.com/"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/body&gt;&lt;/html&gt;
</code></pre>
<p>Whoops! Looks like we requested a resource that wasn&#8217;t there; it&#8217;s been permanently moved to the new Location <code>http://www.expertsrt.com</code>. If you were using a browser, you&#8217;d only see the HTML — everything before the first blank line is the headers. In fact, modern browsers are even smarter than that — when they see the <code>Location</code> header on the third line, they automatically go there so you don&#8217;t have to type in a new URL. Let&#8217;s go to the new URL. By this point, you probably got disconnected while you were reading this. If so, just press your up arrow on the keyboard to get your <code>telnet</code> command back, and press enter to reconnect. If you&#8217;re still connected, you can just go ahead and type the following:</p>
<p class="codelisting">&nbsp;</p>
<pre><code>GET / HTTP/1.1
Host: www.expertsrt.com</code></pre>
<p>and press Enter twice after the second line. You&#8217;ll get another similar response telling you that the page is <em>actually</em> at <code>http://www.expertsrt.com/index.php</code>. The server is particular, isn&#8217;t it? <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  Repeat the above, but this time type</p>
<p class="codelisting">&nbsp;</p>
<pre><code>GET /index.php HTTP/1.1
Host: www.expertsrt.com</code></pre>
<p>Notice that the name of the file we want is in the first line. This time we get flooded with text: the HTML from ERT&#8217;s homepage. The headers look like</p>
<p class="codelisting">&nbsp;</p>
<pre><code>HTTP/1.1 200 OK
Date: Wed, 08 Feb 2006 08:20:07 GMT
Server: Apache/2.0.54 (Debian GNU/Linux) mod_auth_pgsql/2.0.2b1 mod_ssl/2.0.54 OpenSSL/0.9.7e
X-Powered-By: PHP/4.4.0
Transfer-Encoding: chunked
Content-Type: text/html</code></pre>
<p>Simple, no?. Let&#8217;s move forward and see how this relates to your programming. Don&#8217;t worry if you didn&#8217;t understand every single thing that we just did. The important thing is to have a general feel for how the browser and server talk to each other, and to realize that <em>there is nothing magic about it.</em> The take home points are:</p>
<ul>
<li>The browser and the server talk to each other using headers</li>
<li>Headers are sent before the main content, and are separated from the main content by a a   double-<a href="http://www.google.com/search?q=define%3ACRLF">CRLF</a>/newline.</li>
<li>In the header section, there is one header per line. The name of the header comes first, followed by a colon and a space, followed by the content/value of the header:
<p class="codelisting"><code>Header-Name: header-value</code></p>
</li>
<li>Headers can contain many types of information and instructions that the server and browser use to help each other know what to do next</li>
</ul>
<p class="note" style="margin-bottom:2em;"><strong>Note</strong>: If you&#8217;re the type who likes to really dig into the details, you can look at <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</a> for the complete HTTP/1.1 specification in all its glory. In particular, <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14">Section 14</a> offers a complete definition for each header field.</p>
<p class="twocol" style="border-width:0;">&nbsp;</p>
<h2><a title="phpheaders" name="phpheaders" id="phpheaders"></a>PHP <code>header()</code>: The Basics</h2>
<p>Notice the response headers <code>X-Powered-By: PHP/4.4.0</code> and <code>Content-Type: text/html</code> that were returned when we finally got to the homepage. PHP was designed from the beginning to output HTML (the &#8216;H&#8217; in PHP stands for &#8216;Hypertext&#8217;), and the first time a script generates output (e.g. by using <code>echo</code>), PHP automatically includes those headers for you. This is very convenient, but also contributes to the confusion many PHP beginners have regarding headers — in more &#8216;bare bones&#8217; languages like Perl that were not originally designed for the web, sending output without including your own headers produces the dreaded &#8216;500 Internal Server Error&#8217;, so Perl web programmers have no choice but to learn about headers immediately.</p>
<p>The <code><a href="http://www.php.net/manual/function.header.php">header()</a></code> function sends HTTP response headers; nothing more, nothing less.</p>
<hr />
<p class="twocol"> Using this function, you can make your scripts send headers of your choosing to the browser, and create some very useful and dynamic results. However, the first thing you need to know about the <code>header()</code> function is that you have to use it <strong>before</strong> PHP has sent any output (and therefore its default headers).</p>
<p>I doubt there is a PHP programmer in the world who has never seen an error that looks like</p>
<p class="codelisting"> <strong>Warning:</strong> Cannot modify header information &#8211; headers already sent by&#8230;..</p>
<p>As we said above, the response headers are separated from the content by a blank line. This means you can only send them <em>once</em>, and if your script has any output (even a blank line or space before your opening <code><span style="color:#0000bb;">&lt;?php</span></code> tag), PHP does so without asking you. For example, consider the script below, which seems logical enough:</p>
<p class="fullwidth">&nbsp;</p>
<p class="codelisting"><code><span style="color:#000000;"> Welcome to my website!&lt;br /&gt;<br />
<span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(</span><span style="color:#0000bb;">$test</span><span style="color:#007700;">){<br />
echo </span><span style="color:#dd0000;">"You're in!"</span><span style="color:#007700;">;<br />
}<br />
else{<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/someotherpage.php'</span><span style="color:#007700;">);<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>What this script is <em>trying</em> to do is redirect the visitor using the <code>Location</code> header if <code>$test</code> is not true. Do you see the problem? The &#8216;Welcome&#8230;&#8217; text gets sent no matter what, so the headers are automatically sent. By the time <code>header()</code> is called, it&#8217;s already too late: instead of getting redirected, the user will just see an error message (or if you have error reporting off, nothing but the &#8216;Welcome&#8230;&#8217; text).</p>
<p>There are basically two solutions to this. The first is to rewrite the code
</p>
<p class="fullwidth">&nbsp;</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(</span><span style="color:#0000bb;">$test</span><span style="color:#007700;">){<br />
echo </span><span style="color:#dd0000;">'Welcome to my website&lt;br /&gt;You're in!'</span><span style="color:#007700;">;<br />
}<br />
else{<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/someotherpage.php'</span><span style="color:#007700;">);<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>The second is <a href="http://www.php.net/outcontrol">output buffering</a>, which can be somewhat more elegant and easy to use. In our example above, rewriting the code wasn&#8217;t much trouble, but imagine if there had been quite a bit of HTML to move around — it could be pretty cumbersome, and it might make our code harder to follow. While our first example caused an error, the <em>logic of the program</em> was fine. Output buffering allows you to hold on to (&#8216;buffer&#8217;) output (even HTML outside of PHP code tags) and send it to the browser only when you explicitly say to do so. This way you can program however you would like to, and explicitly send the output after you&#8217;ve specified any headers you need to. The two relevant functiosns are <code><a href="http://www.php.net/manual/function.ob-start.php">ob_start()</a></code>, which turns output buffering on, and <code><a href="http://www.php.net/manual/function.ob-flush.php">ob_flush()</a></code>, which sends the content that has accumulated in the buffer:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
ob_start</span><span style="color:#007700;">();  </span><span style="color:#666666;">//begin buffering the output<br />
</span><span style="color:#0000bb;">?&gt;<br />
</span>Welcome to my website!<br />
<span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(</span><span style="color:#0000bb;">true</span><span style="color:#007700;">){<br />
echo </span><span style="color:#dd0000;">"You're in!"</span><span style="color:#007700;">;<br />
}<br />
else{<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/someotherpage.php'</span><span style="color:#007700;">);<br />
}</span></span></code></p>
<p><span style="color:#0000bb;">ob_flush</span><span style="color:#007700;">(); </span><span style="color:#666666;">//output the data in the buffer<br />
</span><span style="color:#0000bb;">?&gt;</span></p>
<p>I encourage you to read more about all of the output buffering functions, which can be quite useful. You should flush the output buffer as soon as possible, especially if you have quite a bit of content to send. Otherwise, your page will appear to load slower, becuase the content will be sent only after it has been entirely assembled, rather than as it is available.
</p>
<p class="note"><strong>Note: The 2nd argument</strong> If you call <code>header()</code> more than once for the same header field, the value for that header will be the one included in the <em>last</em> call you made. For example,</p>
<p class="codelisting"> <code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Some-Header: Value-1'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Some-Header: Value-2'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>would produce the header <code>Some-Header: Value-2</code>. You can cause both headers to be sent by using the second <em><code>replace</code></em> argument for header, which is <code>true</code> by default. If you set this to <code>false</code>, the second header value will not replace the first, and both will be sent. So the code</p>
<p class="codelisting"> <code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Some-Header: Value-1'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Some-Header: Value-2'</span><span style="color:#007700;">, </span><span style="color:#0000bb;">false</span><span style="color:#007700;">); </span><span style="color:#666666;">//don't replace the first value<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>will produce the header <code>Some-Header: Value-1, Value-2</code>. You will rarely need this, but is good to know.</p>
<p>Armed with a good understanding of how HTTP headers and PHP work together, let&#8217;s look at some specific examples of using this functionality.</p>
<h2><a title="phpheaderex" name="phpheaderex" id="phpheaderex"></a>PHP <code>header()</code>: Some Examples</h2>
</p>
<p class="note"><strong>Note:</strong> The code snippets appearing below are just that: snippets from complete working code. When you you include them in your own programs, remember to define all your variables, assign default values, and adhere to other good programming practices.</p>
<h3>Redirecting with the <code>Location</code> header</h3>
<p>We&#8217;ve seen this one a couple times above: it redirects the browser.</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/new_location.html'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>While you can somtimes get away with supplying a relative URL for the value, according to the HTTP specification, you should really use an absolute URL.</p>
<p>One mistake that is easy to make with the <code>Location</code> header is not calling <code><a href="http://www.php.net/manual/function.exit.php">exit</a></code> directly afterwards (you may not always want to do this, but usually you do). The reason this is a mistake is that the PHP code of the page continues to execute even though the user has gone to a new location. In the best case, this uses system resources unnecessarily. In the worst case, you may perform tasks that you never meant to. Consider the code below:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#666666;">//Redirect users with access level below 4<br />
</span><span style="color:#007700;">if (</span><span style="color:#0000bb;">check_access_level</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$username</span><span style="color:#007700;">) &lt; </span><span style="color:#0000bb;">4</span><span style="color:#007700;">){<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/someotherpage.php'</span><span style="color:#007700;">);<br />
}</span></span></code></p>
<p><span style="color:#666666;">//Mail users with higher access level the secret code<br />
</span><span style="color:#0000bb;">mail_secret_code</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$username</span><span style="color:#007700;">);<br />
echo </span><span style="color:#dd0000;">&#8216;The secret email is on its way!&#8217;</span><span style="color:#007700;">;<br />
</span><span style="color:#0000bb;">?&gt;</span></p>
<p>Unauthorized users are indeed redirected, but in fact, they too will receive the email, because the script continues to run. To avoid this, the part for authorized users could be wrapped in an <code>else{}</code> statement, but it is cleaner and easier to call <code>exit</code> immediately after the <code>header</code> command to end the execution of the script:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#666666;">//Redirect users with access level below 4<br />
</span><span style="color:#007700;">if (</span><span style="color:#0000bb;">check_access_level</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$username</span><span style="color:#007700;">) &lt; </span><span style="color:#0000bb;">4</span><span style="color:#007700;">){<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Location: http://www.mysite.com/someotherpage.php'</span><span style="color:#007700;">);<br />
exit; </span><span style="color:#666666;">//stop script execution<br />
</span><span style="color:#007700;">}</span></span></code></p>
<p><span style="color:#666666;">//Mail users with higher access level the secret code<br />
</span><span style="color:#0000bb;">mail_secret_code</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$username</span><span style="color:#007700;">);<br />
echo </span><span style="color:#dd0000;">&#8216;The secret email is on its way!&#8217;</span><span style="color:#007700;">;<br />
</span><span style="color:#0000bb;">?&gt;</span></p>
<h3>Redirecting with the <code>Refresh</code> header</h3>
<p>The <code>Refresh</code> redirects users like the <code>Location</code> header does, but you can add a delay before the user is redirected. For example, the following code would redirect the user to a new page after displaying the current one for 10 seconds:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Refresh: 10; url=http://www.mysite.com/otherpage.php'</span><span style="color:#007700;">);<br />
echo </span><span style="color:#dd0000;">'You will be redirected in 10 seconds'</span><span style="color:#007700;">;<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>Another common application is to force a page to update repeatedly by &#8216;redirecting&#8217; to the current page (see the second &#8216;conversation&#8217; <a href="http://www.expertsrt.com/tutorials/Matt/HTTP_headers.html#secondconv">above</a>). For example, here is a simple page that will &#8216;count&#8217; down from 10, with a 3 second pause between numbers:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(!isset(</span><span style="color:#0000bb;">$_GET</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'n'</span><span style="color:#007700;">])){<br />
</span><span style="color:#0000bb;">$_GET</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'n'</span><span style="color:#007700;">] = </span><span style="color:#0000bb;">10</span><span style="color:#007700;">;<br />
}</span></span></code></p>
<p>if(<span style="color:#0000bb;">$_GET</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'n'</span><span style="color:#007700;">] &gt; </span><span style="color:#0000bb;">0</span><span style="color:#007700;">){<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">&#8216;Refresh: 3; url=&#8217; </span><span style="color:#007700;">. </span><span style="color:#0000bb;">$_SERVER</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'PHP_SELF'</span><span style="color:#007700;">].</span><span style="color:#dd0000;">&#8216;?n=&#8217; </span><span style="color:#007700;">. (</span><span style="color:#0000bb;">$_GET</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'n'</span><span style="color:#007700;">]-</span><span style="color:#0000bb;">1</span><span style="color:#007700;">)  );<br />
echo </span><span style="color:#0000bb;">$_GET</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'n'</span><span style="color:#007700;">];<br />
}<br />
else{<br />
echo </span><span style="color:#dd0000;">&#8216;BLAST OFF!&#8217;</span><span style="color:#007700;">;<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span>
</p>
<p class="note"><strong>Note:</strong> If the refresh time is set to 0, then the <code>Refresh</code> header is effectively the same as the <code>Location</code> header.</p>
<h3>Serving different types of files and generating dynamic content using the <code>Content-Type</code> header</h3>
<p>The <code>Content-Type</code> header tells the browser what type of data the server is about to send. Using this header, you can have your PHP scripts output anything from plain text files to images or zip files. The table below lists frequently-used <a href="http://en.wikipedia.org/wiki/Mime_type">MIME types</a>:</p>
<p class="twocol" style="width:55%;border-width:0;">You can do several interesting things with this. For example, perhaps you want to send the user a pre-formatted text file rather than HTML:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Type: text/plain'</span><span style="color:#007700;">);<br />
echo </span><span style="color:#0000bb;">$plain_text_content</span><span style="color:#007700;">;<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>Or perhaps you&#8217;d like to prompt the user to download the file, rather than viewing it in the browser. With the help of the <code>Content-Disposition</code> header, it&#8217;s easy to do, and you can even suggest a file name for the user to use:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Type: application/octet-stream'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Disposition: attachment; '<br />
</span><span style="color:#007700;">.</span><span style="color:#dd0000;">'filename="plain_text_file.txt"'</span><span style="color:#007700;">);<br />
echo </span><span style="color:#0000bb;">$plain_text_content</span><span style="color:#007700;">;<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>Maybe you need to serve a file for download, but you&#8217;d like to obscure its true location and name, and only serve it to users who are logged in:</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(</span><span style="color:#0000bb;">$b_is_logged_in</span><span style="color:#007700;">){<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Type: application/octet-stream'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Disposition: attachment; '<br />
</span><span style="color:#007700;">.</span><span style="color:#dd0000;">'filename="'</span><span style="color:#007700;">.</span><span style="color:#0000bb;">$different_filename</span><span style="color:#007700;">.</span><span style="color:#dd0000;">'"'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">readfile</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'/path/to/files/' </span><span style="color:#007700;">. </span><span style="color:#0000bb;">$filename</span><span style="color:#007700;">);<br />
}<br />
else{<br />
echo </span><span style="color:#dd0000;">'You are not authorized to view this file'</span><span style="color:#007700;">;<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>Perhaps you&#8217;ve dynamically generated an image using PHP&#8217;s <a href="http://www.php.net/manual/ref.image.php">image functions</a> and you want to display it to the user. You could create a file <code>build_image.php</code> like this</p>
<p class="twocol" style="width:35%;">
<table style="margin-bottom:2em;">
<tr>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>text/html</td>
<td>HTML (PHP default)</td>
</tr>
<tr>
<td>text/plain</td>
<td>Plain Text</td>
</tr>
<tr>
<td>image/gif</td>
<td>GIF Image</td>
</tr>
<tr>
<td>image/jpeg</td>
<td>JPEG Image</td>
</tr>
<tr>
<td>image/png</td>
<td>PNG Image</td>
</tr>
<tr>
<td>video/mpeg</td>
<td>MPEG Video</td>
</tr>
<tr>
<td>audio/wav</td>
<td>WAV Audio</td>
</tr>
<tr>
<td>audio/mpeg</td>
<td>MP3 Audio</td>
</tr>
<tr>
<td>video/mov<br />
video/quicktime</td>
<td>Quicktime Video</td>
</tr>
<tr>
<td>video/x-ms-wmv</td>
<td>Windows WMV video</td>
</tr>
<tr>
<td>audio/x-ms-wma</td>
<td>Windows WMA audio</td>
</tr>
<tr>
<td>audio/x-realaudio</td>
<td>RealPlayer Audio/Video (.rm)</td>
</tr>
<tr>
<td>audio/x-pn-realaudio</td>
<td>RealPlayer Audio/Video (.ram)</td>
</tr>
<tr>
<td>video/x-msvideo<br />
video/avi</td>
<td>AVI Video</td>
</tr>
<tr>
<td>application/pdf</td>
<td>PDF Document</td>
</tr>
<tr>
<td>application/msword</td>
<td>MS Word .doc file</td>
</tr>
<tr>
<td>application/zip</td>
<td>Zip File</td>
</tr>
<tr>
<td>application/octet-stream</td>
<td>Misc. data. Use to force download or open with application.*</td>
</tr>
<tr>
<td>x-foo/x-bar</td>
<td>Misc. data. Use to force download or open with application.*</td>
</tr>
</table>
<p class="fullwidth">&nbsp;</p>
<p class="codelisting"><code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#666666;">//build the image above<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Content-Type: image/jpeg'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">imagejpeg</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$image_resouce</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">?&gt;</span>  </span> </code>
</p>
<p class="note" style="margin:30px;"><strong>Note</strong>: Beware of <a href="http://www.php.net/magic_quotes">magic_quotes</a>! PHP&#8217;s automatic escaping of special characters with a backslash may seem like a good idea at first, but most good programmers generally agree that it (a) encourages sloppy programming that does not validate input and (b) causes annoyances in well-written code that would not occur if &#8220;magic quoting&#8221; were turned off. One such annoyance is the corruption of binary data. In the example above, if <a href="http://www.php.net/manual/en/ref.info.php#ini.magic-quotes-runtime"><code>magic_quotes_runtime</code></a> is on, the data that <code>readfile()</code> outputs may have backslashes added to it, thus corrupting the file that is sent to the user. Ideally, you should turn <code>magic_quotes_runtime</code> off in your <code>php.ini</code> file to avoid this, but if you do not have access to the configuration file, you can also use the <a href="http://www.php.net/manual/en/function.set-magic-quotes-runtime.php">set_magic_quotes_runtime()</a> function (pass is the <code>0</code> (zero) integer) to turn the setting off.</p>
<p>Happily, the <a href="http://www.php.net/%7Ederick/meeting-notes.html#magic-quotes">minutes</a> of a recent PHP Developer meeting show that they have decided to abandon magic quotes in future versions (6+) of PHP. Until everyone upgrades, however, keeping the problems this feature can cause in mind can save you quite a bit of trouble and frustration.<br />
You might pass the parameters necessary to generate the image via the URL so you can access them in the <code>$_GET</code> array. Then in another page, you might include this image using an <code>img</code> tag:</p>
<p class="codelisting"><code><span style="color:#000000;"> &lt;img src="build_image.php<span style="color:#0000bb;">&lt;?php </span><span style="color:#007700;">echo </span><span style="color:#dd0000;">"?$user_id&amp;$caption"</span><span style="color:#007700;">; </span><span style="color:#0000bb;">?&gt;</span>"&gt;</span> </code></p>
<p>The possibilities are more or less endless. The more PHP programming you do, the more you will find that the <code>Content-Type</code> header truly is your friend.</p>
<p class="note"><strong>Note</strong>: The way that browser are <em>supposed</em> to handle content of various MIME types, and the way they actually <em>do</em> may not always be consistent (especially with Internet Explorer), so you&#8217;re well-advised to test your pages in the browsers you need to support to make sure they behave as expected. The PHP Manual has many helpful tips in the <a href="http://www.php.net/manual/function.header.php#usernotes">user-contributed comments</a> on the <code>header()</code> page.</p>
<h3>Preventing Page Caching</h3>
<p>PHP pages often generate very dynamic content, and to prevent users from missing updates by viewing cached pages, it is often helpful to be able to tell browsers not to cache certain pages. The following snippet works quite well on  the browsers that are likely to visit your site:</p>
<p class="codelisting"> <code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Cache-Control: no-cache, no-store, must-revalidate'</span><span style="color:#007700;">); </span><span style="color:#666666;">//HTTP/1.1<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Expires: Sun, 01 Jul 2005 00:00:00 GMT'</span><span style="color:#007700;">);<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Pragma: no-cache'</span><span style="color:#007700;">); </span><span style="color:#666666;">//HTTP/1.0<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>The <code>Expires</code> header can be any date in the past. As with MIME types, browsers (especially older ones) may not always listen properly to your caching instructions (although most modern ones will).</p>
<h3>Other Applications</h3>
<p>There are other ways you can use headers as well, such as setting the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Response Code</a>, or in performing <a href="http://www.php.net/manual/features.http-auth.php">HTTP Authentication</a> (if you are running PHP as an Apache module). Now that you understand how <code>header()</code> works and how to use it, you&#8217;ll be able to do all sorts of things you might not have thought of before.</p>
<p><a title="requestheaders" name="requestheaders" id="requestheaders"></a></p>
<h2>Request Headers in PHP</h2>
<p>We&#8217;ve covered some of the things you can do with response headers above. We can also get a great deal of information from the request headers received by the server from the browser. There are two ways to access these. First, many of the values in the <a href="http://www.php.net/reserved.variables"><code>$_SERVER</code> array</a> are determined from the request headers. Second, if PHP is installed as an Apache module, then <a href="http://www.php.net/manual/function.apache-request-headers.php">apache_request_headers()</a> will return an array of all request headers (even those not in <code>$_SERVER</code>).</p>
<h3>Security first: don&#8217;t trust request headers</h3>
<p>Since request headers are set by the browser, which is controlled by the client, <strong>you must never trust request headers for information that is important to the security of your site</strong>. A good example is the <code>$_SERVER['HTTP_REFERER']</code> variable, which <em>should</em> hold the URL of the page that referred the user to the current one. A common mistake among beginners is to think that they can use this to make sure that users only access pages through a certain path, and that they therefore do not need to worry about server side data validation. For example, consider this code, which attempts to make sure that data has been submitted from a specific page, rather than a custom form on another website:</p>
<p class="codelisting"> <code><span style="color:#000000;"> <span style="color:#0000bb;">&lt;?php<br />
</span><span style="color:#007700;">if(</span><span style="color:#0000bb;">$_SERVER</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'HTTP_REFERER'</span><span style="color:#007700;">] != </span><span style="color:#dd0000;">'http://www.mysite.com/myform.html'</span><span style="color:#007700;">){<br />
</span><span style="color:#0000bb;">header</span><span style="color:#007700;">(</span><span style="color:#dd0000;">'Refresh: 5; url=http://www.mysite.com/myform.html'</span><span style="color:#007700;">);<br />
echo </span><span style="color:#dd0000;">'You must use the form on my site...redirecting now.'</span><span style="color:#007700;">;<br />
}<br />
else{<br />
</span><span style="color:#0000bb;">insert_data</span><span style="color:#007700;">(</span><span style="color:#0000bb;">$_POST</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'var1'</span><span style="color:#007700;">], </span><span style="color:#0000bb;">$_POST</span><span style="color:#007700;">[</span><span style="color:#dd0000;">'var2'</span><span style="color:#007700;">]);<br />
}<br />
</span><span style="color:#0000bb;">?&gt;</span> </span> </code></p>
<p>This might work to deter an unsophisticated hacker who is using his web browser to submit data through a custom form, but someone who is a little more savvy could easily submit data via a telnet session like we did above, including the request header
</p>
<p class="codelisting"> <code>Referer: http://www.mysite.com/myform.html</code></p>
<p>and easily defeat this &#8216;protection&#8217;. The moral of the story is: use HTTP request headers to gather statistics and to help make the user experience more pleasant — most request headers you receive will be supplied by standard browsers and will be entirely truthful&#8230;But <strong>do not</strong> rely on request headers for any issues pertaining to security.</p>
<h3>Using HTTP request headers</h3>
<p>There are several things you can do with these. Using <code>$_SERVER['HTTP_USER_AGENT']</code> you can detect the type of browser the user says it has. You might check the <code>$_SERVER['HTTP_ACCEPT_LANGUAGE']</code> (perhaps along with <code>$_SERVER['HTTP_ACCEPT_CHARSET']</code> and some <a href="http://www.expertsrt.com/articles/Rod/city_country_IP.php">IP address geolocation</a>) to help determine the best language in which to serve your pages to a given user. Although <code>$_SERVER['HTTP_REFERER']</code> is not reliable for security purposes, it could be useful as an aid for building statistics about your website traffic or customizing content to match the path the user took to reach a given page. If for some reason you want to manipulate the raw query string used when the page was accessed, you can look in <code>$_SERVER['QUERY_STRING']</code>. Looking in <code>$_SERVER['REQUEST_METHOD']</code> will tell you whether your page was accessed via  <code>GET</code> or <code>POST</code>. There&#8217;s quite a bit of information there for you to find creative uses for.  <a title="metaequiv" name="metaequiv" id="metaequiv"></a></p>
<h2>HTML Meta Tag HTTP Header Equivalents</h2>
<p>Chances are, before reading this article, you have seen or used the HTML meta tag below to redirect a user:</p>
<p class="codelisting"> <code>&lt;meta http-equiv="refresh" content="0;http://www.mysite.com/somepage.html" /&gt;</code></p>
<p>Look familiar? The &#8216;http-equiv&#8217; meta tags are &#8216;equivalent&#8217; to HTTP response headers, and were introduced so that people writing HTML pages without server side programming would have access to the powerful functionality described above. Using these meta tags is simple: they can be placed anywhere in the <code>&lt;head&gt;</code> of the document, and their <code>http-equiv</code> attribute contains the header name, while the <code>content</code> attribute contains the value for the header.</p>
<p>I&#8217;ve found that these, like the HTTP headers in general, often produce confusion, but now they should seem quite simple to you. Although I usually prefer to use the PHP <code>header()</code> function, these meta tag HTTP header equivalents are often very handy for things like specifying the character set. For example, I often use this is my HTML pages (and sometimes my PHP ones):</p>
<p class="codelisting"> <code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;</code></p>
<p class="note">  <strong>Note:</strong> Support for HTTP headers as equivalet meta tags is not uniformally supported, so it is usually safer and  faster to use the headers themselves if you can. Also, it should be obvious that some headers and values will not work as meta  equivalents: you cannot set the <code>Content-Type</code> to <code>image/png</code> when the real headers have been sent and the  browser is already reading the HTML <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p><a title="conclusion" name="conclusion" id="conclusion"></a></p>
<h2>Conclusion</h2>
<p>Now that you are done with this article, you should have a pretty firm grasp of how HTTP works, how request and response headers are used, and how you can employ this functionality in your programming. This reasonably detailed knowledge should also enable you to start thinking more critically about your web application efficiency and security. I hope that as you move forward with your programming, you will find that you&#8217;ve become quite comfortable working with HTTP headers, and that you are able to exploit them to make your job easier and your pages better.</p>
<p>As a parting thought, remember that headers are like words: they convey information and ask for certain actions to be performed, but by themselves they don&#8217;t force anything to happen. 99.9% of the time, cooperative browsers are talking to cooperative servers, and everything happens smoothly. But you have to remember that, as in life, every once in a while you&#8217;ll run across a jerk (a hacker), or someone who&#8217;s got his own way of doing things (Internet Explorer). Web development is very much a job of customer service, so you&#8217;ve got to do your best to keep the crooks out, and accomodate the customers with &#8217;special needs.&#8217;</p>
<p>Source: http://www.expertsrt.com</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/firebird84vn.wordpress.com/17/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/firebird84vn.wordpress.com/17/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/firebird84vn.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/firebird84vn.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/firebird84vn.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/firebird84vn.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/firebird84vn.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/firebird84vn.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/firebird84vn.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/firebird84vn.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/firebird84vn.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/firebird84vn.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=firebird84vn.wordpress.com&blog=1069990&post=17&subd=firebird84vn&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://firebird84vn.wordpress.com/2007/07/03/http-headers-and-the-php-header-function/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/398741d3a6b8beddeb1f0cf3971b706a?s=96&#38;d=identicon" medium="image">
			<media:title type="html">firebird84vn</media:title>
		</media:content>
	</item>
	</channel>
</rss>