【问题标题】:c program shell input through phpc程序shell通过php输入
【发布时间】:2014-09-05 01:00:16
【问题描述】:

我正在尝试开发可以通过 php 执行 c 程序的东西,使用 system()exec() 命令,它确实执行 c 程序,但这里的问题是 - 如果 c 程序包含 scanf() 语句, system() 不要求用户在 php 网页上输入。

我不太确定它是否可以完成。

<?php

$content = $_POST['content']; //Getting the code from web form
$file = fopen("code.cpp","w"); //Opening a file in write mode
fwrite($file,$content); //Store the code to file code.cpp



$my_file = 'code.cpp';

system("gcc {$my_file} 2> error.txt"); //Compile a c program and log the errors to error.txt

$error = file_get_contents("error.txt"); //Getting contents of error.txt to a variable

if($error=='')
    system("./a.out"); //Executing the c program
else{
$fp = fopen("error.txt","r");    
while (! feof($fp)){             //Printing the output line by line
echo fgets($fp). "<br />";
}
}
fclose($content);

unlink('a.out');
unlink('code.cpp');

?>

我在安装了gcc 的ubuntu 机器上托管了php 页面。任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 这看起来很邪恶,每个有权访问该 php 脚本的人都可以注入和执行任意代码
  • 你有什么解决办法吗?我想执行一个 c 程序,它应该在 php 网页上接受用户输入并在同一页面上执行它,这是否可能

标签: php c shell


【解决方案1】:

抛开安全问题...

  1. $_POST 的数据创建一个输入文件。
  2. 在执行程序时重定向文件的内容。

这是更新后的 PHP 文件。

<?php

$content = $_POST['content']; //Getting the code from web form
$file = fopen("code.cpp","w"); //Opening a file in write mode
fwrite($file,$content); //Store the code to file code.cpp
fclose($file);

$inputData = $_POST['inputData']; //Getting the data from web form
$file = fopen("input.txt","w"); //Opening a file in write mode
fwrite($file,$inputData); //Store the data to file input.txt
fclose($file);

$my_file = 'code.cpp';

system("gcc {$my_file} 2> error.txt");

$error = file_get_contents("error.txt");

if($error=='')
   system("./a.out < input.txt");
else {
   $fp = fopen("error.txt","r");    
   while (! feof($fp)){
      echo fgets($fp). "<br />";
   }
}

unlink('a.out');
unlink('input.txt');
unlink('code.cpp');

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2019-09-16
    • 2014-02-09
    相关资源
    最近更新 更多