Header location ошибка

(1)I’m in the process of uploading my website to a remote web server.

(2)The site’s template system is set up in a way that all of the pages are formed by sending url-encoded get requests to index.php

(3)Loading up the initial page works. This page determines the location of the next page by evaluating the value of its form.

(4)The redirection to the next page is performed by doing a: header('location: next_page')

(5)For some reason, the redirection is not performed. Here’s what the code looks like:

$error = "";
if(isset($_POST['index_choice'])){
    $path_choice = isset($_POST['path']) ? $_POST['path'] : NULL;

    //echo $path_choice;
    //echo $page_inc;

    //nothing after this

    if($path_choice != null){

        if($form->is_connected()){

            //if($path_choice != "" || $path_choice != NULL){
                if($path_choice == "new"){

                    //header('location: /login.php');
                    //header('location: page/login');
                    header('location: /index.php?page=login');
                    exit();

                }
                else{

                    //header('location: /amend.php');
                    //header('location: page/amend');
                    header('location: /index.php?page=amend');
                    exit();
                }
            //}
            /**
            else{
                //destroy_session();
                $error = "You haven't selected a path. Please choose a path";
            }
             *
             */
        }
        else{
            //destroy_session();
            $error = "Problems with connecting to the database";
        }
    }else{
        //destroy_session();
        $error = "You have not indicated your choice";
    }

}

SOLVED

It was a matter of having a blank space after a ?> somewhere else in the code. This was revealed to me after placing the following commands at the top of the code:

 error_reporting(E_ALL); ini_set('display_errors', 'On'); 

I’d like to say thanks to all of the people that have tried to help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
include "../../php/config.php";
$id = $_GET['id'];
 
 
if (isset($_POST['order'])) {
    if(isset($_FILES['filename']) && $_FILES['filename']['error'] == 0){
        // Директория для закачивания
        $dir = '/img/klientphoto/'; 
        // Допустимые MIME-типы
        $arrType = array('image/jpeg','image/gif','image/png',);
        // Допустимые расширения
        $arrExt = array('png', 'jpg', 'jpeg', 'gif');
        // Получаем расширение файла
        $ext = pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION);
        // 1. Проверка MIME-тип файла и расширение
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $type = $finfo->file($_FILES['filename']['tmp_name']);
        if (in_array($type, $arrType) && in_array($ext, $arrExt)){
            // 2. Генерирование уникального имени и пути файла
            $filepath = $dir.uniqid().'.'.$ext;
            if(move_uploaded_file($_FILES['filename']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].$filepath)){
                // Если файл загружен, то можем вывести его на экран
            } else {
                echo 'Хьюстон! У нас проблемы!';
            }
        }
    }
 
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $region = $_POST['region'];
    $city = $_POST['city'];
    $street = $_POST['street'];
    $home = $_POST['home'];
 
    $adres = "$region  $city  $street  $home";
    $orderNumber = $_POST['orderNumber'];
    $product = $_POST['product'];
    $idproduct = $_POST['idproduct'];
    $paymethod = $_POST['paymethod'];
    $price = $_POST['price'];
    $itogo = $_POST['itogo'];
    
    $today = date("d.m.y H:m:s");  
 
    $result = mysql_query ("INSERT INTO LS_Client (Name, Phone, E_mail, Adres, Product, Price, Itogo, PayMethod, NamePhoto, IdProduct, DataTime, OrderNumber) VALUES ('$name', '$phone', '$email', '$adres', '$product', '$price', '$itogo', '$paymethod', '$filepath', '$idproduct', '$today', '$orderNumber')") or die (mysql_error());
 
    header("Location: http://orenmorozko.ru/page/pay/paynow.php?orderNumber=$orderNumber"); // вот собственно сам header.  $orderNumber генерируется случайно, при заходе на страницу и вставляется в инпут скрытый
}
 
 
$ordn = round(microtime(true) * 1000);
$sql = mysql_query("SELECT * FROM `LS_Catalog` WHERE Id=$id") or die(mysql_error());
    $newsData = array();
    while($result = mysql_fetch_array($sql, MYSQL_ASSOC)){
        $newsData[] = $result;
    }           
    foreach($newsData as $pr): 
?>
<?$title = $pr['Title'];?>
<?$size = $pr['Size'];?>
<?$img = $pr['Img'];?>
<?$regprice = $pr['RegularPrice'];?>
<?$oldprice = $pr['OldPrice'];?>
 
