Catty
Catty

Reputation: 466

How to compile and run c program using exec command in php?

When I run

<?php
echo exec('whoami');
?>

It works fine, even for other single word command

but for exec('gcc -o a hello.c'); it does not create object file a.

Or when I try exec('./a'); with precreated object file, it does not make any change. No error no notification!

Any help is appreciable!

Upvotes: 3

Views: 3065

Answers (3)

James Holderness
James Holderness

Reputation: 23001

The most likely explanation is that the user account of your web server doesn't have write access to the directory. You can determine the account name by running whoami from within php.

exec('whoami', $output);
echo $output[0];

I don't know exactly what output you're going to get from that, but let's say it's www-data which is what I see on Ubuntu.

Now, if you look at the permissions of the web root directory, you'll probably find that it's owned by another account, maybe root, and the permissions are rwxr.xr.x so only root has access.

One way to give www-data write access is to make it the owner:

chown www-data .

Alternatively you can set the group to www-data and make sure that group has write access.

chgrp www-data .
chmod 775 .

Worst case you can give everybody write access, but I wouldn't recommend this unless nothing else works.

chmod 777 .

Ideally, you should really create a separate directory with write access, and limit any output to there rather than changing the permissions on the web root directory. But you can start with the root first and make sure this really is the problem before you go to too much effort.

Upvotes: 1

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146350

Basic reference:

With those elements, it's straightforward to obtain error messages:

<?php

exec('gcc -o a hello.c 2>&1', $output, $return_value);

echo ($return_value == 0 ? 'OK' : 'Error: status code ' . $return_value) . PHP_EOL;
echo 'Output: ' . PHP_EOL . implode(PHP_EOL, $output);

E.g., I get this in my (Windows) computer:

Error: status code 1
Output: 
"gcc" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.

Upvotes: 3

Daniel Gelling
Daniel Gelling

Reputation: 920

You could try using shell_exec() in PHP:

shell_exec('gcc -o a hello.c'); should work

Upvotes: 1

Related Questions