java 到 php入門:header()重定向

header() 重定向用戶,常用的有兩種方式

1、 header('Location: url'); url重定向 相當於jsp sendRedirect()

2、header('Content-Type:text/html;charset=utf'); //頁面編碼

使用header函數必須注意:header函數之前不能有輸出

<?php
      echo 'hello';
      header('Location:header01.php');  // 重定向用戶
?>

客戶端運行結果:

hello
Warning: Cannot modify header information - headers already sent


要解決這個問題可以調用ob_start()緩存

<?php
     ob_start(); // 緩存
     echo 'hello';
     header('Location:header01.php');  // 重定向用戶
?>

程序正常運行緩存後再在運行。但是不推薦這麼使用

需要注意的是php代碼之前不能有html輸出

<?php
    // <?php 上有空行
?>

Warning: Cannot modify header information - headers already sent

2、
header('Content-Type:text/html;charset=utf');


中文亂碼的問題: php文件是什麼編碼,header的編碼應該與其相同,否則會出現中文亂碼

header('Content-Type:text/html;charset=utf-8');
    echo '我是中文';
 //瀏覽器顯示:鎴戞槸涓枃


開始我的zend studio(或php頁面編碼)默認編碼是gbk,而header編碼爲utf-8,所以出現了亂碼


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章