<?$saleonof = $pr['Sale'];?>
 
<? $itg = ($regprice - $regprice*(10)*0.01);?>
 
<?php endforeach; ?>
 
 
 
<?php           
    $sql = mysql_query("
        SELECT * FROM `LS_Settings` LIMIT 1
    ") or die(mysql_error());
    $newsData = array();
    while($result = mysql_fetch_array($sql, MYSQL_ASSOC)){
        $newsData[] = $result;
    }           
    foreach($newsData as $settings): 
?>
<?=$settings['YandexWebMaster'];?>
<?=$settings['YandexMetrika'];?>
<?$domen = $settings['Domen'];?>
<?$phone = $settings['Phone'];?>
<?php endforeach; ?>

За последние 24 часа нас посетили 10056 программистов и 948 роботов. Сейчас ищут 674 программиста …


  1. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    Здравствуйте! Не срабатывает

    1. header (‘Location: /index.php’);

    (этот файл чистый и содержит в себе только редирект)

    header (‘Location: index.php’);
    header (‘Location: /’);
    header (‘Location: ‘.APP_DIR);
    header (‘Location: http://site.name/index.php’);
    все эти вариации так же не работают

    В случае отключения ЧПУ (комментирую в .htaccess строки, касающиеся ЧПУ), то header отрабатывает (при прямом заходе на файл соответственно).
    в скриптах пустых строк нет, тег <?php не закрываю. Никакого вывода до отправки заголовка не происходит. кодировка файлов UTF8 без BOM

    код главной страницы

    1. header(«Content-Type: text/html; charset=UTF-8»);
    2. $pageName = substr($_SERVER[‘REQUEST_URI’], 1);
    3. $simbolNum = strpos($pageName, ‘?’);
    4. /*если в запросе есть get значение, то срезаем его*/
    5.     $pageName = substr($pageName, 0, $simbolNum);
    6. /*если обратились к главной*/
    7. if ($pageName == ‘index’ || $pageName == »){
    8. /*если юзверь авторизован, то отдаем ему страницу с его данными, иначе просим авторизоваться или зарегаться*/
    9.         include(APP_DIR.‘/pages/index_authorized.php’);
    10.         include(APP_DIR.‘/pages/index_not_authorized.php’);
    11.     /*иначе лезем за нужной страницей*/
    12.     $url = APP_DIR.‘/pages/’.$pageName.‘.php’;
    13.         include (APP_DIR.‘/pages/404.php’);

    вывод который мог бы быть до «include ($url)» на всякий случай закоментировала и все одно. ошибки нет. Но тем не менее редирект работать принципиально не хочет. Где еще что посмотреть?

    PHP, JavaScript, SQL и другой код пишите внутри тегов

    Код ( (Unknown Language)):
    1. [b]php][/b]Тут код[b][/[/b][b]code][/b][/color]


  2. mahmuzar

    Re: Не работает header(‘Location: …)

    создай чистый скрипт пропиши строки редиректа там, запусти его. Смотри сработает редирект или нет, если сработает то с редиректом все норм, проблема в коде.


  3. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    1. RewriteCond %{REQUEST_FILENAME} !-d
    2. RewriteCond %{REQUEST_FILENAME} !-f
    3. RewriteRule ^(.*)$ index.php [QSA,L] 

    мой .htaccess

    1. #RewriteCond %{REQUEST_FILENAME} !-d
    2. #RewriteCond %{REQUEST_FILENAME} !-f
    3. #RewriteRule ^(.*)$ index.php [QSA,L] 

    А вот так работает

    Добавлено спустя 47 секунд:

    файл который я показала уже так и создан для теста именно редиректа. не отрабатывает при включенном ЧПУ


  4. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Re: Не работает header(‘Location: …)Так отдавайте ЧПУ-ссылку в заголовок, раз так)


  5. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    Так я чпу и отдаю. При запросе корня сайта он отдать должен файл (пока нет авторизации, то со ссылками на вход и регистрацию) а он никуда не переходит. Вообще. И адрес как был, так и остается.
    а.. я там написала index.php… это остался код после теста без чпу. а так я отдавала просто index без .php

    Добавлено спустя 8 минут 7 секунд:

    вот такой вариант (это 100% ЧПУ ссылка) тоже не работает


  6. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Re: Не работает header(‘Location: …)

    Полностью адрес указать попробуйте, начиная с протокола.


  7. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    указывала

    1. header (‘Location: http://site.ru/reg’); 

    то же самое. сейчас выяснила, что при прямом заходе на тестовый файл по пути /pages/1.php редирект отрабатывает, а когда он инклюдом в индекс подключается — нет.


  8. romach

    С нами с:
    26 окт 2013
    Сообщения:
    2.904
    Симпатии:
    719

    Re: Не работает header(‘Location: …)

    А ошибок точно ни где не выводится? В браузер какие заголовки приходят?


  9. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    а ошибки почему то не выводились, хотя error_reporting(E_ALL) стояло.. но сейчас уже выяснила при помощи

    , что как оказалось один из подключаемых файлов файлов почему-то что-то выводил.. точнее в нем было то всего ничего

    1. /*подключаем волшебные файлы с функциями*/
    2. include(APP_DIR.‘/models/users.php’);

    поменяла на

    1. /*подключаем волшебные файлы с функциями*/
    2. include ‘/models/users.php’;

    и заработало. только почему при первом варианте записи такое происходило — непонятно. может кто-нибудь пояснить? файл-то подключался.. функции из него благополучно отрабатывали…

    Добавлено спустя 18 минут 15 секунд:
    ох.. все, всем спасибо. проблему нашла.. надо же пять раз у всех файлов кодировку проверила. но у одного файла почему-то не заметила что кодировка стоит utf8, а не utf8 без BOM …. сейчас когда методом исключений добралась до этого файла только сейчас уже увидела..


  10. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    BOM он такой, зараза… подкрадывается незаметно. Используйте для разработки IDE, а не блокнотики. И не будет такой беды.


  11. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    Эммм.. я кажется еще не доросла)) Надо еще все прочувствовать в hotepad++, что бы захотелось больше с этим не сталкиваться))))
    за то теперь узнала о таких хороших функциях, как


  12. romach

    С нами с:
    26 окт 2013
    Сообщения:
    2.904
    Симпатии:
    719

    Тут главное не застрять на одном месте. Ты ведь с самого начала знала в чем косяк, значит это уже пройденный этап, пора двигаться дальше )


  13. Fell-x27

    Команда форума
    Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.162
    Симпатии:
    1.770
    Адрес:
    :сердА

    Не надо. Поставь себе phpStorm и радуйся жизни. Бояться тут нечего.


  14. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.520
    Симпатии:
    1.743

    Не знаю, может мне везло, но в своих скриптах у меня ни разу Header already sent не возникала из-за BOM… Даже когда я был зелёным в веб-программировании совсем


  15. Evfemizm

    С нами с:
    5 июн 2015
    Сообщения:
    7
    Симпатии:
    0

    ахах… у меня он тоже не возникал… оказалось отображение ошибок отключено на уровне сервера))) сейчас включила (в .htaccess) и обнаружила еще пару варнингов, которые не видела.

    Добавлено спустя 1 минуту 34 секунды:

    php storm… я одно время пыталась его использовать.. но почему-то мне с ним неуютно как-то…

    Добавлено спустя 2 минуты 17 секунд:

    вот и двигаюсь.. сейчас овладеваю MVC и шаблонизация (открыла для себя классную штуку — буферизацию. открыла до всех инклюдов, закрыла после и все заголовки подружились). волшебство… потом ооп))))))))


  16. walerock

    С нами с:
    17 май 2016
    Сообщения:
    1
    Симпатии:
    0

    Спасибо вам большое!!! тоже открыл для себя буферизацию))

Добрый день!
Есть промежуточная страница, для учета переходов по ранее сгенерированной ссылке, при переходе по которой выставляется флаг о переходе. Так вот между запросами и переходами есть разница (из 50 запросов с переходами примерно ссылок 7 ссылок не помечаются «переходом»).
В логах сервера, базы данных ошибок нет. При запросе и при переходе в самом начале пишутся логи. Запрос ссылки происходит через CURL. Ссылка получена, делаю:

header('Location: '.$url);
die();

На стороне клиента такие ссылки все пишутся в логи. На стороне сервера она даже не попадает в лог начала вызова метода, где должна помечаться «переходом». Не могу понять из-за чего. Нигде никаких ошибок, связанных с этим нет (я про логи).
Какие могут быть предположения?


  • Вопрос задан

    более трёх лет назад

  • 1855 просмотров

Пригласить эксперта

Если до вывода хедера был какой-то вывод данных, хедер не отработает. Убедитесь что до выставления хедера не было echo, print_r, var_dump и прочих функций вывода. Если файл подключается, проверьте также в родительском файле. Также проверьте что файл не сохранён с использованием BOM. Если выставлен
error_reporting(E_ALL), то может валится какой-то notice, который тоже является выводом

Работать не будет

<html><body>
<?php
header('Location: '.$url);
die();

