ผู้เขียน หัวข้อ: แก้ปัญหา Warning: Cannot modify header information – headers already sent by  (อ่าน 820 ครั้ง)

0 สมาชิก และ 1 บุคคลทั่วไป กำลังดูหัวข้อนี้

ออฟไลน์ clean

  • Administrator
  • Dev lnw
  • *****
  • กระทู้: 492
  • โดนถีบ +321/-0
    • ดูรายละเอียด
    • อีเมล์
แก้ปัญหา Warning: Cannot modify header information – headers already sent by
« เมื่อ: 23 กุมภาพันธ์ พ.ศ. 2011, 17:28:39 »

Warning: Cannot modify header information – headers already sent by

ปัญหานี้เกิดจาก เรียกใช้คำสั่ง header() หลังจากมี output ส่งไปยัง client แล้ว

ดูตัวอย่างที่มีปัญหานะครับ

1.
โค๊ด: [Select]
<?php
echo "Some text" ;
header("Location:index.php") ;
?>

2.
โค๊ด: [Select]
<html>
<?php
header
("Location:index.php") ;
?>

3.
โค๊ด: [Select]
<?php
$variable 
10 ;
?>

 
<?php
header
("Location:index.php") ;
?>
มีคำว่า Some text ถูกส่งออกไปแล้ว
มีคำว่า <html> ถูกส่งออกไปแล้ว
มี white space ถูกส่งออกไปแล้ว ระหว่างบล็อก php ทั้งสอง ( white space ได้แก่ ขึ้นบรรทัดใหม่,เคาะสเปชบาร์,แท็บ โดยรวมคือช่องว่างที่มองไม่เห็น)

มีวิธีแก้ 3 วิธี

1.หาให้เจอว่ามีเอ้าพุตอะไรออกไปในบรรทัดที่ php ฟ้อง

2.ใส่คำสั่ง ob_start() ใว้บนบรรทัดแรกสุดๆ ของไฟล์ (ไม่แนะนำ)

3.เอาคำสั่งจาวาสคริปเข้าช่วยในการ redirect

หลังจากที่คุณกระทำการอะไรบางอย่างเสร็จและต้องการใช้คำสั่ง header() redirect ไปเพจอื่น ให้เปลี่ยนจากคำสั่ง header() เป็นเซตค่าตัวแปรสักตัว

โค๊ด: [Select]
$complete = "true" ;
แล้วทีนี้ตรงระหว่างแท็ก <head></head> ใส่คำสั่งนี้เข้าไป
โค๊ด: [Select]
<?php if ($complete=="true"){ ?>
<script type="text/javascript">
window.location="gbook.php";
</script>
<?php ?>

ข้อมูลดีดี จาก select2web.com

1 Tive Who's like!? [Click to Show!]