Page 1 of 1

Executing C code through PHP

Posted: Tue Aug 14, 2007 12:26 am
by nitdgp
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?

Posted: Tue Aug 14, 2007 4:08 am
by stereofrog

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`;
}
I'm wondering why you would need it.

Posted: Tue Aug 14, 2007 6:47 am
by nitdgp
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;
 }
[/syntax]

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]

Posted: Tue Aug 14, 2007 8:16 am
by volka
stereofrog wrote:echo $str | ./temp`

Posted: Tue Aug 14, 2007 9:13 am
by nitdgp
The above didn't work on windows. finally I did it using "piping data between processes".
Thanks both of you for your time.

Posted: Tue Aug 14, 2007 10:28 am
by stereofrog
For Windows you most probably have to remove ./

Welcome to the forums btw ;)

Posted: Tue Aug 14, 2007 10:34 am
by volka
You might also be interested in http://de2.php.net/proc_open