How to execute external shell commands from laravel controller? - php

I need to execute shell commands from controller , but not only for files inside the project , ex. system('rm /var/www/html/test.html') or system('sudo unzip /var/www/html/test.zip');
I call the function but nothing happen , any idea how to execute external shell commands from controller like removing one file in another directory?
system('rm /var/www/html/test.html');
//or
exec('rm /var/www/html/test.html')

If you're wanting to run commands from your PHP application I would recommend using the Symfony Process Component:
Run composer require symfony/process
Import the class in to your file with use Symfony\Component\Process\Process;
Execute your command:
$process = new Process(['rm', '/var/www/html/test.html']);
$process->run();
If you're using Laravel, you should be able to skip Step 1.
Alternatively, (if the process running php has the correct permissions) you could simply use PHP's unlink() function to delete the file:
unlink('/var/www/html/test.html');

I would do this with what the framework already provide:
1) First generate a command class:
php artisan make:command TestClean
This will generate a command class in App\Console\Commands
Then inside the handle method of that command class write:
#unlink('/var/www/html/test.html');
Give your command a name and description and run:
php artisan list
Just to confirm your command is listed.
2) In your controller import Artisan facade.
use Artisan;
3) In your controller then write the following:
Artisan::call('test:clean');
Please refer to the docs for further uses:
https://laravel.com/docs/5.7/artisan#generating-commands

Use fromShellCommandline to use direct shell command:
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
Process::fromShellCommandline('rm /var/www/html/test.html');
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();

Related

Run php script in command in symfony

I want to run php script in command line. I have created this file into root folder. and want to run only once.
binary.php
global $em;
$binaryContentRepository = $em->getRepository('\xxx\Entity\xxxx');
$datas = $binaryContentRepository->getAllAttechment();
foreach($datas as $data){
$ext = pathinfo($data['filename'], PATHINFO_EXTENSION);
file_put_contents("C:\\xxxxxx\\".$data['id'].".".$ext, $data['content']);
}
I have try to run this file php -f binary.php. But can not run successfully.
To run Symfony is the command line you need to create a Symfony command.
Note: just like a controller in a command you must have your dependency injection setup if you want to communicate to a database with entity manager.
https://symfony.com/doc/current/console.html
Then you would execute from the Symfony project root:
php bin/console your_command_name

Get all Laravel artisan commands for interface

When you use php artisan in the command line you get a list of all commands. Are there any opportunity to get all Laravel artisan commands programmatically? I need it for example to use it in a select field in the interface.
To get all command objects:
\Artisan::all()
To get all command names:
array_keys(\Artisan::all())
use Illuminate\Contracts\Console\Kernel;
...
$commands = resolve(Kernel::class)->all();
Use shell-exec command.
http://php.net/manual/en/function.shell-exec.php
$output = shell_exec('php artisan');
echo $output;
if I understand the query correctly, you can use CLI (eg bash in debian) to:
&& for individual calls - each subsequent call will be made after the previous performance, eg:
php artisan migrate:fresh && php artisan fixtures:up && php artisan db:seed && php artisan serv
aliases entered in .bash_profile
alias migrate = "php artisan migrate"
and using command migrate in Laravel project.
info: https://gist.github.com/JeffreyWay/5542264
You can put them in your routes like this:
Route::get('/foo', function()
{
$exitCode = Artisan::call('command:name', ['--option' => 'foo']);
//
});
https://laravel.com/docs/5.0/artisan#calling-commands-outside-of-cli

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

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!
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.

How to run yii2 cronjob from linux

I created a cronjob controller in yii2project/console/controllers :
namespace console\controllers;
use yii\base\Model;
use yii\console\Controller;
use Yii;
class MycronController extends Controller {
public function actionIndex() {
echo "cron service runnning";
die;
}
}
In windows i am running this file :
D:\xampp\htdocs\yii2project>d:\xampp\php\php yii mycron
output:
cron service running
Now how to run this in linux?
None of the solutions worked for me, atleast. To make it work from crontab, you have to provide the following command:
* * * * * php /path/to/project/root/yii controller-name/action-name
This example will run every minute by the way. For more information about cronjobs, check this link out.
By the way, if you just want to run the job from your SSH terminal, use this one instead:
php /path/to/project/root/yii controller-name/action-name
Edit: Make sure you have run init command after installing yii with composer. That sets the necessary permissions to run the yii script. If you still can't run it, try chmod +x yii to make the script executable.
Do this:
(take the $ symbol off)
$ /xampp/php/php/./yii mycron
php yii mycron
run in yii2project folder
The Cron-Job is for CentOs.
Open the terminal and navigate to your project folder
cd /var/www/html/advancedyii2
After entering into the folder type
crontab -e
The cron-manager file will be opened in the terminal.
Now edit the cron file like
* * * * * php /var/www/html/advancedyii2/yii controller/function
Before executing the above command make sure a controller is created under
/var/www/html/advancedyii2/console
- Here create a controller and function to server your need
For more about Cron-Configurations Visit this link

Execute Laravel/Symfony/Artisan Command in Background

I need to execute a Laravel long running process in the background for consuming the Twitter Streaming API. Effectively the php artisan CLI command I need to run is
nohup php artisan startStreaming > /dev/null 2>&1 &
If I run that myself in the command line it works perfectly.
The idea is that I can click a button on the website which kicks off the stream by executing the long running artisan command which starts streaming (needs to run in the background because the Twitter Streaming connection is never ending). Going via the command line works fine.
Calling the command programatically however doesn't work. I've tried calling it silently via callSilent() from another command as well as trying to use Symfony\Component\Process\Process to run the artisan command or run a shell script which runs the above command but I can't figure it out.
Update
If I queue the command which opens the stream connection, it results in a Process Timeout for the queue worker
I effectively need a way to run the above command from a PHP class/script but where the PHP script does not wait for the completion/output of that command.
Help much appreciated
The Symfony Process Component by default will execute the supplied command within the current working directory, getcwd().
The value returned by getcwd() will not be the Laravel install directory (the directory that contains artisan), so the command will most likely returning a artisan: command not found message.
It isn't mentioned in the Process Component documentation but if you take a look at the class file, we can see that the construct allows us to provide a directory as the second parameter.
public function __construct(
$commandline,
$cwd = null,
array $env = null,
$input = null,
$timeout = 60, array
$options = array())
You could execute your desired command asynchronously by supplying the second parameter when you initialise the class:
use Symfony\Component\Process\Process;
$process = new Process('php artisan startStreaming > /dev/null 2>&1 &', 'path/to/artisan');
$process->start();
I had a same problem and I solved this with pure php and use proc_open function.
My code :
$descriptionProcOpen = [
["pipe", "r"],
["pipe", "r"],
["pipe", "r"]
];
proc_open("php " . base_path() . "/artisan your:command {$argument}", $descriptionProcOpen, $pipes);
How about queuing the execution of the command via Laravels build-in queues?
$this->callSilently('mail:send', [
'user' => 1, '--queue' => 'default'
]);
https://laravel.com/docs/9.x/artisan#calling-commands-from-other-commands

Categories