Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

header

(PHP 3, PHP 4, PHP 5)

header -- Send a raw HTTP header

Description

void header ( string string [, bool replace [, int http_response_code]] )

header() is used to send a raw HTTP header. See the HTTP/1.1 specification for more information on HTTP headers.

Замечание: Since PHP 4.4.2 and PHP 5.1.2 this function prevents more than one header to be sent at once as a protection against header injection attacks.

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

<?php
header
('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

The second optional http_response_code force the HTTP response code to the specified value. (This parameter is available in PHP 4.3.0 and higher.)

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
header
("HTTP/1.0 404 Not Found");
?>

Замечание: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.

<?php
header
("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

Замечание: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

<?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

Замечание: Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

<?php
header
("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

Замечание: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
?>

Замечание: As of PHP 4, you can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Замечание: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

Замечание: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

See also headers_sent(), setcookie(), and the section on HTTP authentication.



headers_list> <getservbyport
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
header
Anonymous
30-Oct-2007 09:22
When streaming a PDF file I would get the error "'There was an error opening this document.  This file cannot be found."  This seemed to only happen in IE6 that I'm aware of.
After changing the Content-Disposition to inline (rather then attachment) it worked properly.
s_donk_donk at yahoo dot com
27-Oct-2007 11:29
the things from moehbass at gmail dot com is very useful.. thx!
but 1 thing i noticed, as written:

if(isset($_POST['ok'])) {
    if(isset($_POST['yesNo']))
        header('Location: http://www.google.com/');
    else
        header('Location: http://www.yahoo.com/');
}

You can see it live at:
http://labella-pizza.com/header.php

it works fine, only if u put the php on the top.

when u open the link above, u can copy paste the code included in the textarea to try it..
BUT when u run it, it didnt work.
as u can see, the php code is below the html code.

u have 1 simple thing to do :
cut the php code and paste it at the top.. before the html code..
and run it...
then u'll find it works fine! ^^
Dylan at WeDefy dot com
13-Oct-2007 08:17
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);

// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");

// 303 See Other
header("Location: /foo.php",TRUE,303);

// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
tyler at isimple dot net
20-Sep-2007 04:10
I was struggling with session problems for a long time today and I tried everything. Mostly when I was using a header location on IE, it wouldn't pass the vars.

For anyone who has tried everything, the thing that handled it for me was: suExec. Right when I disabled suExec sessions with headers on all browsers started working successfully.

Hope this saves some people a few hours of studious research.

Tyler
predefining at gmail dot com
15-Sep-2007 08:39
I couldn't find an example how to send a status code without the need of resolving the description (e.g. "Not found"). So I was thinking of an array containing all status codes and their descriptions but looking them up can slow down the execution of the script - depending on the array's size. I've looked for an alternative: The solution is to use the third parameter which can send a status code without the need to specify its description! header() will ONLY send the status code if the first parameter is not (!) empty.

function sendStatusCode($statusCode)
{
    header(' ', true, $statusCode);
}

sendStatusCode(404);

This will only work if you're using PHP 4.3.0 or higher. Otherwise you rely on one of the following methods:

header('Status: 404 Not Found');
header('HTTP/1.0 404 Not Found');

Best regards,
Tim
miha dot wagner at gmail dot com
15-Sep-2007 05:35
To avoid the "Headers already sent" error, I just use output buffering:

<?php
// Set output buffering
ob_start();

// Print something
print "Hello World!";

// Set a cookie?
setcookie("name", "value", time()+9999);

// Or send a header
header("Location: http://www.php.net/");

// Everything works!
?>
fantasysportswire at yahoo dot com
13-Sep-2007 05:52
There is a comment below that says:

"Just a little reminder to always use exit(); ! It will save you alot of gray hairs!!!"

... just make sure you are not including that file in another script if you do that... you will gain many more gray hairs than you will ever save in that case.
ryanhanekamp at yahoo dot com
11-Aug-2007 02:10
I strongly recommend the "Live HTTP Headers" plugin for Firefox for any work when manually setting headers. (Find it in the addons section on mozilla.com) This allows you to see the headers your PHP script and server are sending, plus Firefox's request headers.

One important thing to note is a conflict with many of the scripts here, including in lasitha dot alawatta's Excel post just a few below me, is that sending multiple headers of the same type from your script does not actually cause multiple lines of output to the browser, at least for the version of PHP5 I'm running, and it's doubtful the browser would process any other than the last line anyhow.

So sending multiple "Pragma: " or "Cache-Control: " headers results in only the last one set in your script to actually be sent.

Also, it's already been pointed out, but setting "Cache-Control: Pre-Check=0, Post-Check=0" does absolutely nothing. I believe only MSIE even uses these values and it specifically IGNORES both of them when both are set to zero.

I've actually had more trouble trying to encourage caching than preventing it, because PHP sends "Cache-Control" and "Pragma" headers either always or at least always with sessions on (and I always have sessions on). The trick is to always send BOTH "Cache-Control" and "Pragma" because if they conflict it's completely up to the browser to resolve. And if you have a custom server in PHP like I'm working on right now, you'll need to sniff for $_SERVER['IF-MODIFIED-SINCE'] and serve up "HTTP/1.1 304 Not Modified" as appropriate.

If you are doing something like this and want to ensure caching of static files, the best way I found was to give an honest "Last-Modified", set an "Expires:" a reasonable time in the future (a few minutes through the year 2038, depending on what you're doing), set "Cache-Control" to "private" or "public", and stay away from "Max-Age".
JanisB
10-Aug-2007 06:53
<?php header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); ?> - very popular date, according to Google used at least in 52,900 code snippets - is wrong, because on 07/26/1997 was Saturday
StevenMc
09-Aug-2007 07:48
It is important to note that implementation of the following script will destroy all GET and POST data.

<?PHP
header
("location: http://www.example.com");
exit;
?>
eblejr AT phrebh DOT com
31-Jul-2007 08:14
In response to phpnet at stccorp dot net: the reason that Firefox chokes on viewing the PDF is that FF has no native PDF support.
Kal
29-Jul-2007 01:07
I spent a long time trying to determine why Internet Explorer 7 wasn't prompting the user to save a download based on the filename specified on a "'Content-Disposition: attachment; filename=..." header line.

I eventually determined that my Apache installation was adding an additional header: "Vary: Host", which was throwing IE - as per http://support.microsoft.com/kb/824847

I found manually setting the Vary header from within PHP as follows header('Vary: User-Agent'); allowed IE to behave as intended.

Hope this saves someone else some time,

- Kal
lasitha dot alawatta at gmail dot com
28-Jul-2007 10:15
Create MS-Excel file:

<?php

    $export_file
= "my_name.xls";
   
ob_end_clean();
   
ini_set('zlib.output_compression','Off');
   
   
header('Pragma: public');
   
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");                  // Date in the past   
   
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
   
header('Cache-Control: no-store, no-cache, must-revalidate');     // HTTP/1.1
   
header('Cache-Control: pre-check=0, post-check=0, max-age=0');    // HTTP/1.1
   
header ("Pragma: no-cache");
   
header("Expires: 0");
   
header('Content-Transfer-Encoding: none');
   
header('Content-Type: application/vnd.ms-excel;');                 // This should work for IE & Opera
   
header("Content-type: application/x-msexcel");                    // This should work for the rest
   
header('Content-Disposition: attachment; filename="'.basename($export_file).'"');

?>
bt at yotm dot com
25-Jul-2007 02:19
in reply to phpnet's post, this line looks wrong:

header('Content-Length: $len');

should it be

header('Content-Length: '.$len);

regards
jasper at jtey dot com
12-Jul-2007 07:30
If you are finding that header() is not working for no obvious reason, make use of the headers_sent() function to drill down to the cause of the problem.

Consider the following scenario,

<?php
// Sign out
signOut();

// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

If for some reason, the header() call to redirect is not working, there won't be any error messages, making it difficult to debug.  However, using headers_sent(), you may easily find the source of the problem.

<?php
// Sign out
signOut();

/*
 * If headers were already sent for some reason,
 * the upcoming call to header() will not work...
 */
if(headers_sent($file, $line)){
   
// ... where were the mysterious headers sent from?
   
echo "Headers were already sent in $file on line $line...";
}

// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

As the documentation states, "header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP."  In the above debugging solution, you will find out exactly where any of these problematic output or blank lines exist.  You should then be able to resolve the issues with much more ease than if you hunted for the problems aimlessly.
moehbass at gmail dot com
10-Jul-2007 02:40
It says above:
"Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. ..."

But check this out: this code runs fine: (take a closer look!)

...
put your html stuff here
...
Then this:

if(isset($_POST['ok'])) {
    if(isset($_POST['yesNo']))
        header('Location: http://www.google.com/');
    else
        header('Location: http://www.yahoo.com/');
}

You can see it live at:
http://labella-pizza.com/header.php
phpnet at stccorp dot net
30-Jun-2007 09:27
This code works perfectly on explorer 6. It displays NOTHING on firefox 2.  I tried every combination in this page and I always get the same thing in firefox. I am running on iis5, windows xp, php 5.2.3

Why firefox is not capable of displaying the pdf and explorer has no problems???

$filename='test.pdf';
$len = filesize($filename);
header('Content-type: application/pdf');
header('Content-Length: $len');
header('Content-Disposition: inline;    filename="test.pdf"');
readfile($filename);
Alcator
28-Jun-2007 05:02
I thought I'd share this nifty little code that works with headers.

In many situations, you may be asked to obfuscate actual downloadable files location, or perhaps only allow logged users to download a file.

In this example, I'm offering alternate download link for those who use old Internet Explorer; feel free to remove the whole alternate part as needed.

This is translated fragment of actual used code.

<?php

echo '<a href="./provide_file.php?file='.$id.'relid='.$url.'">Direct download link</a>'. // COMMENT: call provide_file.php with ID of the file and relation identifier (relid) that is used to authenticate user.
//output continues here:
'<br /><br />
    If your browser doesn'
t offer you the file for saving, please try the following link instead:
                       
'.(IsSet($_REQUEST['dl'])?'<a href="'.$FileRecord['filename'].'">DOWNLOAD FILE</a>':
                        '
<a href="./?mat='.$id.'&amp;dl=1">Go to download</a>'); // the trick with "dl" parameter allows us to count number of downloads (we store that into database when dl is present in the URL).
?>

Now, what does provide_file.php do?

First, we have to somehow get the filename:
$query1 = "select filename from files where file_id = ".intval($_REQUEST['
file']);
(call mysql_query($query1) to make this query. If it fails or finds zero entries, abort execution (die(1);) )

If a record is found (and eventually the user is authenticated using the relid string), the following sequence will prompt the user to download the file:
<?php
$res = mysql_fetch_row($q); // Get the record from DB.
$tmp1 = $res[0]; // the following sequence extracts the filename from the complete path stored in filename column:
   while (strpos($tmp1,"/")!==false) // originally, $tmp1 is something like /files/filename.zip; while there are slashes, cut the first char:
   {
       $tmp1 = substr($tmp1,1); // cut the first char.
   }
   Header ("Content-type: application/x-zip-compressed"); // assuming the file is zip
   header('
Content-Disposition: attachment; filename="'.$tmp1.'"'); // This ensures prompt "What do you want to do with the file", with "Save to disk" preferred.
       $tmp = file_get_contents($res[0]); // read the contents of the file into a variable...
       echo $tmp; // ... and output it after the headers.

?>

If you have multiple options of file types, you need to store the type or extract it from the filename (substr($filename,-3) gives you the extension); this can also be used for images if you want to block hotlinking - just set: src="provide_image.php?..." which works similarly and has Content-Type: image/gif or image/png or image/jpg as content type; in the case of images, don'
t use Content-disposition header; just read the file and echo it.
zenobic at gmail dot com
26-Jun-2007 06:28
Javascript vars with php - To use serverside variables in a html document (unfortunately html files on IIS can not be simple associated with php) as client-side javascript, you can send a javascript header in a javascript-container that contains a php
script and generate the js vars.
markup: script src="serverdate.php"

serverdate.php:
<?php
error_reporting
(0);
header("content-type: application/x-javascript");

echo
'var year = "'.date("Y").'";'; // var year = 2007;

//echo 'alert(" y:"+parseInt(year))';
?>
greg dot jones at senokian dot com
21-Jun-2007 09:16
In case anyone else is having trouble:
using a web-server behind the pound load balancer, we found that trying to redirect to https://example.com for requests to http://example.com were getting into an infinite loop because pound, by default, 'fixes' changes of protocol for you. You want to set RewriteLocation to 0 to turn this behaviour off.
12gurus developer
15-Jun-2007 01:50
Even with no-caching tags, images displayed on the page may be cached.

You can prevent the cached image from displaying by appending a random number to the SRC in the IMG tag

for example:

<img src="image_name.jpg?<?=rand(100,999);?>" />

the "?" and everything following it make the browser re-request the image.
Tchouamou Eric H.
10-Jun-2007 12:11
This is a good function to send an image to the browser having the path.

function PE_img_by_path($PE_imgpath = "")
{
    if (file_exists($PE_imgpath)) {
        $PE_imgarray = pathinfo($PE_imgpath);

        $iconcontent = file_get_contents($PE_imgpath);
        header("Content-type: image/" . $PE_imgarray["extension"]);
        header('Content-length: ' . strlen($iconcontent));
        echo $iconcontent;
        die(0);
    }
    return false;
}
nobileelpirata at hotmail dot com
02-Jun-2007 03:04
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP
header
( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

?>
Jean-Pierre
27-May-2007 04:21
You can use the Header command to force a browser to use fresh content (no caching).

However, this only works for the HTML code your code generates. When you have updated images for example (with the same filename) then there's a chance that these are still cached.

The easiest way to solve this problem I found is changing:

<?
print "<img src='yourfile.jpg'>";
?>

into:

<?
print "<img src='yourfile.jpg?".time()."'>";
?>

This adds an unique number to the url and wont hurt at all.
ludovic.goix-arobas-"google mail"
17-May-2007 11:58
When not using "exit;" after the header("Location: ..."),  the execution of the script continue below the header, until the end is reached. After this, it's doing the "Redirect".

if($error)
{
   header("Location: http://url.com");
}

//the script continue with or without an error and execute some function that we do not want...
delete($file);

It could be important to put exit always after a Redirect.

if($error)
{
   header("Location: http://url.com");
   exit;
}

//the script continue only without error. It will execute what we want to do.
Michael Keyser
11-May-2007 12:12
I use this to stream and download media files:

<?php

if (isset($_GET['action']) && isset($_GET['file']) && file_exists(stripslashes($_GET['file']))) {

   
$file = stripslashes($_GET['file']);
   
$base = basename($file);

   
$extension = "";

   
$i = strlen($base);

    while (
substr($base, $i, 1) != ".") {
       
$extension = substr($base, $i--, 1) . $extension;
    }

    switch (
strtolower($extension)) {

        case
"wmv":
        case
"mpg":
        case
"mpeg":
        case
"avi":
        case
"mov":
            include
"../mysql_settings.php";
           
$con = mysql_connect($mysql_host, $mysql_user, $mysql_password) or die(mysql_error());
           
mysql_select_db($mysql_database) or die(mysql_error());

            switch (
$_GET['action']) {

                case
"download":
                   
$query = "INSERT INTO downloads (file,ip_address) VALUES ('". addslashes($file) ."','". $_SERVER['REMOTE_ADDR'] ."')";
                   
mysql_query($query) or die(mysql_error());
                   
mysql_close($con);

                   
$message = "Hello Michael,<br><br>\n&quot;<b>". $file ."</b>&quot; has been downloaded from your website at ". date("g:i:s A - M j, Y") .".<br><br>\nIP Address: <b>". $_SERVER['REMOTE_ADDR'] ."</b>";

                   
email($file ." has been downloaded from your website!", $message);

                   
// tell the browser how big the file is so the user has a percentage complete progress bar
                   
header("Content-Type: ". $extension);
                   
header("Content-Length: ". filesize($file));
                   
header("Content-Disposition: attachment; filename=\"". str_replace(" ", "%20", $base) ."\"");

                   
readfile($file);
                    break;

                case
"stream":
                   
$query = "INSERT INTO stream (file,ip_address) VALUES ('". addslashes($file) ."','". $_SERVER['REMOTE_ADDR'] ."')";
                   
mysql_query($query) or die(mysql_error());
                   
mysql_close($con);

                   
$message = "Hello Michael,<br><br>\n&quot;<b>". $file ."</b>&quot; is or has been streamed from your website at ". date("g:i:s A - M j, Y") .".<br><br>\nIP Address: <b>". $_SERVER['REMOTE_ADDR'] ."</b>";

                   
email($file ." is or has been streamed from your website!", $message);

                   
header("location: ". str_replace(" ", "%20", $base));
                    break;

                default:
                   
// action is invalid
                   
break;

            }

            break;

        default:
           
// invalid file extension
           
break;

    }

}

?>
dracolytch at yahoo dot com
10-May-2007 09:00
You may find that you want to process a PHP file, and have the browser treat the output as an XML file. Unfortunately, most browsers will only do this if the file extension is ".xml"

In those situations where you can't/don't want to change your apache config to put XML files through the PHP processor, you can use the header function to change the output to something the browser will recognise as XML:

header('Content-Type: text/xml');
header('Content-Disposition: inline; filename=sample.xml');

(The inline portion helps ensure the browser renders the page itself, instead of prompting the user to download the page)

~D
greg d0t pwpp 4t gmail d0t com
02-May-2007 01:53
More on downloading files...

Here's a slight improvement to the method provided by Nick Sterling.

I tried this and it works great, but using fopen ran into memory limit problems.

By using readfile($filename), I solved this problem without having to change the ini settings.

readfile() reads a file and writes it to the output buffer.

Here's my version of the code:

<?php
$filename
= "theDownloadedFileIsCalledThis.mp3";
$myFile = "/absolute/path/to/my/file.mp3";

$mm_type="application/octet-stream";

header("Cache-Control: public, must-revalidate");
header("Pragma: hack"); // WTF? oh well, it works...
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($myFile)) );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary\n");

readfile($myFile);

?>
robert [at] everah [dot] com
01-May-2007 04:24
A brief amendment to the comment by Brandon K [ brandonkirsch uses gmail ]...

The issue with IE downloading dynamic files produced on an SSL encrypted connection with the no-cache Cache Control settings affects most types of files, including .csv, .txt and all Office document types in addition to .pdf files.

This problem affects IE7 as well as IE6 and IE5.5. I haven't found a user using anything earlier so I cannot confirm if it is happening in earlier IE browsers, though I suspect it is. As far as my users have reported, this is not an issue in FF, Opera or Safari.

There is more information on this issue at http://support.microsoft.com/kb/812935 in addition to the many other MSDN reports on this same issue.
Brandon K [ brandonkirsch uses gmail ]
25-Apr-2007 12:34
I just lost six hours of my life trying to use the following method to send a PDF file via PHP to Internet Explorer 6:

<?php
header
('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');
readfile('original.pdf');
?>

When using SSL, Internet Explorer will prompt with the Open / Save dialog, but then says "The file is currently unavailable or cannot be found.  Please try again later."  After much searching I became aware of the following MSKB Article titled "Internet Explorer file downloads over SSL do not work with the cache control headers" (KBID: 323308)

PHP.INI by default uses a setting: session.cache_limiter = nocache which modifies Content-Cache and Pragma headers to include "nocache" options.  You can eliminate the IE error by changing "nocache" to "public" or "private" in PHP.INI -- This will change the Content-Cache header as well as completely remove the Pragma header.  If you cannot or do not want to modify PHP.INI for a site-wide fix, you can send the following two headers to overwrite defaults:

<?php
header
('Cache-Control: maxage=3600'); //Adjust maxage appropriately
header('Pragma: public');
?>

You will still need to set the content headers as listed above for this to work.  Please note this problem ONLY effects Internet Explorer, while Firefox does not exhibit this flawed behavior.
asaucier777 at mac dot com
21-Apr-2007 08:25
Refreshing/redirecting a/to a Page Using the "header" command in PHP.

I found the following code to help me refresh a page or really redirecting to a page after a certain number of secionds.  (I'm using php 5.x)

<?php
print(" <p align=\"center\"> User Not Found</p><br><br>");   // err msg  
 
header('Refresh: 3; url=index.html'); // waits 3 seconds & sends to homepage
?>

Explaination:
1. I used php to set up a simple html message as to what is happening
2. with header, there is a command, "Refresh" and here is how it works:
    a. 'Refresh: 3;  -- start all header commands with a single quote
    b.  Refresh requires a parameter that is in seconds which tells the browser
         to refresh after this time period has passed.
    c.  The ; is necessary to separate it from the rest of the Refresh parameters
    d.   Refresh must be uppercased - I think
3. After the ; put the url= command and put in your desired web page
4. Location doesn't work! with in this context.
5. Order matters.  Refresh first, then it's second parameter, url=

--Allen
neil at 11 out of 10
20-Mar-2007 05:52
Response to hervard at gmail dot com (18-Apr-2006 06:53)

The code you gave for preventing the message appearing with the back button did not work for IE7, but changing the line:

$offset = 60 * 60 * 24 * -1;
to
$offset = 60 * 60 * 24 * 1;

makes it work OK, with my set up there's no issues with serving cached versions of the page.
 
<?php

 
// Original code found at http://www.mnot.net/cache_docs/
  // thanks to hervard at gmail dot com for this solution to browser back button problems

  
header("Cache-Control: must-revalidate");
  
$offset = 60 * 60 * 24 * 1;
  
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
  
header($ExpStr);

?>

I've tested this in a standalone version of IE6
Also tested in IE7, Firefox 1.5, Opera 7.54
KKOOPORATION at gmail dot com
18-Mar-2007 11:07
This is an Example of an UID based download Platform:

document 1:
<?php
if($_GET['verify']==broken){
die(
'Please do not leech.');
}
if(
$_GET['accepted']==1){
//Generate a password:
$password ="";
$pool .= "123456789";
srand ((double)microtime()*1000000);
for(
$index = 0; $index < 200; $index++)
{
 
$password .= substr($pool,(rand()%(strlen ($pool))), 1);
}
//use on a windows server:
passthru('echo '.$passwort.' >> verify.pajaxtxt');
//Use on a linux server:
//$fneu = fopen("verify.pajaxtxt","w+");
//fputs ($fneu,$password);
//fclose ($fneu);
header('location: document2.php?UID='.$password);
}
else
{
echo
'<a href="?accepted=1">I accept (Insert what do you think)</a>';
}
?>

document2:
<?php
//Check if $get exist:
if($_GET){
//Parameter for UID:
$s = $_GET['UID'];
//file definition:
$sa = file("verify.pajaxtxt");
for(
$i=0; $i<count($sa); $i++)
{
if (
ereg($s, $sa[$i]))
{
//if verification code exist in the file:
echo "Finished!";
//end.
//
}
}
}
else
{
//Go back if the verification code does not exist in the file
header('location: document1.php?verify=broken');
//end.
}
?>

The file verify.pajaxtxt must deleted every day!
ianar
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571