Executing C code through PHP
Moderator: General Moderators
Executing C code through PHP
I want to compile and run a C program through PHP. I have used the shell_exec function to run the command of compiling the program. It works properly. Then I execute it.. its fine. But Suppose I have a C code in which the user accepts input from the user, like stdin, then how to achieve that using PHP? How to pass a particular input through PHP?
- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
Code: Select all
$c = <<<CODE
#include <stdio.h>
#include <string.h>
void main() {
static char buf[1024];
gets(buf);
puts(strrev(buf));
}
CODE;
if(isset($_GET['str'])) {
$str = escapeshellarg($_GET['str']);
file_put_contents('temp.c', $c);
echo `gcc -otemp -w temp.c && echo $str | ./temp`;
}feyd | Please use [/syntax]
feyd | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
I guess you have not understood the problem. I already have a (working )C code hello.c Now
[syntax="c"]#include<stdio.h>
int main()
{
int i;
scanf("%d",&i);
printf("%d\n",i);
return 0;
}Code: Select all
<?php
$command="gcc -c hello.c "; // am using devc++ on windows ..no problem in that..
$output=shell_exec($command);
print($output);// if any compilation error it gets displayed properly
$command="gcc hello.c -o hello" // linking and creating object file
$output=shell_exec($command);
[b]$command="hello"; //The problem is here. The code starts executing but how to give input. I can see the hello.c being executed in Windows task manager processes[/b]feyd | Please use
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
You might also be interested in http://de2.php.net/proc_open