Sunday, February 19, 2012

วิธีแก้ [Solved] 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 ได้แก่ ขึ้นบรรทัดใหม่,เคาะสเปชบาร์,แท็บ โดยรวมคือช่องว่างที่มองไม่เห็น)
มีวิธีแก้ 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 } ?>



Credit : http://www.select2web.com