使用PHP header进行页面跳转出现的问题解疑

开发 后端
PHP header在使用的过程需要注意一些问题,在这篇文章中我们将为大家详细的介绍这些问题,以便大家牢固掌握PHP header的含义。

我们在进行页面跳转的时候,通常会用到PHP header。那么如何才能正确的使用PHP header呢?我们在使用的过程中应当注意些什么问题呢?#t#

在PHP中用header("location:test.php")进行跳转要注意以下几点,有助于解决一些新手经常遇到的问题

1、location和“:”号间不能有空格,否则会出错。
2、在用header前不能有任何的输出。
3、header后的PHP代码还会被执行。

下面是和asp中重定向response.redirect的比较:

例1:

response.redirect "../test.asp"
header("location:../test.php");

两者区别:

asp的redirect函数可以在向客户发送头文件后起作用.

  1. < html>< head>< /head>< body> 
  2. < %response.redirect "../test.asp"%> 
  3. < /body>< /html> 

查是php中下例代码会报错:

  1. < html>< head>< /head>< body> 
  2. <? 
  3. header("location:../test.php");  
  4. ?> 
  5. < /body>< /html> 
  6. 只能这样:  
  7. < ?   
  8. header("location:../test.php");  
  9. ?> 
  10. < html>< head>< /head>< body>...< /body>< /html> 

即PHP header之前不能向客户发送任何数据.
例2:

asp中

  1. < html>< head>< /head>< body> 
  2. <%  
  3. response.redirect "../a.asp"  
  4. response.redirect "../b.asp"  
  5. %> 
  6. < /body>< /html> 
  7. 结果是重定向a.asp文件.  
  8. php呢?  
  9. < ?  
  10. header("location:../a.php");  
  11. header("location:../b.php");  
  12. ?> 
  13. < html>< head>< /head>< body>< /body>< /html> 

我们发现它重定向b.php.
原来在asp中执行redirect后不会再执行后面的代码.
而php在执行header后,继续执行下面的代码.
在这方面上php中的header重定向不如asp中的重定向.有时我们要重定向后,不能执行后面的代码:
一般地我们用

  1. if(...)  
  2. header("...");  
  3. else  
  4. {  
  5. ...  
  6. }  

但是我们可以简单的用下面的PHP header方法:

  1. if(...)  
  2. { header("...");exit();}  

还要注意的是,如果是用Unicode(UTF-8)编码时也会出现问题,需要调整PHP header的缓存设置.

  1. < [email=%@]%@LANGUAGE="VBSCRIPT[/email]" CODEPAGE="936"%> 
  2. < %if Request.ServerVariables("SERVER_NAME")="s.jb51.net" then  
  3. response.redirect "news/index.htm"  
  4. else%> 
  5. < %end if%> 
  6. < script> 
  7. var url = location.href;  
  8. if(url.indexOf('http://www.jb51.net/')!=-1)location.href='/index/index.htm';  
  9. if(url.indexOf('http://www.kanshule.com/')!=-1)location.href='/index1/index.htm';  
  10. if(url.indexOf('http://www.shouji17.com/')!=-1)location.href='/cn/index.asp';  
  11. if(url.indexOf('http://www.baidu.com/')!=-1)location.href='/cn/index.asp';  
  12. < /script>  

以上就是在使用PHP header时应当注意的几点问题。

责任编辑:曹凯 来源: 网易博客
相关推荐

2009-12-07 10:05:22

PHP session

2009-12-01 15:41:16

PHP substr截

2010-03-15 17:17:29

Java线程池

2009-12-08 10:33:23

PHP应用问题

2009-12-03 15:13:51

PHP开发中问题

2009-12-31 15:28:02

Silverlight

2010-02-05 16:07:52

C++多态覆盖

2010-01-04 13:15:33

跨域引用Silverl

2009-02-04 18:20:42

服务器虚拟化VMware

2010-02-02 13:20:33

C++对象传递

2015-05-05 10:51:32

php页面跳转方法

2009-11-23 18:47:51

PHP中用header

2009-12-02 20:02:18

PHP实现页面跳转

2009-12-02 19:42:24

PHP页面自动跳转

2010-01-20 14:52:21

VB.NET修改数据窗

2009-12-11 13:25:01

PHP页面跳转

2009-12-02 20:09:45

PHP页面跳转函数

2009-11-27 10:02:54

PHP mb_strw

2009-12-11 13:33:14

PHP无法修改head

2009-11-27 16:13:21

PHP递归返回值
点赞
收藏

51CTO技术栈公众号