简体   繁体   中英

PHP execute sed shell command

Im trying to execute a sed shell command through PHP to change some string in a file. The file is located at /etc/text.txt and I try to modify some text inside that file using following code :

$old_path = getcwd();
chdir('/etc/');
$cmd = "sed -i 's/footext/newtext/g' text.txt";
exec($cmd);
chdir($old_path);

But the text 'footext' at text.txt doesn't change.

Please help me solve this problem

Thanks

First of all I'd like to re-iterate the inherent dangers of allowing your (public) web-server to change system files. Doing this will lead to an attacker compromising your system, it's only a question of how much time it takes.

That said, there are a couple of issues with your code. The first of which is the reliance upon external third party (shell) commands, for something that could, and should, be done in pure PHP instead.
Editing text is one of PHP's main strengths, after all, and the code would be quite simple. As an example...

if (!$content = file_get_contents ($filename)) {
    // Handle errors opening/reading the file here.
}

// Assuming case-sensitive search and replace here, as per the `sed` used.
$content = str_replace ("old text", "new text", $content);

if (!file_put_contents ($filename, $content)) {
    // Handle errors with writing to the file here.
}

The main benefit of this is that you don't need to rely upon unrelated third party programs to be present (even though sed is quite ubiquitous). Which makes the code is a lot easier to understand, self-contained, and thus platform agnostic (to the fullest extent possible).

AS for why your code doesn't work, I too suspect that this has something to do with file permissions. As noted in the comments, the www-data user does not have permission to write to the /etc/ folder by default. So in order to enable it to edit a file there, you first need to create the file with a root-enabled user, and then change the ownership to www-data .
However, do not under any circumstances do this to already existing files in this folder. The potential for unintended, and catastrophic, side effects is just too huge!

If you absolutely need to have a PHP script modify the system file, write a shell-script and invoke it via crontab or something similar. After you've made 100% sure that the input is 100% safe from abuse. (IE: Printable characters only, preferably ASCII.)

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