2012-10-02 18 views

उत्तर

8

नहीं, आप इसे पकड़ नहीं सकते, unserialize() अपवाद नहीं फेंकता है।

यदि पारित स्ट्रिंग अचूक नहीं है, तो FALSE वापस कर दिया गया है और E_NOTICE जारी किया गया है।

आप सभी त्रुटियों को संभालने के लिए एक कस्टम अपवाद हैंडलर सेट कर सकते हैं:

function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 
3

Convert सभी पीएचपी त्रुटियों अपवादों को (चेतावनी नोटिस आदि)। उदाहरण here है।

9

एक आसान तरीका है:

$ret = @unserialize($foo); 
if($ret === null){ 
    //Error case 
} 

लेकिन यह सबसे आधुनिक समाधान नहीं है।

कस्टम त्रुटि/अपवाद हैंडलर (न केवल इस मामले के लिए) होने से पहले सबसे अच्छा तरीका बताया गया है। लेकिन आप जो कर रहे हैं उसके आधार पर यह अधिक हो सकता है।

+2

: मामले में स्ट्रिंग पारित unserializeable नहीं है, गलत दिया जाता है। सौभाग्य से कुछ लोग 'serialize (false) ' – gfaceless

+0

करेंगे" यदि पारित स्ट्रिंग अचूक नहीं है, तो FALSE वापस कर दिया गया है ** और E_NOTICE जारी किया गया है **। " एक ई_ भी फेंक दिया जाता है। – zedee

2

एक पूर्ण समाधान निम्नलिखित दिखाई देगा:

<?php 
// As mentioned in the top answer, we need to set up 
// some general error handling 
function exception_error_handler($errno, $errstr, $errfile, $errline) { 
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline); 
} 
set_error_handler("exception_error_handler"); 


// Note, there are two types of way it could fail, 
// the fail2 fail is when try to unserialise just 
// false, it should fail. Also note, what you 
// do when something fails is up to your app. 
// So replace var_dump("fail...") with your 
// own app logic for error handling 
function unserializeSensible($value) { 
    $caught = false; 
    try { 
     $unserialised = unserialize($value); 
    } catch(ErrorException $e) { 
     var_dump("fail"); 
     $caught = true; 
    } 
    // PHP doesn't have a try .. else block like Python 
    if(!$caught) { 
     if($unserialised === false && $value !== serialize(false)) { 
      var_dump("fail2"); 
     } else { 
      var_dump("pass"); 
      return $unserialised; 
     } 
    } 
} 

unserializeSensible('b:0;'); // Should pass 
unserializeSensible('b:1;'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:"foo";}'); // Should pass 
unserializeSensible('a:2:{s:1:"a";b:0;s:1:"b";s:3:1111111111111111;}'); // Should fail 
unserializeSensible(123); // Should fail 
unserializeSensible("Gday"); // Should fail 
unserializeSensible(false); // Should fail2 
unserializeSensible(true); // Should fail 
प्रलेखन प्रति
संबंधित मुद्दे