Laravel 5.2 - How to run shell command via Modal / Controller

Viewed 3997

How i can run shell command via a Model or Controller. Not through Artisan command or $schedule.

And also how i can run a sudo command?

I have try the next options. Nothing works:

1:

$process = new Process('sudo /usr/bin/touch /var/www/html/Poptin test2.html');
                $process->run();
                // executes after the command finishes
                if (!$process->isSuccessful()) {
                    throw new ProcessFailedException($process);
                }

2:

shell_exec(escapeshellcmd('sudo /usr/bin/touch /var/www/html/Poptin test2.html));

3:

exec('sudo /usr/bin/touch /var/www/html/Poptin test2.html);

Help please!

2 Answers

Have just tested running exec in Laravel 5.5 and it works. This is what i tried:

$test = exec('echo 123');
dd($test);

I know you are running 5.2, but it should be no different i terms of running this.

I can see that you have forgot an ending ' in the exec method and also the shell_exec.

Instead of writing

exec('sudo /usr/bin/touch /var/www/html/Poptin test2.html);

You should write

exec('sudo /usr/bin/touch /var/www/html/Poptin test2.html');

Also make sure that the command you are trying to run works when running it in the shell directly.

what you have done is correct but you have to do it like this for example shell_exec('sudo /usr/bin/touch /var/www/html/Poptin test2.html') give a try and one more thing using of shell_exec in controller is a bad practice.

Related