Sudo在exec函数中

I have the following folder on my server, with the following files:

error-2015-12-20.log
error-2015-12-21.log
error-2015-12-22.log

And I written a PHP script that packs into .tar.gz with names earlier than the current date, moves the packed file into another partition, and removes the input files. It's done via exec().

The problem is that all of those operations require me to use sudo and provide password.

How can I deal with this?

Are you familiar with Linux file permissions? If you want to execute a script you have to have the right to do so (by being in the group/owner with executable bit set), and if you want to read files you also have to have the right to read those files. Otherwise you are forced to execute the file as sudo, because root can access all files.

Learn about this here: https://www.linux.com/learn/tutorials/309527-understanding-linux-file-permissions

As stated above it's a permission problem, to solve this let instruct sudo to let your php script run without prompting for a password:

  1. Create a custom sudoers file :

    sudo visudo -f /etc/sudoers.d/90_your_user
    
  2. Copy the following contents in the newly created file (customizing the relevant section):

    Cmnd_Alias PHP_SCRIPT = /path/to/my/script.php param1 param2
    Cmnd_Alias ROOT_PROGS = PHP_SCRIPT
    
    # Programs allowed to run without password prompt of your_user
    your_user HOST=(root) NOPASSWD:ROOT_PROGS
    

You can then execute your program with sudo /path/to/my/myscript.php without permissions problem and without sudo prompts you for your password.