Php output before header

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

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.


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

Parameters

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.

// This example illustrates the «HTTP/» special case
// Better alternatives in typical use cases include:
// 1. header($_SERVER[«SERVER_PROTOCOL»] . » 404 Not Found»);
// (to override http status messages for clients that are still using HTTP/1.0)
// 2. http_response_code(404); (to use the default message)
header ( «HTTP/1.1 404 Not Found» );
?>

Читайте также:  Http sdo mosritual ru 25555 login index php

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 the 201 or a 3xx status code has already been set.

header ( «Location: http://www.example.com/» ); /* Redirect browser */

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

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:

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

Return Values

Errors/Exceptions

On failure to schedule the header to be sent, header() issues an E_WARNING level error.

Examples

Example #1 Download dialog

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.

// 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’ );
?>

Example #2 Caching directives

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:

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

Note:

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.

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

Note:

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.

Note:

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.

Note:

Most contemporary clients accept relative URI s as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER[‘HTTP_HOST’] , $_SERVER[‘PHP_SELF’] and dirname() to make an absolute URI from a relative one yourself:

/* 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;
?>

Note:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

See Also

  • headers_sent() — Checks if or where headers have been sent
  • setcookie() — Send a cookie
  • http_response_code() — Get or Set the HTTP response code
  • header_remove() — Remove previously set headers
  • headers_list() — Returns a list of response headers sent (or ready to send)
  • The section on HTTP authentication
  • Network Functions
    • checkdnsrr
    • closelog
    • dns_​check_​record
    • dns_​get_​mx
    • dns_​get_​record
    • fsockopen
    • gethostbyaddr
    • gethostbyname
    • gethostbynamel
    • gethostname
    • getmxrr
    • getprotobyname
    • getprotobynumber
    • getservbyname
    • getservbyport
    • header_​register_​callback
    • header_​remove
    • header
    • headers_​list
    • headers_​sent
    • http_​response_​code
    • inet_​ntop
    • inet_​pton
    • ip2long
    • long2ip
    • net_​get_​interfaces
    • openlog
    • pfsockopen
    • setcookie
    • setrawcookie
    • socket_​get_​status
    • socket_​set_​blocking
    • socket_​set_​timeout
    • syslog

    Источник

    «Конец ошибки script вывода перед заголовками» в Apache

    Apache в Windows дает мне следующую ошибку при попытке получить доступ к моему Perl script:

    Server error! The server encountered an internal error and was unable to complete your request. Error message: End of script output before headers: sample.pl If you think this is a server error, please contact the webmaster. Error 500 localhost Apache/2.4.4 (Win32) OpenSSL/1.0.1e PHP/5.5.3 
    #!"C:\xampp\perl\bin\perl.exe" print "Hello World"; 

    но не работает в браузере

    ОТВЕТЫ

    Ответ 1

    Если это CGI script для Интернета, вы должны вывести свой заголовок:

    #!"C:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n"; print "Hello World"; 

    Следующее сообщение об ошибке сообщает об этом End of script output before headers: sample.pl

    Или даже лучше, используйте CGI для вывода заголовка:

    #!"C:\xampp\perl\bin\perl.exe" use strict; use warnings; use CGI; print CGI::header(); print "Hello World"; 

    Ответ 2

    Проверить права доступа к файлам.

    У меня была точно такая же ошибка на машине Linux с неправильным набором разрешений.

    Ответ 3

    Обычно это ошибка, возникающая, когда вы не можете просмотреть или выполнить файл, причиной которого является, как правило, ошибка разрешений. Я бы начал с предложения @Renning и выполнил chmod 755 test.cgi (очевидно, замените test.cgi на имя вашего cgi script здесь).

    Если это не работает, вы можете попробовать еще пару вещей. Я однажды получил эту ошибку, когда создал test.cgi как root в другом доме пользователя. Исправлено было выполнение chmod user:user test.cgi , где пользователь — это имя пользователя, в котором вы находитесь.

    Последнее, что я могу придумать, это убедиться, что ваш cgi script возвращает правильные заголовки. В моем ruby ​​script я сделал это, положив puts «Content-type: text/html» , прежде чем я на самом деле вывел что-либо на страницу.

    Ответ 4

    Вероятно, это блок SELinux. Попробуйте следующее:

    # setsebool -P httpd_enable_cgi 1 # chcon -R -t httpd_sys_script_exec_t cgi-bin/your_script.cgi 

    Ответ 5

    Была та же ошибка на малине-пи. Я исправил его, добавив -w в shebang

    Ответ 6

    Итак, для всех, начиная с XAMPP cgi

    изменить расширение от pl до cgi
    измените разрешения на 755

    mv test.pl test.cgi chmod 755 test.cgi 

    Ответ 7

    Если вы используете Suexec, убедитесь, что script и его каталог принадлежат тому же пользователю, который вы указали в suexec.

    Кроме того, убедитесь, что пользователь, на котором запущен cgi script, имеет разрешения, выполняет разрешения на файл и программу, указанную в shebang.

    Например, если мой cgi script начинается с

    Тогда пользователю нужны разрешения для выполнения/usr/bin/cgirunner.

    Ответ 8

    Основываясь на предложениях от всех, я использовал xampp для запуска скриптов cgi. В Windows 8 он работал без каких-либо изменений, но Cent7.0 выдавал такие ошибки, как указано выше.

    AH01215: (2) Нет такого файла или каталога: exec из ‘/opt/lampp/cgi-bin/pbsa_config.cgi’ не удалось:/opt/lampp/cgi-bin/pbsa_config.cgi, referer: http:// < >/MCB_HTML/TestBed.html

    [Wed Aug 30 09: 11: 03.796584 2017] [cgi: error] [pid 32051] [клиент XX: 60624] Конец вывода script перед заголовками: pbsa_config.cgi, referer: http://xx/MCB_HTML/TestBed.html

    Учитывая полные разрешения для script, но 755 будет нормально

    Я наконец добавил, что -w как ниже

    #!/usr/bin/perl -w* use CGI ':standard'; < print header(), . end_html(); >**-w** indictes enable all warnings.It started working, No idea why -w here. 

    Источник

    «Конец ошибки script вывода перед заголовками» в Apache

    Apache в Windows дает мне следующую ошибку при попытке получить доступ к моему Perl script:

    Server error! The server encountered an internal error and was unable to complete your request. Error message: End of script output before headers: sample.pl If you think this is a server error, please contact the webmaster. Error 500 localhost Apache/2.4.4 (Win32) OpenSSL/1.0.1e PHP/5.5.3 
    #!"C:\xampp\perl\bin\perl.exe" print "Hello World"; 

    но не работает в браузере

    ОТВЕТЫ

    Ответ 1

    Если это CGI script для Интернета, вы должны вывести свой заголовок:

    #!"C:\xampp\perl\bin\perl.exe" print "Content-Type: text/html\n\n"; print "Hello World"; 

    Следующее сообщение об ошибке сообщает об этом End of script output before headers: sample.pl

    Или даже лучше, используйте CGI для вывода заголовка:

    #!"C:\xampp\perl\bin\perl.exe" use strict; use warnings; use CGI; print CGI::header(); print "Hello World"; 

    Ответ 2

    Проверить права доступа к файлам.

    У меня была точно такая же ошибка на машине Linux с неправильным набором разрешений.

    Ответ 3

    Обычно это ошибка, возникающая, когда вы не можете просмотреть или выполнить файл, причиной которого является, как правило, ошибка разрешений. Я бы начал с предложения @Renning и выполнил chmod 755 test.cgi (очевидно, замените test.cgi на имя вашего cgi script здесь).

    Если это не работает, вы можете попробовать еще пару вещей. Я однажды получил эту ошибку, когда создал test.cgi как root в другом доме пользователя. Исправлено было выполнение chmod user:user test.cgi , где пользователь — это имя пользователя, в котором вы находитесь.

    Последнее, что я могу придумать, это убедиться, что ваш cgi script возвращает правильные заголовки. В моем ruby ​​script я сделал это, положив puts «Content-type: text/html» , прежде чем я на самом деле вывел что-либо на страницу.

    Ответ 4

    Вероятно, это блок SELinux. Попробуйте следующее:

    # setsebool -P httpd_enable_cgi 1 # chcon -R -t httpd_sys_script_exec_t cgi-bin/your_script.cgi 

    Ответ 5

    Была та же ошибка на малине-пи. Я исправил его, добавив -w в shebang

    Ответ 6

    Итак, для всех, начиная с XAMPP cgi

    изменить расширение от pl до cgi
    измените разрешения на 755

    mv test.pl test.cgi chmod 755 test.cgi 

    Ответ 7

    Если вы используете Suexec, убедитесь, что script и его каталог принадлежат тому же пользователю, который вы указали в suexec.

    Кроме того, убедитесь, что пользователь, на котором запущен cgi script, имеет разрешения, выполняет разрешения на файл и программу, указанную в shebang.

    Например, если мой cgi script начинается с

    Тогда пользователю нужны разрешения для выполнения/usr/bin/cgirunner.

    Ответ 8

    Основываясь на предложениях от всех, я использовал xampp для запуска скриптов cgi. В Windows 8 он работал без каких-либо изменений, но Cent7.0 выдавал такие ошибки, как указано выше.

    AH01215: (2) Нет такого файла или каталога: exec из ‘/opt/lampp/cgi-bin/pbsa_config.cgi’ не удалось:/opt/lampp/cgi-bin/pbsa_config.cgi, referer: http:// < >/MCB_HTML/TestBed.html

    [Wed Aug 30 09: 11: 03.796584 2017] [cgi: error] [pid 32051] [клиент XX: 60624] Конец вывода script перед заголовками: pbsa_config.cgi, referer: http://xx/MCB_HTML/TestBed.html

    Учитывая полные разрешения для script, но 755 будет нормально

    Я наконец добавил, что -w как ниже

    #!/usr/bin/perl -w* use CGI ':standard'; < print header(), . end_html(); >**-w** indictes enable all warnings.It started working, No idea why -w here. 

    Источник

Оцените статью