ตรวจสอบ session_start() หรือยัง

ตรวจสอบ session_start() หรือยัง ถ้ายังก็ start ซะสิ (^_^)

จริงๆแล้วการใช้ php ตามปกติเรามักถูกสอนหรือเจอคำแนะนำให้ session_start() ซะตั้งแต่บรรทัดแรกๆแล้วก็ใช้งานไป ไม่มีปัญหาครับ แต่ใครจะรู้ว่าจากประสบการณ์ของผมในบางงานเราก็ใช้มันในช่วงกลางๆของเรื่อง ซึ่งอาจ start ไปแล้วด้วยซับฟังก์ชั่นอื่นๆก่อนหน้านี้ ทีนี้ถ้า start ซ้ำก็จะเกิดเรื่องที่ไม่ควรเกิดได้ ดังนั้นก็ต้องตรวจก่อนว่า start ไปหรือยังจะได้ไม่ต้อง start ซ้ำ เรื่องนี้ผมพบ solution ในเว็บ http://www.php.net/manual/en/function.session-status.php ที่มีผู้ถามและตอบไว้เกี่ยวกับเรื่องนี้พอดี และเนื้อความค่อนข้างน่าสนใจครับลองอ่านดูครับ ส่วนท่านไหนไม่อยากรู้อยากจะใช้แล้วก็เหมือนเคยครับเชิญ (ท้ายบทความ) เก็บผลลัพธ์ของเรื่องเป็นฟังก์ชั่นที่ปรุงสำเร็จแล้วไปใช้พลางๆก่อนแล้วค่อยกลับมาอ่านทีหลังก็ไม่ว่ากันครับ

The advice of ive_insomnia at live dot com should be taken with great care. First of all, while his use case for session_status is valid, a simpler way to avoid the warning is:

<?php
    if (!isset($_SESSION)) { session_start(); }
?>

The example of session_status uses the raw values of constants (2 in this case) created specifically for the purpose of not having to use magic numbers.
Better code would be:

<?php
    if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
?>

The same can be done using

<?php
    if (session_id() === "") { session_start(); }
?>

The use of this function is lies more towards status management: change the behavior of a script when sessions are disabled altogether, for example.



ข้างล่างนี้คือฟังก์ชั่นแนะนำสำหรับเรื่องนี้ครับ ผมทำโครงร่างสำหรับการนำไปบรรจุไว้ในโปรเจ็คของคุณไว้ให้แล้วด้วยมือใหม่ๆก็คงดูไม่ยากนะครับ
<?php

function somefunction(){
if ( is_session_started() === FALSE ) session_start();
...
...
...
...
...
}

function is_session_started(){
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
}else{
            return session_id() === '' ? FALSE : TRUE;
        }
    }
return FALSE;
}
?>


แสดงความคิดเห็น

0 ความคิดเห็น