Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php session_start general error handling

I'm looking for a general way to handle session_start errors, not a way to handle one specific error. There are numerous errors which can happen, such as the session directory being full, which cause a fatal error. I want a way to trap those errors and handle them cleanly, without having to write custom handlers for each possibility.

Something like this (but not this as it doesn't work):

try{
    session_start();
}catch(Exception  $e){
    echo $e->getMessage();
}

All help appreciated, thanks in advance.

like image 719
user2320402 Avatar asked May 15 '13 14:05

user2320402


1 Answers

The regular PHP session functions don't throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.

function session_error_handling_function($code, $msg, $file, $line) {
    // your handling code here
}

set_error_handler('session_error_handling_function');
session_start();
restore_error_handler();

However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from errors and surround code parts that may throw errors with try ... catch blocks.

like image 69
chiborg Avatar answered Oct 12 '22 23:10

chiborg