2012-12-20 117 views
4

在php中使用反序列化時,處理變量不能反序列化的潛在情況的最安全方法是什麼?php安全反序列化

例如(不,我會永遠這樣,只是爲了例子):

$myVar = true; 

$result = unserialize($myVar); 

這將返回錯誤,這是罰款。但它也引發了一個討厭的通知。

我一直在做以下幾點:

$result = @unserialize($myVar); 

這感覺哈克。那麼,什麼是反序列化時,有虛假

+2

我想理想的解決方案是隻反序列化的變量,你確定包含一個序列化的字符串。出於安全原因,您不應該接受來自不可信外部源的序列化PHP數據,所以您應該能夠相當確信您認爲是序列化字符串的變量確實如此。如果你對此沒有把握,那麼你會遇到更大的問題。 – Spudley

+0

我認爲一個「討厭的通知」是一個很好的回覆失敗的反序列化(反正你可以也不應該顯示這些通知)。你說的「最安全」和「最好」是什麼意思?我認爲'@ unserialize'是好的,如果你不關心被通知錯誤。 –

+0

@Spudley我完全明白你在說什麼。我想這實際上是這裏真正的挑戰。由於我的問題的性質,我根本無法看到確保我加載的模型始終具有此特定屬性集和序列化的方法。 –

回答

3

的可能性您可以使用的try/catch錯誤處理的最佳方式:

set_error_handler('exceptions_error_handler'); 
function exceptions_error_handler($severity, $message, $filename, $lineno) { 
    if (error_reporting() == 0) { 
    return; 
    } 
    if (error_reporting() & $severity) { 
    throw new ErrorException($message, 0, $severity, $filename, $lineno); 
    } 
} 
$string = 'bob'; 
try { 
    $result = unserialize($string); 
} catch (Exception $e) { 
    echo 'Caught exception: ', $e->getMessage(), "\n"; 
} 
if(isset($result)) { 
    //Continue code for valid serialized array here 
} 
+0

但是就像上面的評論,我會推薦JSON over serialized arrays。我回答了發佈的問題。 – Pitchinnate