parsing a String in PHP
i got a string in the following format:
a:5:{s:21:"securimage_code_value";s:4:"4l7z";s:6:"userID";s:2:"25";s:8:"username";s:6:"lu开发者_高级运维poxy";s:10:"angemeldet";s:4:"true";s:9:"user_role";s:3:"111";}
I need to parse the entries within the quotes, and get an Array like this:
$testarray[0]['key'] = "securimage_code_value";
$testarray[0]['value'] = "417z";
$testarray[1]['key'] = "userID";
$testarray[1]['value'] = "25";
and so on...
No I'm not trying to hack any sessions ;) I'm using Uploadify with Codeigniter, and I need to verify, that a user is allowed to upload, based on his session. I cannot use the Codeigniter session functions, since Uploadify creates its own session for the Upload-PHP-Script. So I pass the session_id as Uploadify scriptdata, and then I look for the session_id in the ci_sessions table, to parse the required session userdata myself.
Maybe somebody knows a better solution for this as well? ;)
$params = unserialize($string);
$testarray = array();
foreach($params as $key => $value) {
$testarray[]= compact('key', 'value');
}
See unserialize documentation.
UPDATE. You could also inherit/patch sess_read()
from system/libraries/Session.php to make it accept custom session ID:
Before:
function sess_read() {
...
// Unserialize the session array
$session = $this->_unserialize($session);
...
}
After:
function sess_read($session_id = null) {
...
// Unserialize the session array
$session = $this->_unserialize($session);
if ($session_id) $session['session_id'] = $session_id;
...
}
Also remember to set sess_match_useragent = false
in session config file, otherwise request from Uploadify will be rejected, because Flash's user agent is different from broswer's user agent.
And now you can load any session by ID:
$this->session->sess_read($custom_session_id)
Much less of a hack than parsing data from DB manually.
I believe you're looking for unserialize()
http://php.net/manual/en/function.unserialize.php
the complet code
<?php
$s = 'a:5:{s:21:"securimage_code_value";s:4:"4l7z";s:6:"userID";s:2:"25";s:8:"username";s:6:"lupoxy";s:10:"angemeldet";s:4:"true";s:9:"user_role";s:3:"111";}';
$final = array();
foreach (unserialize($s) as $k => $v) {
$final[] = array('key' => $k, 'value' => $v);
}
var_dump($final);
精彩评论