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

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

使用PHP header进行页面跳转出现的问题解疑(php页面跳转可以用header)  PHP header 第1张

在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. <%ifRequest.ServerVariables("SERVER_NAME")="s.jb51.net"then
  3. response.redirect"news/index.htm"
  4. else%>
  5. <%endif%>
  6. <script>
  7. varurl=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时应当注意的几点问题。

转载请说明出处
知优网 » 使用PHP header进行页面跳转出现的问题解疑(php页面跳转可以用header)

发表评论

您需要后才能发表评论