Работать не будет

<?php
echo "123";
header('Location: '.$url);
die();

Работать не будет

{ПРОБЕЛ, ТАБУЛЯЦИЯ ИЛИ ДРУГОЙ СИМВОЛ}<?php
header('Location: '.$url);
die();


  • Показать ещё
    Загружается…

04 июн. 2023, в 01:35

1500 руб./за проект

04 июн. 2023, в 01:25

40000 руб./за проект

03 июн. 2023, в 23:42

1500 руб./за проект

Минуточку внимания

PHP

So sometimes when using the PHP header function to cause a redirect to another page, you will get the error:


Warning: Cannot Modify Header Information- Headers Already Sent by (output started at /home/content/84/…/searchpage.php:1)

This can happen such as with using the following code:

<?php

header(‘Location: http://www.google.com’);

?>

This error occurs for pretty much one reason only but how it can exist can take many forms. We’ll explain now.

The reason this error occurs is because output is written to the browser before the redirect to another page occurs.
With the PHP header function, this is forbidden. No output can be written to the browser before the redirect occurs. If this is
the case, you will get the error, such as shown above.

So how does output can written to the browser?

And the answer is, this can take many forms.

For one, you may actually have output shown before the php header function, such as an echo statement.

The code below will run an error:

<?php
echo «This output causes the header function to not work»;
header(‘Location: http://www.google.com’);

?>

The above is a more obvious blatant example.

However if you have an HTML tag located before the code, it will also cause this error to occcur. This html tag
may be <html> or <header>.

The code below will cause an error:

<?php
<html>
header(‘Location: http://www.google.com’);

?>

So you can’t have any statements printed by PHP. You can’t have any HTML tags present before the header function.

You also can’t even have white space present before the PHP header tag. This, too, will cause an error.

The following code below will cause an error:

       <?php

header(‘Location: http://www.google.com’);

?>

Only the following code, below, no white space, html tags, or statements printed to output will cause no errors.

<?php

header(‘Location: http://www.google.com’);

?>

But what if you’ve run the code with absolute no white space, html tags, printed statements. The php code is right
at the top with only the header function, and yet the same error is still occurring. Then what may be causing it? Yes, even with
absolutely no space visible to us, this error can still occur.

And if you have no whitespace or anything else and still getting the error, it’s more than likely due to how the
PHP file is saved. If you use a text editor like notepad, you can save PHP file in many different encoding formats. You can
save the PHP file in either ANSI encoding, Unicode encoding, Unicode big endian encoding, or UTF-8 encoding. The format you choose
can trigger this error. The best encoding to save it at is the ANSI encoding.

ANSI encoding

This encoding adds no hidden whitespace or characters
to the PHP file. If you use unicode, unicode big endian, or UTF-8 encoding, these encodings can actually add characters to the text
in the PHP file. This is why this error can occur even when you see absolutely no whitespace at all. Some encodings can add
things to the file you can’t even see. The best format to save the file is in ANSI. It’s the purest form that doesn’t add
characters to the PHP file, so what you actually can see in the text is the same behind the scenes of the binary code. The other
encodings can add. So whatever you have for the PHP, copy it, and paste it to notepad. Save it with a .php extension and in
ANSI encoding. Then upload this file to web and this may correct the error.

So there are many reasons why this error may occur again, but these solutions should fix that problem.

To see a classic example of a program that uses the header function that uses location for a redirect,
see How to Create a Search
Engine Using PHP. We create a search engine using the php function as the basis of the search engine. This function causes
redirects to various websites based on the search query that a user enters.

Такой код (скрипт, обрабатывающий данные формы для отсылки их на мыло):

проверяем, данные пришли именно из нашей формы?
если ДА, то include(«file2.php»)
иначе header(«Location: на главную страницу сайта»);

—————file2.php——————
проверяем поля формы не были пустыми?
если НЕТ, то
чистим данные от спецсимволов, формируем тело письма
include(«file3.php»)
header(«Location: на страницу формы, где сообщается, что письмо отправлено»);

иначе header(«Location: на страницу формы для повторного ввода данных»);

—————file3.php——————
include(«class.phpmailer.php»)
отправляем письмо

НО, header, выделенный красным, никуда не отправляет. Я уже куда только его не переставлял. Заменял его на meta-тег с атрибутом refresh, так прикол в том, что какой адрес для этого meta ни укажи, он всё равно перенаправляет браузер на главную страницу сайта.

На локальном сервере (под управлением Винды) всё работает, на удалённом сервере под управлением АльтЛинукс (php 4.3.11) красный header упирается по полной.

Может, кто в силах объяснить эту мистику? Может, проблема в большой вложенности скриптов (много include)? Как быть?

Wondering how to fix PHP header not redirecting issue? We can help you.

This redirection error occurs due to some incorrect output buffering settings and wrong header formats.

At Bobcares, we often receive requests to fix redirection errors in PHP as part of our Server Management Services.

Today, let’s discuss this error in detail and see how our s Support Engineers fix it effectively.

Steps to fix PHP header not redirecting

Before going into the steps for fiing this issue let’s see some uses of PHP header?

The header() function in PHP sends a raw HTTP header. This raw data contains the request made by the server as information.

And, we call header() before any actual output is sent. It gives a clear idea about the object sent in the message body.

Also, the Location: parameter of the header returns a redirect status code to the browser.

Usually, we can redirect it either to a URL or some file.

In PHP, redirection to a URL will be of the following format:

< ?php header("Location: http://www.redirect.to.url.com/"); ?>

Similarly, to redirect to a file, we use the following command:

Often this redirection results in some tricky errors, we will see how our Support Engineers fix them.

Fixing PHP header not redirecting

PHP redirections are usually set when we get failed sessions. We can check this with the code given below:

if(
!isset($_SESSION['SESS_MEMBER_ID'])
|| (trim($_SESSION['SESS_MEMBER_ID']) == '')
AND !isset($fb_login)
) {
header("location:login.php?msg=Please+Login+Again.");
}

For failed session logins, we will try redirection to another page and this is when we notice that redirection has failed and a black page showed up.

This generally happens due to an error with output buffering.

If we use header(“Location: “);, then it is necessary to use ob_start(); earlier in the script.

ob_start() function will turn the output buffering ON. While output buffering is active no output is sent from the script other than headers until we call ob_end();

Calling header(“Location: “); after content has already been output to the browser can cause problems.

So, we ensure that no output is sent before calling the header.

Setting ob_start() at the beginning of the PHP file heps to resolve the error.

Similarly, errors in the header format can also cause redirection failures.

It is important to make the “Location” start with uppercase. Also, the header contents must be inside double-quotes.

[Still facing PHP redirection errors?- We’ll help you.]

Conclusion

In short, the PHP header not redirecting error occurs mainly due to the absence of ob_start() function, incorrect header formats, and so on. Today we discussed this error in detail and saw how our Support Engineers fix this for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

mjt at jpeto dot net

13 years ago


I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.


Marcel G

13 years ago


Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php

  header
( "refresh:5;url=wherever.php" );

  echo
'You'll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';

?>



Hth someone


Dylan at WeDefy dot com

15 years ago


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.


mandor at mandor dot net

17 years ago


When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php// Test image.
   
$fn = '/test/foo.png';// Getting headers sent by the client.
   
$headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current.
   
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
       
// Client's cache IS current, so we just respond '304 Not Modified'.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
       
// Image not cached or cache outdated, we respond '200 OK' and output the image.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
       
header('Content-Length: '.filesize($fn));
       
header('Content-Type: image/png');
        print
file_get_contents($fn);
    }
?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)


php at ober-mail dot de

3 years ago


Since PHP 5.4, the function `http_​response_​code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).

bebertjean at yahoo dot fr

14 years ago


If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header
("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header
("Content-Disposition: attachment; filename="" . basename($filename) . """);
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)


tim at sharpwebdevelopment dot com

5 years ago


The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.

yjf_victor

7 years ago


According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
                          filename*= UTF-8''%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
                          filename="EURO rates";
                          filename*=utf-8''%e2%82%ac%20rates

As a result, we should use

<?php
$filename
= '中文文件名.exe';   // a filename in Chinese characters$contentDispositionField = 'Content-Disposition: attachment; '
   
. sprintf('filename="%s"; ', rawurlencode($filename))
    .
sprintf("filename*=utf-8''%s", rawurlencode($filename));header('Content-Type: application/octet-stream');header($contentDispositionField);readfile('file_to_download.exe');
?>

I have tested the code in IE6-10, firefox and Chrome.


David Spector

1 year ago


Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is "header('Content-type: text/javascript');".


sk89q

14 years ago


You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php

$last_modified_time
= filemtime($file);

$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");

header("Etag: $etag");

if (@

strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||

   
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {

   
header("HTTP/1.1 304 Not Modified");

    exit;

}

?>


nospam at nospam dot com

7 years ago


<?php// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

?>

ben at indietorrent dot org

11 years ago


Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Cache-control:no-store
Cache-control:no-cache

See: http://support.microsoft.com/kb/323308

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:

BrowserMatch ".*MSIE.*" gzip-only-text/html


David

5 years ago


It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»


chris at ocproducts dot com

6 years ago


Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:

session_cache_limiter('');

...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.


shutout2730 at yahoo dot com

14 years ago


It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header
("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header
("location: 1.html");
echo
"send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start
();
header("location: 1.html");
echo
"send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>


jp at webgraphe dot com

19 years ago


A call to session_write_close() before the statement

<?php

    header
("Location: URL");

    exit();

?>



is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.


dev at omikrosys dot com

13 years ago


Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');


Angelica Perduta

3 years ago


I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:

    header_remove();
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // ... and then try redirecting
    // 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
    // 302 "moved temporarily" does seems to load it!
    header("location:$dst", FALSE, 302); // redirect to the file now we have it


mzheng[no-spam-thx] at ariba dot com

14 years ago


For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header
("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.$fp = fopen($file, "r");
while (!
feof($fp))
{
    echo
fread($fp, 65536);
   
flush(); // this is essential for large downloads

fclose($fp);
?>


razvan_bc at yahoo dot com

5 years ago


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

this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

header

('Location: http://www.example.com/');
die();
?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!

there are many situations  with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!


scott at lucentminds dot com

13 years ago


If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so...

<?php

    header

( 'Content-Type:' );?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close


Vinay Kotekar

8 years ago


Saving php file in ANSI  no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>

Would give something like this :-

Warning: Cannot modify header information - headers already sent by (output started at C:wwwinfo.php:1) in C:wwwinfo.php on line 1


Cody G.

12 years ago


After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Content-type: text/javascript");
 
header("Content-Disposition: inline; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
} else {
 
header("Content-type: application/force-download");
 
header("Content-Disposition: attachment; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(
strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Cache-Control: no-cache");
 
header("Pragma: no-cache");
}
include(
"my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.


Refugnic

13 years ago


My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.


Anonymous

13 years ago


I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location

Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header("Content-Type: text/plain");

wrong: header("Content-Type:text/plain");

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

good: header("Location: http://www.example.com/something.php?a=1");

4. Relative URIs are NOT allowed

wrong:  Location: /something.php?a=1

wrong:  Location: ?a=1

It will make proxy server and http clients happier.


bMindful at fleetingiamge dot org

20 years ago


If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)

     header("HTTP/1.0 204 No Response");


nobileelpirata at hotmail dot com

16 years ago


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: Sat, 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' );
?>


jamie

14 years ago


The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)


er dot ellison dot nyc at gmail dot com

7 years ago


DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !

// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !


ASchmidt at Anamera dot net

5 years ago


Setting the "Location: " header has another undocumented side-effect!

It will also disregard any expressly set "Content-Type: " and forces:

"Content-Type: text/html; charset=UTF-8"

The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!


hamza dot eljaouhari dot etudes at gmail dot com

4 years ago


// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error

//This line causes the error
        7
header('Location : index.php&controller=produit&action=index');

// While It must be written without the space
header('Location: index.php&controller=produit&action=index');


cedric at gn dot apc dot org

12 years ago


Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.

Понравилась статья? Поделить с друзьями:
  • He go to school every day найти ошибку
  • He drives carefully his car исправить ошибки
  • He are sleeping now исправить ошибки
  • Hdtsmp64 dll skyrim ae ошибка
  • Hdslvc2 oculus quest 2 ошибка