Disclaimer
I wrote this function (out of fun:) and because I'm lazy AF I wanted a short way to convert an array inside a string to a valid PHP array. I'm not sure if this code is 100% safe to use in production as exec
and it's sisters always scare the crap out of me.
$myArray = 'array("key1"=>"value1", "key2"=>"value2")';
function str_array_to_php(string $str_array) {
// No new line characters and no single quotes are allowed
$valid_str = str_replace(['\n', '\''], ['', '"'], $str_array);
exec("php -r '
if (is_array($valid_str)) {
function stap(\$arr = $valid_str) {
foreach(\$arr as \$v) {
if(is_array(\$v)){
stap(\$v);
}
else {
echo \$v,PHP_EOL;
}
}
}
stap();
}'2>&1", $out);
return $out;
}
print_r(str_array_to_php($myArray));
Output:
Array ( [0] => value1 [1] => value2 )
As you can see, it will convert $myArray
into a valid PHP array, and then indexes it numerically and if it is multidimensional it will convert it into single one.
BE CAREFUL:
1- never pass the array in double quotes as this will allow null byte characters (\0) to be evaluated.
For example:
$myArray = "array(\"key1\"=>\"value\n\0 ggg\", \"key2\"=>\"value2\")"
//Output: Warning: exec(): NULL byte detected. Possible attack
2- This function wont work if exec
is disabled (Mostly will be )
3- This function wont work if php
command is not set
One last thing, if you find any error or flaws please let me know in the comments so i can fix it and learn.
Hope this helps.