2

Ok i wanted to create a crawler with my PHP script. Certain parts of my crawler requires real fast manipulation of strings thats why i have decided to use a C/C++ program to assist my PHP script for that particular job. The following is my code:

$op=exec('main $a $b');
echo $op;

main is the executable file generated using my C file main.c i.e main.exe. in the above operation i just made a simple C program which accepts 2 values from PHP and returns the sum of the two values. the following is how my C program in looking like

#include< stdio.h >
#include< stdlib.h >
int main(int argc, char *argv[])
{
  int i=add(atoi(argv[1]),atoi(argv[2]));
  printf("%d\n",i);
  return 0;
}

int add(int a, int b)
{
  int c;
  c=a+b;
  return c;
}

i tried to execute the program via the CMD main 1 1 and it returned 2....it worked! when i entered them in the php script like this,

$a=1;
$b=1;
$op=exec('main $a $b');
echo $op;

it didn't work as expected so any ideas, suggestions or anything else i need to do on my code. I would be great if you could show me an example. THANKS IN ADVANCE!!!

2
  • 3
    You need to review the strings part of the manual an dunderstand the differences between single quotes and double quotes. Commented Jun 17, 2012 at 8:05
  • I hope you do realise string standard PHP functions for string manipulation are C++. I've seen this mistake made before, by people who benchmarked an executable vs a PHP function, instead of benchmarking the PHP+exec+executable VS PHP. Commented Jun 17, 2012 at 8:28

3 Answers 3

3

You should enclosed the arguments of exec with double quotes since you're passing variables. And the output of your program is in the second argument of exec.

exec("main $a $b", $out);
print_r($out);

See exec() reference.

Sign up to request clarification or add additional context in comments.

Comments

2

The function atoi() cannot distinguish invalid and valid inputs. I suggest you use strtol() instead.

#include <stdio.h>
#include <stdlib.h>

void quit(const char *msg) {
  if (msg) fprintf(stderr, "%s\n", msg);
  exit(EXIT_FAILURE);
}

int add(int, int);

int main(int argc, char *argv[]) {
  int a, b, i;
  char *err;

  if (argc != 3) quit("wrong parameter count");
  a = strtol(argv[1], &err, 10);
  if (*err) quit("invalid first argument");
  b = strtol(argv[2], &err, 10);
  if (*err) quit("invalid second argument");

  i = add(a, b);
  printf("%d\n", i);
  return 0;
}

int add(int a, int b) {
  return a + b;
}

2 Comments

No. It has to do with his quotes.
Of course it has to do with his quotes, which is trivial (and, frankly speaking, can be solved just with comment). But this answer deals with more subtle error, hence +1 from me.
0

You need to create an executable ./main. And then use this code.It works

<?php
 $a=1;
 $b=1;
 echo exec("./main $a $b"); 
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.