Question

I have a web application running on PHP. It sometimes has bugs, and I'd like to be able to reproduce specific requests locally through the CLI SAPI. The way I imagined doing it was something like this:

<?php
// index.php
if (!empty($_GET["export_for_debug"]) && DEBUG_MODE) {
    file_put_contents("request.dat", serialize(get_defined_vars()));
}

// resume normal execution

This isn't for any public facing feature, it's just to allow reproducible requests for debugging with phpdbg or similar.

However, I'm having trouble extracting the request variables into the current global ones.

<?php
// test_request.php

// get the request variables
$vars = unserialize(file_get_contents("request.dat"));

// this doesn't work
extract($vars);

// neither does this
foreach ($vars as $key => $val) {
    $$key = $val;
}

tl;dr: How do I extract an array that looks like this:

array("_SERVER" => array("foo" => "bar"))

Into the current scope?


Edit:

I got it. You can overwrite the globals, but it seems like the code needs to be eval'd. After a little bit of trial and error, here's what I got:

<?php

// get the request variables
$vars = unserialize(file_get_contents("request.dat"));

foreach ($vars as $key => $val) {
    eval("\${$key} = \$val;");
}

Is there a better way of doing this?

Was it helpful?

Solution

If you want to use phpdbg console:

1) Create file named .phpdbginit into the working directory from which you call phpdbg. File contents:

<:
extract(array("_SERVER" => array("foo" => "bar")));
:>

2) Start debugging console phpdbg -e PATH/TO/SCRIPT/NAME.php. For example phpdbg -e index.php

3) Test if it works using command ev $_SERVER

For me with php 5.6.12 and phpdbg v0.4.0, it prints:

root@host:/var/www/html# cat .phpdbginit
<:
extract(array("_SERVER" => array("foo" => "bar")));
:>
root@host:/var/www/html# phpdbg -e index.php
[Welcome to phpdbg, the interactive PHP debugger, v0.4.0]
To get help using phpdbg type "help" and press enter
[Please report bugs to <http://github.com/krakjoe/phpdbg/issues>]
[Attempting compilation of /var/www/html/index.php]
[Success]
phpdbg> ev $_SERVER
Array
(
    [foo] => bar
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top