PHP输出HTML头的应用

2012-05-15  金城  6411

点击下列跳转索引:
301 moved permanently
302 moved temporarily
404 page not found
Service not available
CSS
Javascript
Images(JPEG,BMP,PNG)
PDF
Force browsers not to cache pages
Download dialog
Authentication

PHP没有限制HTML内容的输出。PHP可以输出图像,PDF,Javascript 等文件。浏览器通过分析发送的HTML头信息判定文档的类型。本教程会展示几种发送头信息的例子。PHP使用header()函数来发送头信息,并且必须在任何内容输出前使用它。使用headers_sent()可以检查之前是否发送过任何头信息。


301 moved permanently (redirect):(301 永久跳转)
<?php 
header('HTTP/1.1 301 Moved Permanently');
header('Location:http://www.example.com');
die();
?>

302 moved temporarily(redirect):(302 临时跳转)
<?php 
header('Location:http://www.example.com');
die();
?>

404 Page Not Found:(404 资源没有找到)
<?php 
header('HTTP/1.1 404 Not Found');
?>

Service not avaliable:(服务不可用)
<?php 
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status:503 Service Temporarily Unavailable');
header('Retry-After:60');
?>

CSS:
<?php
header('Content-Type:text/css');
?>

Javascript header:
<?php 
header('Content-Type:application/javascript');
?>

Images:
For JPEG(jpg):
<?php 
header('Content-Type:image/jpeg');
?>
For PNG:
<?php 
header('Content-Type:image/png');
?>
For BMP:
<?php 
header('Content-Type:image/bmp');
?>

PDF (output pdf with php):
<?php 
header('Content-Type:application/pdf');
echo file_get_contents('filename.pdf');
?>

Cache (force browsers not to cache files):
<?php 
header('Expires:Sat,26 Jul 1997 05:00:00 GMT');
header('Cache-Control:no-store,no-cache,must-revalidate');
header('Cache-Control:pre-check=0,post-check=0,max-age=0');
header ('Pragma:no-cache'); 
?>

Download dialog:
<?php 
header('Content-Disposition:attachment;filename=' . urlencode($f));   
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($f));
echo file_get_contents($f);
?>

Authentication (force the browser to pop up a Username/Password input window) - only available when PHP is running as an Apache module:(身份验证<强迫浏览器弹出一个用户名/密码输入窗口>仅当PHP作为Apache的一个模块运行的时候)


<?php
if (!isset($_SERVER['PHP_AUTH_USER'])){
 header('WWW-Authenticate:Basic realm="The Realm"');
 header('HTTP/1.0 401 Unauthorized');
 echo 'If cancel is pressed this text shows';
 die();
}else{
 //always escape your data//
 $user='user';
 $pass='pass';
 if($_SERVER['PHP_AUTH_USER']==$user &&$_SERVER['PHP_AUTH_PW']==$pass){
   echo 'Authorized';
 }
}
?>