Laravel 8 Storage move file not found - php

I am trying to move a file from a temporary path to the correct path. However no matter what I tried it always sends back this file not found error:
League\Flysystem\FileNotFoundException
File not found at path: var/www/html/storage/app/public/covers/tmp/608c07a082451-1619789728/81-536x354.jpeg
I am using sail thus there are 'var/www/html/' in the path, even though there is no problem with this path in the container since it is possible to reach this path from the frontend fetch API and that is how the temp file was saved.
Here is the code in the controller:
//...
$temp_file = TempFile::where('folder', $cover_folder)->first();
if ($temp_file) {
// retrieve file path and target path
$filepath = storage_path("app/public/covers/tmp/{$temp_file->folder}/{$temp_file->filename}");
$target_path = storage_path("app/public/covers/{$course->id}/");
Storage::move($filepath, $target_path);
$course->cover_img = "{$target_path}/{$temp_file->filename}";
$course->save();
// remove temp directory and temp file record
rmdir(storage_path("app/public/covers/tmp/{$temp_file->folder}/"));
$temp_file->delete();
}
The error traceback highlighted on this line:
Storage::move($filepath, $target_path);
Also tried to use Storage::disk('public')->move(), or public_storage, or Storage::path(), or only pure string, all did not work.
Symlink is set from public/storage to storage by running php artisan storage:link.
I have searched as much as I could find on laracast, stack overflow, or github, but could not reach a solution. Does anyone have any idea on this issue?
Really really appreciate it.

