PHP header()

本文详细解释了PHP中header()函数的作用、使用方法及常见错误,并提供了正确使用示例,帮助开发者避免常见的输出错误。

header()函数向客户端发送原始的HTTP报头。

说明:

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

注意问题:

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 common error to read code with include,or require,functions,or another file access functionm and have spaces or empty lines that are output before haeder() is called. The same problem exists when using a single PHP/HTML file.

错误示例:在调用 header() 之前已存在输出如下面的<html>

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

正确使用示例:

示例1:

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

示例2:

<?php header('Location:http://www.example.com');/* Redirect brower */ /* Make sure that code below does not get executed when we redirect */ exit; ?>

示例3:

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

示例4:下载original.pdf,默认的保存文件名为download.pdf

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

转载于:https://my.oschina.net/syc2013/blog/177187

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值