Monday 5 December 2011

shell_exec() in php..is the usage similar to shell script

shell_exec() in php..is the usage similar to shell script

hey guys,
i am interested in using shell_exec but somehow it doesn't give me the output like i want.
Let me explain a little bit about what i did and what i am interested to do.
I have created a shell script which can execute a c program and this c program will create a text file according to some conditions.

so this is my shell script and i named it as test.sh:

echo -n "enter the value to pass to c programm : "
read var
echo "The value is : $var"
$(./myfile $var)

and below is my c program:
#include <stdio.h>
#include <stdlib.h>

int main(int arg,char *argv[])
{
int option=atoi(argv[1]);
int i=0;
int d[10]={1,2,3,4,5,6,7,8,9,10};
FILE *fp;
char file_one[]="text.txt";
char file_second[]="text1.txt";
printf("option:%d\n",option);
if(option==1)
{
fp=fopen(file_one,"a");
if(fp==NULL) exit(1);
}
if(option==2)
{
fp=fopen(file_second,"a");
if(fp==NULL) exit(1);
}

for(i=0;i<10;i++){
fprintf(fp,"x[%d]:%d,",i,d[i]);
}
return 0;
}
i compiled my c program using gcc -o myfile myfile.c as well as compile my shell script using chmod +x test.sh.then i executed my shell script using ./test.sh.Then it will ask me to give the value to my variable var.if i enter whatever value as the value of var,this value will be later passed to c program as the main argument.i convert the main argument argv[1] to integer using atoi(argv[1]).so by doing this i will give value to the variable option.then i used the if statements and provided conditions to them.if the condition true,the txt file will be created.for example i give the value of 1 to var in my shell script, and this value of 1 will be pass to argv[1].as argv is converted to integer,the option now will posses the value of 1.As option equal to 1 the 1st if statement will evaluate option==1 as true and as a result text.txt will be created.Otherwise if i enter 2,the text1.txt will be created

Using the same idea, i plan to used my php to do the same as shell script.
This is my php code
<html>
<title>File Option</title>
<body>
<h1>Give a suitable value</h1>
1:File_One
2:File_Two
<form method="post">
<p>Num1:<input type="text" name="arg1" size="40" value=""/></p>
<p><input type="submit" name="submit" value="GO"/>
</form>
<?php
if(isset($_POST['arg1']))
{
$num1=$_POST['arg1'];
if($num1){
$output=system("./myfile $num1");
print "<p>$output</p>";
}
}
?>
</body>
</html>
So basically the idea is if i enter 1 in the input and click GO,this value of 1 will pass to the main argument using the command shell_execution(./myfile $num1) and the text.txt will be created.unfortunately this text.txt has not created..i dont know why and thats why i decided to seek some ideas here..thanks in advanced

No comments:

Post a Comment