PHP Warning: Cannot modify header information – headers already sent by

PHP Warning: Cannot modify header information – headers already sent by

สำหรับข้อความที่แสดงออกมานี้ เป็นข้อความที่เกิดขึ้นเมื่อเราเรียกใช้ฟังก์ชัน header() หลังจากบรรทัดที่มีการส่ง Output ออกไป
ไม่ว่าจะด้วยคำสั่ง echo “..”; หรือ การเว้นบรรทัดก็ตามดังตัวอย่าง

 <?php
     echo “Output Text” ;
     header(“Location:http://www.abc.com/index.php”) ;
 ?>
 
<?php
$abc = 123 ;
?>

 

<?php
header(“Location:http://www.abc.com/index.php”) ;
?>

ก็จะทำให้เกิดข้อความข้างต้นครับ วิธีการแก้ไขมีแนวทางปฏิบัติดังนี้

1. ไปลบข้อความหรือ Output ที่อยู่ก่อนหน้าฟังก์ชัน header() ออก เช่นหากเว้นบรรทัดก็ลบออก หรือย้ายข้อความก่อนหน้ามาหลังฟังก์ชัน header();
ดังตัวอย่าง

<?php     header(“Location:http://www.abc.com/index.php”) ;
     echo “Output Text” ;
 ?>

2. ใช้ java script ในการ redirect โดยแทรกอยู่ระหว่าง..แล้วใช้ตัวแปรในการตรวจสอบการ redirect แทน ดังตัวอย่าง

<?php if ($complete==”true”){ ?>
<script type=”text/javascript”>
window.location=”http://www.abc.com/index.php”;
</script>
<?php } ?>
 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *