วิธีแก้ปัญหา Warning: Cannot modify header information – headers already sent by… Warning: Cannot modify header information – headers already sent by


หน้าแรก PHP MySQL เกร็ดความรู้ วิธีแก้ปัญหา Warning: Cannot modify header information – headers already sent by… Warning: Cannot modify header information – headers already sent by
ปัญหานี้เกิดจาก เรียกใช้คำสั่ง header() หลังจากมี output ส่งไปยัง client แล้ว

ดูตัวอย่างที่มีปัญหานะครับ
1.
<?php
echo "Some text" ;
header("Location:index.php") ;
?>

2.
<html>
<?php
header("Location:index.php") ;
?>

3.
<?php
$variable = 10 ;
?>
 
<?php
header("Location:index.php") ;
?>

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

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

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

1.หาให้เจอว่ามีเอ้าพุตอะไรออกไปในบรรทัดที่ php ฟ้อง
2.ใส่คำสั่ง ob_start() ใว้บนบรรทัดแรกสุดๆ ของไฟล์ (ไม่แนะนำ)
3.เอาคำสั่งจาวาสคริปเข้าช่วยในการ redirect

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

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



ขึ้นไปด้านบน