0

I have a case that require I to write some string to the file that only root can do that. I was try some solutions base on this post but none of them works.

CASE: When user was successfully done, he automatically access writefile.php which contain script that can write to the file ( tes.txt ) that only root have access.

I used visudo and added this to my sudoers file:

username ALL=(root) NOPASSWD: /var/www/html/myprogram/writefile.php not works!

username ALL=(ALL) NOPASSWD: /var/www/html/myprogram/writefile.php not works!

My simple code in writefile.php

<?php
echo file_put_contents("tes.txt","Hello World. Testing!");
?>

Result:

Warning: file_put_contents(tes.txt): failed to open stream: Permission denied
Ugy Astro
  • 111

2 Answers2

1

After trying several times, and also reading a number of related articles. Finally, I understand, the problem is in the arrangement that I did. Hopefully this can help other users who are new about sudo n visudo.

Problems:

1. Username

About username, the user I added is a user who has login access through the terminal. Even though the application is accessed through the website. So the user should be www-data, looks like:

www-data ALL=(root) NOPASSWD: /usr/bin/php /var/www/html/myprogram/writefile.php

2. Not use exec or shell_exec

I forget that writefile.php should not be directly accessed through the browser. Having to go through another file ( index.php ) and then in the file must use shell_exec or exec to execute writefile.php with the sudo command. The structure looks like:

index.php

<?php
exec("sudo /usr/bin/php /var/www/html/myprogram/writefile.php");
?>

writefile.php

<?php
echo file_put_contents("tes.txt","tes write file");
?>

Finally open tes.txt and works fine! Thanks for all.

Ugy Astro
  • 111
0

This looks like a misunderstanding of how sudo works. Just putting something in the sudoers file will not cause permissions for files to actually change, the file to be must be run like: sudo php /var/www/html/myprogram/writefile.php by the "username".. You might also be encountering SELinux issues as running from a file from that location might be disallowed depending on its setting.

mdpc
  • 6,834