在线运行代码的 PHP 沙盒环境实现
演示:
作用:
- 方便作为独立的调试环境运行 一些 临时逻辑,查看执行结果。
- 方便比较不同版本的 PHP 执行差异,进行一般的兼容性测试。
思路:
Docker镜像构建多个PHP运行端口,使用 php 命令行来运行 PHP 脚本,借助 PHP 接口执行输入。
操作:
1. 编写 Dockerfile 构建 PHP 环境。
2. 在有 PHP 的环境中,终端可执行 `php test.php`
3. PHP 接口接受输入, 内容写入 test.php,借助 exec 函数执行终端命令。
代码:
Dockerfile
FROM php:7.4-apache COPY ./index.php /var/www/html/
PHP
<?php $code = isset($_POST['code']) ? $_POST['code'] : ''; $filename = md5(microtime(true) . mt_rand(1,9999)) . '.php'; file_put_contents($filename, $code); $outputFile = 'output.txt'; exec("php {$filename} > {$outputFile} 2>&1", $out, $result_code); $output = file_get_contents($outputFile); echo $output;
构建:
docker build .
docker images
docker run -d --name test_sandbox_1 -p 8081:80 4aa27e445284
docker ps
测试:
curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' -i 'http://localhost:8081/index.php' --data 'code=<?php echo PHP_VERSION; ?>'

浙公网安备 33010602011771号