So I made a custom artisan command that will dump an sql file from my database.
Here's what is inside the command.
I named it db:dump with this syntax:
protected $signature = 'db:dump';
Next is the command itself:
public function handle()
{
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$ts = time();
$path = database_path() . $ds . 'backups' . $ds . date('Y', $ts) . $ds . date('m', $ts) . $ds . date('d', $ts) . $ds;
$file = date('Y-m-d-His', $ts) . '-dump-' . $database . '.sql';
$command = sprintf('mysqldump -h %s -u %s -p\'%s\' %s > %s', $host, $username, $password, $database, $path . $file);
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
exec($command);
}
So all of the info needed are inside my .env file. If it would help, I'll also provide what's inside it:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:3WuXKyS70VX+V/Ic5QjuVcmFbzsqTkJehiQA7q9s9gk=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_salesandinventory
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
With that info, everything's ready and hopefully it could have worked.
But whenever I execute the command in my command prompt:
php artisan db:dump
It always says "Access is denied."
I lost any lead here, I don't know what could be the problem.
EDIT: When I replace the command with just $this->info('TEST'); it will work. It's like a console.log command or some sort. What I wanted to say is that there's something wrong in my command that restricts me from doing it.
From the comments, you describe that the command your script is generating and trying to execute is (as seen when you dd($command) instead of trying to exec($command)):
mysqldump -h 127.0.0.1 -u root -p'' db_salesandinventory > <output-file>
where <output-file> is in your home directory so presumably writable. You also mentioned that running that command manually fails with the same permissions error. So the problem has nothing to do with Laravel, but your access to your MySQL server.
First of all test if your username and password are correct. Try, on your console:
mysql -u root -p db_salesandinventory
(without -h). You will be prompted for a password, enter the one you are using in your script. If it does not work, you are using the wrong u/p, fix those and try your script again.
If it does work, it means your root user is not allowed to connect to 127.0.0.1. For MySQL, localhost is not the same as 127.0.0.1, and you'll need to enable access for your root user using that IP, as described in this question.
I managed to find the problem and did some alternative ways to prevent it.
Unfortunately, I cannot access my C:\Users\PCNAME\ and my project is saved there. I'm trying to dump the database inside the project path but it can't be accessed.
So as an alternative, I changed the path of where it will be dumped, I set it to C:\salesandinventory\backups\
Here's the whole code:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MySqlDump extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'db:dump';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Runs the mysqldump utility using info from .env';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$ds = DIRECTORY_SEPARATOR;
$host = env('DB_HOST');
$username = env('DB_USERNAME');
$password = env('DB_PASSWORD');
$database = env('DB_DATABASE');
$mysqlpath = 'C:\xampp\mysql\bin\mysqldump';
$ts = time();
// $path = 'database' . $ds . 'backups' . $ds . date('Y', $ts) . $ds . date('m', $ts) . $ds . date('d', $ts) . $ds;
$path = 'C:\salesandinventory\Backups' . $ds . date('Y', $ts) . $ds . date('m', $ts) . $ds . date('d', $ts) . $ds;
$file = date('Y-m-d-His', $ts) . '-dump-' . $database . '.sql';
$command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' > ' . $path . $file);
if (!is_dir($path))
{
mkdir($path, 0755, true);
}
exec($command);
}
}
The bottomline is, there's a problem with my folders with it being not accessible. I still don't know why, I tried opening command promt as an Administrator. But it still doesn't work.
Related
I am trying to upload an image in Laravel. Getting the following error:
"message": "Could not move the file \"C:\\xampp\\tmp\\php84AA.tmp\" to \"F:\\bvend\\bvend-web\\public\\uploads/products\\bvend-product-1666274539.jpg\" (move_uploaded_file(): Unable to move "C:\\xampp\\tmp\\php84AA.tmp" to "F:\\bvend\\bvend-web\\public\\uploads/products\\bvend-product-1666274539.jpg").",
"exception": "Symfony\\Component\\HttpFoundation\\File\\Exception\\FileException",
"file": "F:\\bvend\\bvend-web\\vendor\\symfony\\http-foundation\\File\\UploadedFile.php",
"line": 177,
"trace": [ .... ]
My code is given below:
public function uploadImage($image, $image_path)
{
$path = config('global.' . $image_path . '_image_path');
file_exists($image) && unlink($image);
$image_name = 'bvend-' . $image_path . '-' . time() . '.' . $image->getClientOriginalExtension();
$image->move($path, $image_name); // $path: public_path('uploads/products')
return $image_name;
}
I understand its a simple issue but still no clue where it causing issue.
Edit
#WahidulAlam Please, try removing file_exists($image) && unlink($image);
– steven7mwesigwa - https://stackoverflow.com/posts/comments/130904221?noredirect=1
#WahidulAlam You're essentially deleting the temporary file/image before its copied or moved.
– steven7mwesigwa - https://stackoverflow.com/posts/comments/130904261?noredirect=1
ah this is the catch !! thanks a lot.
– Wahidul Alam - https://stackoverflow.com/posts/comments/130904399?noredirect=1
Specifying A File Name
If you do not want a filename to be automatically assigned to your
stored file, you may use the storeAs method, which receives the
path, the filename, and the (optional) disk as its arguments:
$path = $request->file('avatar')->storeAs(
'avatars', $request->user()->id
);
You may also use the putFileAs method on the Storage facade, which
will perform the same file storage operation as the example above:
$path = Storage::putFileAs(
'avatars', $request->file('avatar'), $request->user()->id
);
Solution
public function uploadImage(\Illuminate\Http\UploadedFile $image, $image_path)
{
return $image->storePubliclyAs(
config('global.' . $image_path . '_image_path'),
'bvend-' . $image_path . '-' . time(),
["disk" => "public"]
);
}
Addendum
Don't forget to create a symbolic link from public/storage to storage/app/public. I.e:
php artisan storage:link.
The Public Disk
Once a file has been stored and the symbolic link has been created,
you can create a URL to the files using the asset helper:
echo asset('storage/file.txt');
In Summary
$savedPath = $request->file("***REQUEST-INPUT-IMAGE-NAME-HERE***")->storePubliclyAs(
"***IMAGE-PATH-HERE***",
"***CUSTOM-FILENAME-HERE***",
["disk" => "public"]
);
I am using this methodology in Laravel 9.
try this:
public function uploadImage($image, $image_path)
{
// $path = config('global.' . $image_path . '_image_path');
file_exists($image) && unlink($image);
$image_name = 'bvend-' . $image_path . '-' . time() . '.' . $image->getClientOriginalExtension();
//$image->move($path, $image_name); // $path: public_path('uploads/products')
$image->move(public_path('/images'), $image_name);
return $image_name;
}
I want to store an uploaded file with its original client name in the storage folder. What do I need to add or change in my code?Any help or recommendation will be greatly appreciated
Here my Controller
public function store(Request $request) {
$path = "dev/table/".$input['id']."";
$originalName = $request->file->getClientOriginalName();
$file = $request->file;
Storage::disk('local')->put($path . '/' . $originalName, $request->file);
}
Edit: I know how to get the originalClientName. the problem is storing the file in the folder using the original name, not the hash name. It doesn't store in the file in the original it makes a new folder instead here is the output "dev/table/101/Capture1.PNG/xtZ9iFoJMoLrLaPDDPvc4DMJEXkRL3R4qWOionMC.png" what I trying to get is "dev/table/101/Capture1.PNG"
I have tried to use StoreAs Or putFileAs but the method is undefined
I managed to figure out how to store it with a custom name, for those who want to know how to do it here is the code
$id = $input['id'];
$originalName = $request->file->getClientOriginalName();
$path = "dev/table/$id/".$originalName;
Storage::disk('local')->put($path, file_get_contents($request->file));
public function store(Request $request) {
$originalName = $request->file->getClientOriginalName();
$extension = $request->file->getClientOriginalExtension();
$path = "dev/table/" . $input['id'] . "/" . $originalName . "." . $extension;
$file = $request->file;
Storage::disk('local')->put($path, $file);
}
To get the original file name you can use this in your ControllerClass:
$file = $request->file->getClientOriginalName();
To get additional the extension you can use this Laravel Request Method:
$ext = $request->file->getClientOriginalExtension();
Then you can save with:
$fileName = $file.'.'.$ext;
$request->file->storeAs($path, $fileName);
// or
Storage::disk('local')->put($path . '/' . $fileName , $request->file);
You can save files using storage with the default name using putFileAs function instead of put which allow take third param as a file name
$path = "dev/table/101/";
$originalName = request()->file->getClientOriginalName();
$image = request()->file;
Storage::disk('local')->putFileAs($path, $image, $originalName);
Update
You can do something like this with put,
Storage::disk('local')->put($path.$originalName, file_get_contents($image));
I tried to manage like this;
$insurance = $request->file('insurance_papers');
$insuranceExtention = $insurance->getClientOriginalExtension();
$path = "public/files/" . $carrier->id . "/insurance_papers." . $insuranceExtention;
Storage::disk('local')->put($path, file_get_contents($insurance));
You can try this, this is work for me
if ($request->hasFile('attachment')) {
$image = $request->file('attachment');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$path = "foldername/".$imageName;
Storage::disk('public')->put($path, file_get_contents($image));
}
I wrote function which changes values in config/app.php using file_put_content.
public function updateConfig($path, $key, $value)
{
$content = file_get_contents($path);
$pattern = "/'" . $key . "' => '[0-9]+'/";
$replacement = "'" . $key . "' => '" . $value . "'";
$content = preg_replace($pattern, $replacement, $content);
file_put_contents($path, $content);
}
$path = base_path() . '/config/app.php';
$key = 'version_number';
$value = '10';
$service->updateConfig($path, $key, $value);
$this->assertEquals(config('app.version_number'), $value);
How can I test it with changing config file?
I presume you want to change the config then use it.
There is a way you can achieve this without editing the config file. Note that, in order to speed up Laravel, configurations are cached and you need to run php artisan clear:cache or manually delete cache files.
If you want to change config on the fly. Change it as shown before using it.
Config::set('app.version_number', 10);
I'm trying to create multiple copies of profile pic in different sizes when a profile is created. But I am constantly getting this error:
" NotReadableException: Image source not readable"
Can somebody point me what I'm missing in my below code:
public function updateprofile(UserProfileRequest $request){
$user_id = Auth::User()->id;
$profile = UserProfile::where('user_id','=',$user_id)->first();
$profile->fullname = $request->fullname;
if ($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( '32', '64', '128');
$targetPath = 'public/uploads/'.$user_id;
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$original = $fName . array_shift($types) . $ext;
Storage::putFileAs($targetPath, $file, $original);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
Storage::copy($targetPath . $original, $targetPath . $newName);
$newImg = Image::make($targetPath . $newName);
$newImg->resize($sizes[$key], null, function($constraint){
$constraint->aspectRatio();
});
$newImg->save($targetPath . $newName);
}
$profile->img = 'public/uploads/'.$user_id;
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
$profile->save();}
I had the same issue i ran this command and it worked
php artisan storage:link
This command creates a storage directory under the public folder.
Also use public path function to get the public path
$targetPath = public_path('storage/uploads/'. $user_id);
The 'storage' used inside the laravel public_path() function is used to get the storage main folder.
If I'm not mistaken, the path which is provided should be the absolute filepath on your server. For example instead of:
$targetPath = 'public/uploads/'.$user_id;
Use (your actual path will vary depending on your configuration)
$targetPath = '/var/www/sitename/public/uploads/'.$user_id;
Laravel also contains a helper function called public_path() which can be used to obtain the "fully qualified path to the public directory". This would allow you to use something such as:
$targetPath = public_path('uploads/'. $user_id);
Also, on this line, do not forget to place a slash before the new filename:
$newImg = Image::make($targetPath . '/' . $newName);
I would also confirm that the user executing the script (if apache or nginx usually www-data unless altered) has write permissions to your public/uploads/ directory
Finally, I got it working. I made following changes to my code:
Use the full OS path as suggested by commanderZiltoid for the destination path.
Don't use Storage::putFileAs method to save the file. So, remove this line: Storage::putFileAs($targetPath, $file, $original);
Don't use Storage::copy() to copy the file, so, remove this line:
Storage::copy($targetPath . $original, $targetPath . $newName);
For points 2 and 3, use Image::make($file->getRealPath()); This will create the file and remember the path where the file was created. Image->resize method will use this path later.
In the end, save the relative path in the database, as here: $profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName. Since we'll use {{ asset($profile->img) }}, it's necessary to save only the relative path and not the absolute OS path.
if($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( array('32','32'), array('64','64'), array('128','128'));
$targetPath = '/Users/apple/Documents/_chayyo/chayyo/storage/app/public/uploads/'.$user_id.'/img/profile/';
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$o_name = $fName . array_shift($types) . $ext;
$original = Image::make($file->getRealPath());
$original->save($targetPath . $o_name);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
$newImg = Image::make($file->getRealPath());
$newImg->resize($sizes[$key][0], $sizes[$key][1]);
$newImg->save($targetPath . $newName);
}
$profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName;
}
catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
I scheduled a cronjob through Laravel console. It is working and giving the result in every minute. But I tried to write the output to a file using the sendOutputTo and appendOutputTo method. But this is not writing to the file. My file has write permission.
Below is my code:
Kernel.php
protected function schedule(Schedule $schedule) {
$filePath = base_path() . "\cron\CleanSession.txt";
$schedule->command('cleansession')
->everyMinute()
->sendOutputTo($filePath);
}
Session.php
public function handle() {
$this->info('Display this on the screen');
$onlineCodeObj = new OnlineCode();
if ($onlineCodeObj->cleanSession()) {
echo "SESSION CLEANED : echo" . "\n";
return "SESSION CLEANED: return" . "\n";
}
echo "SESSION CLEANED : echo2" . "\n";
return "SESSION CLEANED: return2" . "\n";
}
Solved the issue. Changed the path
$filePath = base_path() . "\cron\CleanSession.txt"; to $filePath = base_path() . "/cron/CleanSession.txt";