简体   繁体   中英

Executing a linux command with php exec() and running a shell script

i am trying to run this piece of php code on my server:

<?php
$cmd = 'echo "this is a test" > /home/ubuntu/scripts/test_file';
echo exec($cmd);
?>

From my understanding it should add the piece of text to the file test_file . The file exists in the appropriate location and i have tried chmod 755 and chmod 777 on the php file. But i dont see the text being added to the text_file . I tried running the linux command directly on the server and it works. Could some one tell me what i am doing wrong?

Also, i am trying to create a virtual host file on the server through a php script. Rather than running the commands through php exec() , i thought it would be better to run a shell script, with the shell script reading the required parameters from a text file and setting the directory path in the virtual host file. I am new to linux, is this a good approach or is there a better way in going about this? All this is being done to setup a magento based site programatically. Thanks.

Your code is OK. The problem probably either lies with your php being in safe mode (though it's deprecated, see link) or with file/directory permissions.

No need to give the file permissions 0777 since that makes the file executable, 0666 should suffice. It is not enough however for the file to have the right permissions, each directory on the path must be traversable. Try a different directory to which the user with whose privileges the php code runs has access, /tmp is a good start.

General way to debug problems like this is to execute a different command which gives you extra information about the context in which echo is executed, eg

<?php
echo exec("id");
echo "<br/>";
echo exec("ls -l /home/ubuntu/scripts/test_file");
?>

(remember exec() only returns the last line of command's output, these display just one line though). These commands will tell you the user which runs the code and whether they can see the file at all.

As the comment already said: this is actually bad way to accomplish what you're trying to do, as writing Apache configuration based on user input through web could open you up to multiple issues.

What you might consider, is to have the PHP side write the required information to a file, or a database, which is then polled every now and then via a cron script or similar by a different process that does the actual configuration changes. This eliminates the need to exec() from PHP (which is always bad). With this, your process that runs PHP wouldn't need to have write permissions to important system files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM