Run php script in command in symfony - php

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

Related

error in Run PHP code with command line linux

My system is :
Ubuntu 20.04
Php 7.4
Nginx
I have a php file with following content in /var/www/hamrah.com/create.php path :
<?php
$output = shell_exec('bash flutter create test');
echo "<pre>$output</pre>";
i run this command in terminal and And this command executes correctly (creates a flutter project for me)
cd /var/www/hamrah.com && php /var/www/hamrah.com/create.php
BUT !
But when I put this command in Crontab, the command is not executed properly and gives an error
In Crontab :
* * * * * cd /var/www/hamrah.com && php /var/www/hamrah.com/create.php
Note: If I put shell_exec(' bash ls') instead of shell_exec('bash flutter creat test') in the php file, it will run well and some commands like the flutter create command will not be executed.
error : bash: flutter: No such file or directory
You can test
<?php
$output = shell_exec('bash /opt/flutter/bin/flutter create test');
echo "<pre>$output</pre>";
Cron doesn't read user's environment variables, the default value of PATH is /usr/bin:/bin, usually your flutter SDK won't be located in these 2 folders, so you need explictly specify the location of the flutter SDK. Add this line to the crontab.
PATH=/usr/bin:/bin:/path-to-flutter-sdk-bin
Use the following command if you don't know where flutter is.
which flutter

Exec shell command in symfony "No such file or directory"?

Using:
Laravel 8
PHP 8.0 (homebrew)
Problem:
Running any shell commands using Symfony: Symfony\Component\Process\Process
The following code executes on php7.4, but not on php8.0, both within Laravel 8
$newDir = storage_path('test');
$process1 = new Process(["mkdir ". $newDir]);
$process1->run();
if (! $process1->isSuccessful()) {
throw new ProcessFailedException($process1);
}
The result on PHP 7.4 is that the test directory is created within Laravels storage directory.
The result on PHP 8.0 is that the exception ProcessFailedException is triggered, with the result.
Error Output:
================
sh: /Users/username/code/project-name/mkdir /Users/username/code/project-name/storage/test: No such file or directory
sh: line 0: exec: /Users/username/code/project-name/mkdir /Users/username/code/project-name/storage/test: cannot execute: No such file or directory
I have attempted to use other commands and all give the same result
cannot execute: No such file or directory
My suspicion is that it may be permissions related, but all related processes can be seen running as the user executing the process. What am i missing?
Use a full path i.e. /bin/mkdir and separate the arguments instead of mkdir plus string concatenation.
$process1 = new Process(["/bin/mkdir", "-p", $newDir]);
The Process component can't find an executable with name mkdir [arguments] in your current working directory.

How to execute external shell commands from laravel controller?

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();

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