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.
Related
hope you are doing really good today, I'm trying to copy a file using the function copy from Laravel Storage, but I don't know where it is saving them cause the first time looks normal but after the second shot I got an error about the file already exists, but I don't know where is saving it, this is my code, $dirDest should be a folder inside of my project but is not saving it there and I've already searched it in the ftp directory, hope you can help me.
$dirDest = 'temp-docs\temp.pdf';
Storage::disk('custom-ftp')->copy($this->document_path, $dirDest);```
Regards!
Check the path you have configured for your 'custom-ftp' in filesystems.php. This part:
'custom-ftp' => [
...
'root' => 'your/base/path',
...
],
You file copy will be located in this root folder + 'temp-docs\temp.pdf'
The copy function does not changes the driver. So it copies just inside of your ftp server.
To copy the file from one server to another (or your server) use a combination of get and put functions from the storage drivers.
$file = Storage::disk('my_ftp')->get($this->document_path);
Storage::disk('other_ftp')->put('temp-docs\temp.pdf', $file);
After that you will find the file of the other server root folder + 'temp-docs\temp.pdf'
I would also recommend you use the exists function to be sure that the file is there before you copy it.
Storage::disk('my_ftp')->exists($this->document_path)
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}/");
I've been using laravel for nearly all my projects and I've came across a problem when trying to list all files in a directory.
Here is my code below:
$directory = ("upload/"."$username->username");
$scanned_directory = storage::allfiles($directory);
So as you can see First line is the directory which is in Upload followed by the username of the account.
The second line is meant to scan this directory and list only files. Sadly it always gives me back an empty array. Using Scandir() here works... But it gives me folders which I'm not wanting.
So... Any tips? I checked the API and I really can't see what is wrong here :(
The reason you're getting no results when using the Storage::allFiles('directory') method is this method only looks inside of your application's storage folder, usually storage/app. Hence why modifying the storage path in configuration works as mentioned by #yassine (you shouldn't do this).
If you wish to use files outside of the storage folder, simply use the File facade instead. e.g. File::allFiles('directory')
Me too i had the same issue for local storage. I fixed it by :
project/config/filesystems.php
line 44
changed root folder to from storage_path('app') to changed to
base_path()
then I provided a related path to the root folder in Storage::files() or Storage::allfiles().
Like Storage::allfiles("app") if I want to fetch files withing the sub folder "app" relative to the base path given in the config file.
Good luck
$direcotry has to be an absolute path from your laravel root folder.
When your uploaded folder is in the root folder try this
$directory = base_path("upload/"."$username->username");
$scanned_directory = storage::allfiles($directory);
I recently started to mess around with some HTML and PHP, and have run into what is probably a super easy to solve error, but one I have not for the life of me been able to fix.
In a nutshell, what I'm trying to do is create a directory, then create a .txt file in that directory with the same name, something to the effect of "/number/number.txt". While it seems simple to create a file, or to create a directory, I'm having no end of troubles trying to do both.
Here's my code:
mkdir($postnum, 0777);
chmod($postnum, 0777);
$post = "/" . $postnum . "/" . $postnum . ".txt";
$post = boards(__FILE__) . $post;
$po = fopen($post, 'w+') or die("Can't open file");
chmod($post, 0777);
A few issues I ran into writing this, I read that using mkdir I could set the permissions of the directory I create, but despite doing what I believe to be the right way of doing so, it didn't do anything. So I ran chmod right after.
Then, I had hoped that just /$postnum/$postnum.txt would work for the directory to open, but I get the die text when I try just that, I had to add in the "boards(FILE) part to get it to work. (Side note, "boards" is the directory I'm working in)
Even then, while it doesn't give me "Can't open file", it isn't creating the file or anything.
I've made certain that any file or folder even remotely interacting with the files has had it's permissions set to 0777, so it's likely not an issue with that. (Also, I know that having all my files completely open like that may not be the best idea; once I get this working properly, I'll be sure to set the permissions to something more safe)
Any idea what I'm doing wrong?
making directory and creating path:-
$new_folder=mkdir('uploads\\'.$folder_name, 0777, true);
('uploads\\'.$folder_name)->path where you create folder like www->upload->folder name(whatever you provide)
$path="uploads\\".$folder_name."\\";//if you want to provide path you can provide this way
The mkdir function takes a path relative to the root of the filesystem, not the document root.
If you're on a *nix system, your website document root is likely in a path such as /var/www/sitename/html, but you're trying to create /number/number.txt which your account doesn't have permissions to do. Change the path you pass into mkdir to somewhere in the filesystem you have permissions to create folders and files and your code should work.
Edit:
The code in your question doesn't actually attempt to write anything. By calling fopen you've created a file handle, but you need to call fwrite to actually write data to the file. As suggested by #JamesSwift, you may want to take a look at file_put_contents.
Here, try this :
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
mkdir("$root/root_website_folder/php/testing_folder", 0777);
PHP uses your real path not the virtual one, we assign to $root the real path on your machine than add the virtual path of your website root
I am having a weird problem with my php. Whenever I try to move a file with rename(), not only the file is not moved, but also the directory to which it should be copied is deleted, together with all files within it. The original code is:
rename('temp.odt', 'tmp/report.odt');
but I have already tried other path delimiters like
rename('temp.odt', 'tmp\report.odt');
rename('temp.odt', 'tmp\\report.odt');
rename('temp.odt', 'tmp' . DIRECTORY_SEPARATOR . 'report.odt');
rename('C:\wamp\www\zaiko\temp.odt', 'C:\wamp\www\zaiko\tmp\report.odt');
all to no avail. The code comes from a 3rd-party module which is used in the system I am working on.
Points well checked:
The file 'temp.odt' does exist in the current directory;
The directory 'tmp' does exist and there are several files in it. Also it is not read only.
The target file does not already exist (the actual file name has a timestamp, I reduced it here for simplicity)
After running rename(), the 'temp.odt' file is intact in its original location, while the folder 'tmp' is vanished as well as everything inside it. The following warning is issued:
( ! ) Warning: rename(temp.odt,tmp\report.odt) [function.rename]: The system couldn't find the specified path*. (code: 3) in C:\wamp\www\zaiko\modules\mod_deliver.php on line 192
*translated from Portuguese
Running: Apache 2.2.17 with PHP 5.3.5 on Windows XP with NTFS
Editing:
Just found the cause of the problem. It turns out that the module used by the application uses, in turn, a compression library; this library uses a temporary folder with exactly the same name as the one used by the application.
It must use some sort of cache, which would explain why the error didn't appear 100% times.
Problem solved by changing the name of the 'tmp' folder to anything else.
Thank you all for your time, and sorry for bothering you with such a stupid thing that, as it turns out, had absolutely nothing to do with my initial guess and, consequently, with the question formulated.
The example on PHP.net tells you exactly what to do - use the ROOT PATH to the file - normally this can be got by using $_SERVER['DOCUMENT_ROOT'] (but this only goes to the htdocs/public_html directory - you need to specify the rest) or by manually typing the path in (but try to avoid this).
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
At a guess, the following should work (assuming this is your path) - this also checks that your file actually exists so it can be renamed - you need to make sure that tmp/ actually exists in the first place, but you will get an error popping out if it didn't:
<?php
$root = getcwd().DIRECTORY_SEPARATOR; // Obtain the current working dir
$srcpath = $root."temp.odt"; // The file you want to rename
$destpath = $root."tmp/report.odt"; // Where you want to rename the file to
// make sure file exists and its movable
if(is_writable($srcpath)){
// if it exists, rename it
rename($srcpath, $dstpath);
echo "File was renamed!";
} else {
echo "It seems that the specified file doesn't exist!";
}
?>
You were escaping characters by using backslashes - always use forward slashes (I know this is within a single quote, which is ok, but if you use double quote then you would wonder what's gone wrong)!