使用PHP header进行页面跳转出现的问题解疑 - Go语言中文社区

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


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

在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时应当注意的几点问题。

【责任编辑:曹凯 TEL:(010)68476606】

点赞 0
版权声明:本文来源51CTO,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:http://developer.51cto.com/art/200912/166403.htm
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-16 23:06:12
  • 阅读 ( 624 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