dont use storage_path function because method Storage::move( have prefix path [app_path]/storage/app/
Storage::move("public/covers/tmp/{$temp_file->folder}/{$temp_file->filename}", "public/covers/{$course->id}/");

Related

Copy file from any given path in Laravel

I want to copy a file from outside the root directory of my Laravel application using an artisan command which i made myself. The user will call the command like so:
php artisan crawl:pdf {filepath}
Then the filepath will be processed and on this part:
File::copy($path, storage_path('pdfs') . '/' . $fileName . ".pdf");
it breaks every time i use a path outside of my root directory it says "Failed to open stream: No such file or directory" as error msg".
I've already googled about copying files in plain php using copy() and in Laravel using Storage::copy(). Also reading through articles that all describe creating a disk which can route outside of laravel-root-directory.
All of that is not the solution to my problem. The user should be able to use any path.
C:\dir1\pdf3.pdf ;
E:\dir456\pdf2222.pdf`
...
from his own filesystem to copy files to the laravel-application.
Is their a way todo it ? Thx for all the help in advance!
EDIT 1:
Before anyone asks if i have write and read permission: yes i do. if i use plain php i can write and read everywhere on my working drive. I also checked the user laravel is running on with echo whoami and it gives the same user as my plain php application which works fine.
EDIT 2:
Worked in comments regarding using File-Facad-copy
Ok i found a solution and now it is working as i want it.
But first why is this happening. Laravel is expecting to always work on files using disks. It is required.
the solution is On-demand Disks!!!
This way it is possible to take a path given by a user and create a temporary disk which only works in this instance through facades.
Important is to make sure that the path given is always a directory! Like so:
$diskpath = dirname($path);
$disk = Storage::build([
'driver' => 'local',
'root' => "$diskpath",
]);
In my case I only want to copy one specific file which makes it mandatory to get the file information for correct naming and copying. Like so:
$pathinf = pathinfo($path)
$fileName = time() . '_' . $pathinf['filename']
Next we need to safe it to the new location. Like so:
Storage::disk('pdfs')->putFileAs('/', $path, $fileName . ".pdf");
Notes:
'pdfs' disk is a disk i configured in my filesystems.php config-file
I always asume that the user is giving the full path from the file like C:\...\test.pdf or something similar so watch out for the dirname() function. It will always cut the last part of the path and delete it.
Thanks to apokryfos for helping solving this through his comments and hints.

How to unlink file from children dir of parent dir? PHP

I want to unlink an image file from children dir of a parent dir.
I developing this project in a director folder under my website (mysite/project) but when i complete the project i will move to another hosting package.
Whic code i need use for stable running in all directories?
I get this error:
Warning: unlink(../../images/urunler/deneme-urun.jpg): No such file or directory in /home/admin/public_html/eticaret/admin/includes/updateproduct.php on line 120
My folder structure:
click here to see my folder structure
$delete = unlink("../../images/products/".$img);
Before running unlink() command you can check the existence of the file to get rid of such error
$path = "../../images/products/".$img;
if (file_exists(path)) {
unlink($path)
}
Better is using the full directory path (absolute path). An example, let your project structure is
and your unlinking code is in script.php, then your can get full absolute path the following way
$path = __DIR__ . "/../../images/products/{$img}";
if (file_exists(path)) {
unlink($path)
}
Thanks for all answers.
I have a fault on this topic.
Image name is xxx.jpg in my database but xxx.jpeg in the folder.
but there is an interesting situation: if you have an image as .jpeg format, you can open on browser as .jpg format.
I've tried a lot of methods to solve the above error, but I've found that.
I using chrome browser now.
So i solved my problem yet :)
as the script is run from "public_html/eticaret/admin/includes/" you need to .. traverse back 3 directories to get to public_html which is a common ancestor folder for both image and script
according to your directory image your images are in public_html/myproject/images/products/ and according to error detailed in your comment you are trying to delete from images/urunler/ I assume urunler is the actual project name.
if the folder containg your images is urunler try $delete = unlink("../../../images/urunler/".$img);
if the container folder is products try $delete = unlink("../../../images/products/".$img);
if that fails try using an absolute path instead of a relative path.

Laravel Uploaded file path return error

i been following the upload method using this tutorial and i got some errors that i cant brain anymore.
Here are the example, i upload file name "fileNumber1.pdf", the laravel system will save the file using Storage facade.
$filePath[] = $fileData->storeAs('uploadedFile', $fileName);
So the original path will be "storage/app/uploadedFile/fileNumber1.pdf".
To view the file, the tutorial suggest that to use
echo asset('storage/file.txt');
So from my understanding the echo should be like
echo asset('storage/uploadedFile/fileNumber1.pdf');
Since i use local development the return is
http://localhost:8000/storage/uploadedFile/fileNumber1.pdf
Then i go to the link given, it return
Sorry, the page you are looking for could not be found.
So how is the proper way to receive or view the file?
This url http://localhost:8000/ points to pubilc folder
So store your file inside uploadedFile folder inside public folder then use like
http://localhost:8000/uploadedFile/fileNumber1.pdf
otherwise use storage_path('uploadedFile/fileNumber1.pdf'); instead asset('storage/uploadedFile/fileNumber1.pdf');
If you would have followed the tutorial link then you should have run the below command which creates a symlink, If you haven't, do run that artisan command in your application folder.
php artisan storage:link
So now the below commad will give you desired result.
{{ asset('storage/uploadedFile/fileNumber1.pdf') }}
or
{{ storage_path('uploadedFile/fileNumber1.pdf') }}
You don't have to point the complete path of your file because asset() will defaultly point you to public folder and then you have to add the required path of your file location.
sorry for all the rude if you receive.
The mistake is mine.
The solution was simple.
Original is
$filePath[] = $fileData->storeAs('uploadedFile', $fileName);
The solution is
$filePath[] = $fileData->storeAs('public/uploadedFile', $fileName);
Just add "public" before the file path before uploading.
Thanks all for the effort.

Laravel 5.2 File Upload

When I try and upload a file as follows:
$name = $img->getClientOriginalName();
$fullPath = Product::getUploadPath(); // Returns public_path(); with custom directory appended
$uploaded = $img->move($fullPath, $name);
I get the below error:
Could not move the file
"/private/var/folders/1l/fxl7spqj2p113fpffm3k0sy00000gn/T/phpIgpWGy" to
"/dir/subdir/subsubdir/subsubdir/public/backend/images/products/pic.jpg" ()
For interestsake, I built the entire resolve path for the image, and passed that as an argument to the move() method. Memory served that it has worked previously.
$uploaded = $img->move($fullPath.'/'.$name);
No exceptions are thrown, however, the uploaded file, now becomes a directory:
"/dir/subdir/subsubdir/subsubdir/public/backend/images/products/pic.jpg/"
I'm very close to driving my fist through my screen.
Could be a permissions issue - the user running the PHP process will need to have write access to the directory where the file will be saved. If you can stomach chmod'ing the directory to 777 for testing, that would at least provide an immediate yes or no to the permissions possibility.
Also, be sure that the directory that file is to be moved to exists - Symfony's UploadedFile::move() method falls back to PHP's move_uploaded_file() function, which according to a comment on the documentation will not create missing directories when moving a file.
When it comes to uploading files, we've all been there before. Can be maddening.

PHP Unlink Not working

I am trying to delete photo in php using unlink. I have used it earlier on other server but this time it is not working. I have used absolute path for a test but still does not works:
I have used it as:
unlink('img1.jpg');
and :
unlink('http://www.mysite.com/img1.jpg');
Please anyone having such experience?
url not allow in ulink function
can you please used this
It's better, also safety wise to use an absolute path. But you can get this path dynamically.
E.g. using:
getcwd();
Depending on where your PHP script is, your variable could look like this:
$deleteImage = getcwd() . 'img1.jpg';
unlink($deleteImage);
check this
bool unlink ( string $filename [, resource $context ] )
and
filename
Path to the file.
So it only takes a string as filename.
Make sure the file is reachable with the path from the location you execute the script. This is not a problem with absolute paths, but you might have one with relative paths.
Even though unlink() supports URLs (see here) now, http:// is not supported: http wrapper information
use a filesystem path to delete the file.
If you use unlink in a linux or unix you should also check the results of is_writable ( string $filename )
And if the function returns false, you should check the file permissions with fileperms ( string $filename ).
File permissions are usual problems on webspaces, e.g. if you upload an file per ftp with a ftp user, and the webserver is running as an different user.
If this is the problem, you have do to a
chmod o+rwd img1.jpg
or
chmod 777 img1.jpg
to grand write (and delete) permissions for other Users.
unlink($fileName); failed for me.
Then I tried using the realpath($fileName) function as unlink(realpath($fileName)); it worked.
Just posting it, in case if any one finds it useful.
php unlink
use filesystem path,
first define path like this:
define("WEB_ROOT",substr(dirname(__FILE__),0,strlen(dirname(__FILE__))-3));
and check file is exist or not,if exist then unlink the file.
$filename=WEB_ROOT."img1.jpg";
if(file_exists($filename))
{
$img=unlink(WEB_ROOT."img1.jpg");
}
unlink won't work with unlink('http://www.mysite.com/img1.jpg');
use instead
unlink($_SERVER['DOCUMENT_ROOT'].'img1.jpg');//takes the current directory
or,
unlink($_SERVER['DOCUMENT_ROOT'].'dir_name/img1.jpg');
There may be file permission issue.please check for this.
Give relative path from the folder where images are kept to the file where you are writing script.
If file structure is like:
-your php file
-images
-1.jpg
then
unlink(images/1.jpg);
Or there may be some folder permission issue. Your files are on a server or you are running it on localhost? If it is on a server then give 755 permission to the images folder.
you are using url insted of path, here is how you should do it...
i am assuming your are uploading the picture to public_html. i suggest you to create a folder for pictures.
unlink("public_html/img1.jpg");

Categories