So, I have storage files saved and can access them like this:
$file = Storage::disk('public')->url("featured/{$i->image}")
That nets me the full url of the file I have in my storage/ directory. How can I make it so that can copy and paste that same exact file into a new directory but with a new file name?
I have tried:
$url = Storage::disk('public')->url("featured/{$i->image}");
$fileName = 'u_' . (new \DateTime())->getTimestamp() . '.png';
$fileDestination = '/new_folder/' . $fileName;
$i->image = $fileDestination;
File::copy($url, $fileDestination);
I am getting PHP execution timeout errors. I don't think I am referencing the paths correctly.
I want to copy /storage/app/public/featured/imageOne.png to /storage/app/public/new_folder/imageOneWITHNEWFILENAME.png
Is there a Storage facade solution?
Use Storage facade instead of File::copy to copy file to the new destination like
Storage::disk('public')->copy("featured/{$i->image}", $fileDestination);
Reference: Laravel 5.5 file storage
Related
I am having a problem with move_uploaded_file().
I am trying to upload a image path to a database, which is working perfectly and everything is being uploaded and stored into the database correctly.
However, for some reason the move_uploaded_file is not working at all, it does not produce the file in the directory where I want it to, in fact it doesn't produce any file at all.
The file uploaded in the form has a name of leftfileToUpload and this is the current code I am using.
$filetemp = $_FILES['leftfileToUpload']['tmp_name'];
$filename = $_FILES['leftfileToUpload']['name'];
$filetype = $_FILES['leftfileToUpload']['type'];
$filepath = "business-ads/".$filename;
This is the code for moving the uploaded file.
move_uploaded_file($filetemp, $filepath);
Thanks in advance
Try this
$target_dir = "business-ads/";
$filepath = $target_dir . basename($_FILES["leftfileToUpload"]["name"]);
move_uploaded_file($_FILES["leftfileToUpload"]["tmp_name"], $filepath)
Reference - click here
Try using the real path to the directory you wish to upload to.
For instance "/var/www/html/website/business-ads/".$filename
Also make sure the web server has write access to the folder.
You need to check following details :
1) Check your directory "business-ads" exist or not.
2) Check your directory "business-ads" has permission to write files.
You need to give permission to write in that folder.
make sure that your given path is correct in respect to your current file path.
you may use.
if (is_dir("business-ads"))
{
move_uploaded_file($filetemp, $filepath);
} else {
die('directory not found.');
}
I have a form with a file to uplaod. All works find. But I don't want to move the file directly into a folder.
After submit I show a confirm page and there I show the uploaded file with
header('Content-Type: image/x-png');
$file = file_get_contents(\Illuminate\Support\Facades\Input::file('restImg'));
$imgType = \Illuminate\Support\Facades\Input::file('restImg')->guessClientExtension();
echo sprintf('<img src="data:image/png;base64,%s" style="max-height: 200px"/>', base64_encode($file));
This works fine. After the confirmation I like to move the file to a folder. How can I move the file after the confirmation? The Input::get('file') is not available anymore.
You will have to store the file in the initial upload somewhere temporarily other than the default tmp directory.
The documentation for PHP file uploads says:
The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed
This means that moving onto the next request, the file will no longer be available.
Instead, move it to your own custom temp directory or rename it to something special, then keep the filename in the $_SESSION to persist it to the next request.
For Laravel, this should mean putting it in the /storage directory with something like this:
// Get the uploaded file
$file = app('request')->file('myfile');
// Build the new destination
$destination = storage_path() . DIRECTORY_SEPARATOR . 'myfolder';
// Make a semi-random file name to try to avoid conflicts (you can tweak this)
$extension = $file->getClientOriginalExtension();
$newFilename = md5($file->getClientOriginalName() . microtime()).'.'.$extension;
// Move the tmp file to new destination
app('request')->file('myfile')->move($destination, $newFilename);
// Remember the last uploaded file path at new destination
app('session')->put('uploaded_file', $destination.DIRECTORY_SEPARATOR.$newFilename);
Just remember to unlink() the file after the second request or do something else with it, or that folder will fill up fast.
Additional Reference:
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/File/UploadedFile.html
Im trying to save a manipulated image which i will them push to s3.
My code that works This code saves the image directly within the public folder*
public function store(Filesystem $filesystem)
{
$request = Input::all();
$validator = Validator::make($request, [
'images' => 'image'
]);
if ($validator->fails()) {
return response()->json(['upload' => 'false']);
}
$postId = $request['id'];
$files = $request['file'];
$media = [];
$watermark = Image::make(public_path('img/watermark.png'));
foreach($files as $file) {
$image = Image::make($file->getRealPath());
$image->crop(730, 547);
$image->insert($watermark, 'center');
$image->save($file->getClientOriginalName());
}
}
What i would like to achieve is to be able to save it within a folder of it's own. Firstly what is the best place to store an image for a blog post, within the storage of public folder? But anyway when i do this:
$image->save('blogpost/' . $postId . '/' . $file->getClientOriginalName());
// Or this
$image->save(storage_path('app/blogpost/' . $postId . '/' . $file->getClientOriginalName()));
I get the error:
folder within public
NotWritableException in Image.php line 138: Can't write image data to
path (blogpost/146/cars/image.jpg)
or
storage path
NotWritableException in Image.php line 138: Can't write image data to
path /code/websites/blog/storage/app/blogpost/146/image.jpg
I've tried
cd storage/app/
chmod -R 755 blogpost
And it still wont work
Thank you for reading this
Ok so here is how i solved it, I made the directory first before storing,
Storage::disk('local')->makeDirectory('blogpost/' . $postId);
Once the folder is created i then go on to store the manipulated images like so:
$image->save(storage_path('app/blogpost/' . $postId . '/' . $imageName));
And then pushing the image to S3
$filesystem->put('blogpost/' . $postId . '/' . $imageName, file_get_contents(storage_path('app/blogpost/' . $postId . '/' . $imageName)));
This worked
You can solve it by casting the Intervation/Image variable to a data stream using function stream. Then use the Storage Laravel facade to save the image.
$img = Image::make('path-to-the-image.png')->crop(...)->insert->stream('jpg', 90)
Storage::put('where_I_want_the_image_to_be_stored.jpg', $img);
Laravel 5 needs permission to write to entire Storage folder so try following,
sudo chmod 755 -R storage
if 755 dont work try 777.
Am improving #Amol Bansode answer.
You are getting this error because $postId folder does not exist in the path you specified.
You could do it like this:
//I suggest you store blog images in public folder
//I assume you have created this folder `public\blogpost`
$path = public_path("blogpost/{$postId}");
//Lets create path for post_id if it doesn't exist yet e.g `public\blogpost\23`
if(!File::exists($path)) File::makeDirectory($path, 775);
//Lets save the image
$image->save($path . '/' . $file->getClientOriginalName());
In my case I migrated a project from Windows 10 to Parrot (Debian-Linux) and I had the same problem and turned out the slashes were backward slashes and Linux interpret them differently. Unlike Windows, it doesn't really matter.
//Windows Code:
$image_resize->save(public_path('\storage\Features/' .'Name'.".".'png'));
//Linux Code (Working):
$image_resize->save(public_path('storage/Features/' .'Name'.".".'jpg'));
I know the question is related to Laravel but I came across from making it to work with WordPress. If somebody is coming from WordPress world, this code works (I was getting the same 'cannot write' error) and changing directory permission would not work as the library probably needs the relative path (the code below is valid for direct installation of Intervention through composer into any PHP application, not Laravel per se)-
require 'vendor/autoload.php';
use Intervention\Image\ImageManager;
$manager = new ImageManager(array('driver' => 'imagick'));
$image = $manager->make('PUBLIC IMAGE URL/LOCAL IMAGE PATH');
$image->crop(20, 20, 40, 40);
$image->save(__DIR__ . '/img/bar.png');
in my case:
i double check my symlinks in filesystem.php in config folder in laravel
and remove all symlink then regenerate them
php artisan storage:link
in my case my fileName is not valid format for naming in windows but it worked on linux or docker
$make_name = date('Y-m-d-H:i:s') . hexdec(uniqid()) . '.' . $img->getClientOriginalExtension();
when I remove this date('Y-m-d-H:i:s') it worked as well
I have faced the same issue but 775 permission not sort it so I changed the write permission to the folder(also sub-folders) to 777 to get over this issue.
I am trying get all images which are located in standard cakePHP image folder. I am using:
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
$dir = new Folder('/app/webroot/img/');
$files = $dir->find('.*\.png');
pr($files);
but i always get empty array. Where is the problem?
Ina addition when I try make dir in that folder i get error:
mkdir(): No such file or directory [CORE\Cake\Utility\Folder.php, line 515]
By doing new Folder('/app/webroot/img/'); you're actually saying your app folder is in the root of the drive, and since it isn't, CakePHP will try and create it, which it can't (that mkdir error).
You probably need to do something like
$dir = new Folder(App.imageBaseUrl);
or
$dir = new Folder(APP_DIR . DS . "webroot" . DS . "img");.
Check the constants CakePHP gives you to handle paths http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#core-definition-constants should be usefull
Knowing the answer is given and accepted,
This is a right way given by the documents.
<?php
// Find all .png in your app/webroot/img/ folder and sort the results
$dir = new Folder(WWW_ROOT . 'img');
$files = $dir->find('.*\.png', true);
http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::find
I am looking to save an xml file to a different directory from the root using php5. any ideas?
//write to the file
$filename = $id . ".xml";
$doc->save($filename);
I want to save the file to the /xml/ directory.
Change the argument to $doc->save to include the path
$filename = '/xml/' . $id . ".xml";
$doc->save($filename);
Now the thing to bear in mind is that this is a filesystem path, not web URL so its literally going to save in /xml not DOCUMENT_ROOT/xml.