Warning Using sudo
in a php script is a terrible idea, as it has huge security implications.
1. Clean and secure solution
i need to change the ownership of the file so that mp4box can write files to that directory
Let's say your directory is /srv/directory. You need to create a group that contains the www-data
user and any user that will write to the directory (let's say there is only one user: tony
).
groupadd mygroup
usermod -a -G mygroup www-data,tony
then change the directory ownership and permissions accordingly.
chown -R /srv/directory www-data:mygroup
chmod -R /srv/directory 770
but that is configuration/installation part and such command should not be run at runtime as it might require root access. It would allow any php script to do anything on the computer. this should be run when you install and configure the environement your script will run on.
not dev-ops note :
@my sysadmin: if you read this, please don't kill me.
You shouldn't care about user permissions at runtime as it is sysadmin's job to make the system secure and ensure your code can run on it. Because you don't care about that, there should not be any sudo in your code.
However, there is not a single sysadmin on earth that would grant root access to the www-data
user (maybe there are, but they get fired quickly).
more dev-ops note :
If you are a kind person that don't want to be hated by his co-workers and/or user. You should :
- document the needs of write access to directory X or Y.
- Maybe create an install script that will do the configuration job as root just once.
- Or maybe create a Docker container, or a virtual machine that is preconfigured to run your code.
2. tldr; I-don't-care-about-security solution
take a look at this unix stack exchange post