I'm having some problems when trying to unserialize an array in PHP.
I have two methods in a class, one to handle storing a serialized array in a mysql table and one to retrieve it.
I get the following error when executing the second method (when retrieving / unserializing):
Notice: unserialize(): Error at offset 50623 of 50647 bytes in /Users/benwaine/NetBeansProjects/SentimentEngineMk2/lib/TSE/Mapper/Filter.php on line 39
The string is stored ina blob field in MySQL. The array is multi-dimentional and composed of a token with an array of floats. The problem is intermittent perhaps suggesting the issue is with the tokens?
// Structure
keywordA - 0.234
- 0.234
KeywordB - 0.23
- 0.47
// Methods
public function insertFilterForKeyword($id, array $filterProbs)
{
$sql = "INSERT INTO filter (keyword_id, filter_probs, sample_size_pos, sample_size_neg)
VALUE (:id, :filterProbs, :pos, :neg)";
$stmt = $this->pdo->prepare($sql);
$meta = array_shift($filterProbs);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':filterProbs',serialize($filterProbs));
$stmt->bindParam(':pos', $meta['sample_size_pos']);
$stmt->bindParam(':neg', $meta['sample_size_neg']);
$result = $stmt->execute();
return $result;
}
public function getFilterByKeyword($keyword)
{
$sql = 'SELECT f.id, f.keyword_id, f.filter_probs, f.sample_size_pos, f.sample_size_neg
FROM filter f
JOIN keyword k ON k.id = f.keyword_id
WHERE k.keyword = :keyword';
$stmt = $this->pdo->prepare($sql);
$stmt->bindParam(':keyword', $keyword);
$result = $stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$probArray = unserialize($data['filter_probs']);
$filter = new TSE_Filter($probArray);
return $filter;
}
I'm guessing the error has to do with characters in the data that are causing deserialization issues.
After googling I tried methods the deserialization line in the following ways, none of which worked:
1) base64_encode / decode the serialized string.
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));
//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
2) Use a preg match to alter potentially difficult characters:
unserialize(preg_replace('/;n;/', ';N;', strtolower($data['filter_probs'])));
Any help would be much appreciated!
Thanks.