0

Below is the example, I was trying to execute the command using PHP function.

Not getting any error or not happen anything after execute this code.

$siteConfig = <<<EOL
server {
    listen 80;
    server_name test.local;
    root /var/www/html/test.local;
    index index.php index.html index.htm;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }

    error_log /var/log/nginx/test.local_error.log;
    access_log /var/log/nginx/test.local_access.log;
}
EOL;

$filePath = '/etc/nginx/sites-available/test.local';

shell_exec("echo Test@123 | sudo -S echo '$siteConfig' && sudo tee $filePath");

shell_exec('"echo Test@123 | sudo systemctl restart nginx');

3
  • Why would you want to do this? Can you give us come context? You cannot use sudo in non-interactive scripts unless you set it up to work without a password which is a very, very bad idea. Such things are usually done by running the script itself with sudo but that can also be dangerous. So if you explain what your final goal is (do you want a webpage with a button that does things? Will you be running this manually? Something else?) we can try and give you a good solution.
    – terdon
    Commented Jan 9 at 14:05
  • Sure @terdon, so I want to create dynamic file for host in sites-available folder. I can't access that folder without sudo, so as a programatilcally I want to access and create file and put host related content as you see in above example. Do you have any other approch for that? let me know Thanks Commented Jan 10 at 5:17
  • Please edit to clarify instead of putting it a comment because comments are easy to miss and can be deleted without warning. We need to know how this will be used, who will be running it. Is it random users on a website? Is it only the root user of the local machine? Are you running this from the command line? Is it going to be linked to a button on a website that users can click? Can't you just run the script itself with sudo?
    – terdon
    Commented Jan 10 at 11:13

0

You must log in to answer this question.

Browse other questions tagged .