09/10/2018, 18:06
Help! Lỗi ngớ ngẩn trong PHP về Session
Tôi có một đoạn code đơn giản như sau.
Nhưng khi test thử trên localhost (và ngay cả trên host) thì bị lỗi sau:
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at c:inetpubwwwroota.php:1) in c:inetpubwwwroota.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at c:inetpubwwwroota.php:1) in c:inetpubwwwroota.php on line 2
Registered: 22
Các bạn cho tôi biết nguyên nhân tại sao với. Thanks!
Code:
<?php session_start(); $snumber=22; session_register("snumber"); if (session_is_registered("snumber")) { echo "Registered: ". $snumber; } else { echo "Fail to register"; } ?>
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at c:inetpubwwwroota.php:1) in c:inetpubwwwroota.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at c:inetpubwwwroota.php:1) in c:inetpubwwwroota.php on line 2
Registered: 22
Các bạn cho tôi biết nguyên nhân tại sao với. Thanks!
Bài liên quan
Cannot send session cookie - headers already sent by (output started at c:\inetpub\wwwroot\a.php:1)
Rất mong reply!
<?php
@session_start();
.......
?>
Nguyên nhân nó báo lỗi là do session bạn dùng cookies để quản lý, và cookies này được gửi tới client bằng các "header" information. Và phần header này phải được gửi đi trước các phần còn lại của một HTTP request. Nói đơn giản là do trong trang của bạn có một dòng trắng đầu tiên nên khi dịch file a.php của bạn, PHP engine gửi luôn thông tin header đi rồi, do đó khi bạn dùng các hàm session sẽ không gửi thêm thông tin trong phần header đến client nữa.
Khi gặp trường hợp này, bạn hãy test nó :
if isset($snumber){... bạn register...}
Có lẽ là mình đã trả lời câu hỏi bạn cần.
Reply Cont.
Sướng quá! Tôi đã khắc phục được rồi. Làm theo cách thêm @session_start(); thật đơn giản và hiệu quả.
Cảm ơn tất cả các bạn. Thế là tôi lại có thể tiếp tục rồi...