Laravel: check file existence without extension - php

I'm saving files in server only with a md5 hashed name without extension.
I noticed laravel Storage::exists() method will return true even if file does not exists. in fact laravel assume file name as a directory name. is there any way to force laravel to check file existence ?

Actually, it's because the way PHPs file_exists function works. Anyways, you may use something like this:
if(is_file('68e109f0f40ca72a15e05cc22786f8e6')) {
// ...
}
Also, you may try glob like this:
$all = glob('*'); // Read everything from current directory in array
if(in_array('68e109f0f40ca72a15e05cc22786f8e6', $all)) {
// ...
}
There are more ways to do this but why not use an extension?

Related

I want to create a .html file in /public folder of Laravel

I'm trying to create and store some HTML code from a textarea into a file
fopen method in PHP will create a file if that file doesn't exist already but it is not working in Laravel 5.7
Here is my demo code
$plugin_html_file_nm = "plugin_html".time().".html";
$html_plugin = fopen("/public/plugin_html_storage/".$plugin_html_file_nm,"w");
fwrite($html_plugin,$request->input('plugin_html'));
$plugin->plugin_html = $plugin_html_file_nm;
This error is given fopen(/public/plugin_html_storage/plugin_html1546535810.html): failed to open stream: No such file or directory
Can anyone help me?
Laravel provides a helper public_path()
The public_path function returns the fully qualified path to the
public directory. You may also use the public_path function to
generate a fully qualified path to a given file within the public
directory
Maybe you need to add the full path. So:
$html_plugin = fopen(public_path("plugin_html_storage/.$plugin_html_file_nm"),"w");
Also, make sure you have writing privilegies. As the PHP documentation states:
The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access.
Your laravel app by default is served from the public directory.
So in order to achieve what you're trying to do, replace
$html_plugin = fopen("/public/plugin_html_storage/".$plugin_html_file_nm,"w");
with:
$html_plugin = fopen("./plugin_html_storage/".$plugin_html_file_nm, "w");
Note: The plugin_html_storage directory should be created in the public directory so the operation doesn't fail.
You just need to add the relative path.
$html_plugin = fopen("../public/plugin_html_storage/".$plugin_html_file_nm,"w");
file_put_contents(public_path()."plugin_html".time().".html",
$request->input('plugin_html'));

Laravel File Storage delete all files in directory

Is there a way to delete all files in specific directory. I'm trying to clear all my files in my created folder backgrounds in storage\app\backgrounds but in docs seems no method for delete all.
Storage::delete('backgrounds\*.jpg');
I don't think if this is the best way to solve this. But I solved mine calling
use Illuminate\Filesystem\Filesystem;
Then initiate new instance
$file = new Filesystem;
$file->cleanDirectory('storage/app/backgrounds');
for Laravel >= 5.8
use Illuminate\Support\Facades\Storage;
// Get all files in a directory
$files = Storage::allFiles($dir);
// Delete Files
Storage::delete($files);
Just use it.
File::cleanDirectory($direction);
You can use Filesystem method cleanDirectory
$success = Storage::cleanDirectory($directory);
Please see documentation for more information:
https://laravel.com/api/5.5/Illuminate/Filesystem/Filesystem.html#method_cleanDirectory
In Laravel 5.8 you can use:
Storage::deleteDirectory('backgrounds');
Remember to include:
use Illuminate\Support\Facades\Storage;
In Laravel 5.7 you can empty a directory using the Storage facade like so:
Storage::delete(Storage::files('backgrounds'));
$dirs = Storage::directories('backgrounds');
foreach ($dirs as $dir) {
Storage::deleteDirectory($dir);
}
The delete() method can receive an array of files to delete, while deleteDirectory() deletes one directory (and its contents) at a time.
I don't think it's a good idea to delete and then re-create the directory as that can lead to unwanted race conditions.
I'm handling this by deleting the whole directory as I don't need it. But if, for any case, you need the directory you should be good by just recreating it:
$d = '/myDirectory'
Storage::deleteDirectory($d);
Storage::makeDirectory($d);
//You can use Illuminate\Filesystem\Filesystem and it's method cleanDirectory('path_to_directory).
For Example:
$FolderToDelete = base_path('path_to_your_directory');
$fs = new \Illuminate\Filesystem\Filesystem;
$fs->cleanDirectory($FolderToDelete);
//For Delete All Files From Given Directory.
$succes = rmdir($FolderToDelete);
//For Delete Directory
//This Method Works for me
#Laravel
#FileManager
#CleanDirectory

Laravel - Get storage disk path

I have created a new storage disk for the public uploads. I use it like this:
Storage::disk('uploads')->get(...);
But I am trying to figure out a way to get the path to the disk itself, I have spent some considerable time wondering between the framework files, but couldn't find what I am looking for. I want to use it in a scenario like so:
$icon = $request->file('icon')->store('icons', 'uploads');
Image::make(Storage::disk('uploads')->path($icon))->resize(...)->save();
So, how to get a storage disk's path ?
Update 2022
You can get the path from the config:
config('filesystems.disks.uploads.root')
Anyway, I keep the old answer, as it still works and is not wrong:
There is a function for this!
Storage::disk('uploads')->path('');
https://laravel.com/api/5.8/Illuminate/Filesystem/FilesystemAdapter.html#method_path
Looks like this has been there since 5.4! I never noticed...
After extra search I found that I can use the following:
$path = Storage::disk('uploads')->getAdapter()->getPathPrefix();
But still, isn't a "->path()" method is a given here or what!
We can also access the disk storage path from configuration helper directly:
config('filesystems.disks');
There are helper functions in the framework now that can get some of the commonly used paths in the app fairly easily.
https://laravel.com/docs/5.8/helpers
For example, if you wanted to access a file from the public folder you could do the below.
$image_file_path = public_path("images/my_image.jpg")
This will return you a local path for a file located in your app under the public/images folder.
Laravel Default Method
return Storage::disk('disk_name')->path('');
Get List of All Directories using disk name
Storage::disk('disk_name')->directories()

How to check view exist or not?

In CodeIgniter I am trying to check before loading the view that the file exist or not from controller, I tried like-
public function foo($file = "")
{
if (file_exists(APPPATH."views/log/{$file}.".EXT))
{
$this->load->view('log/'.$file);
}
else
show_404();
}
But the file is exist there then also the file_exists() method is returning false, I have checked it using var_dump() also. I am not getting what is the problem here, I am guessing that there is something problem related to mapping because the directory structure is like-
application
|--controllers
| |--ctrl.php //Controller file where I am checking
|--views
|--log
|-- .. //Checking files for here
but how can I resolve?
Edit: Just mistyped 'views' to 'view'(in code where I am calling file_exists() method in if) corrected it.
The EXT constant in Codeigniter is equal to .php and defined in index.php:
// The PHP file extension
// this global constant is deprecated.
define('EXT', '.php');
You are adding an extra dot:
APPPATH."views/log/{$file}.".EXT
// ^
Which would result in something like views/log/myfile..php
Since the constant is being phased out you should avoid it.

Is there a way to get the name of the top level PHP file from inside an included one?

Let's say I'm writing a global logData method that wants to write to a log file that has the same name as the php that's running it, but with a .log extension.
I'm including this logging in a parent php with the intention of having it always write to log files that are whatever the *parent file name is (not the tools.php lib in which it's sitting).
So, I have
/some/arbitrary/directory/parent.php
which calls
include ("/path/to/my/php/libs/tools.php");
but when I run my logging method that's in tools.php it logs to a file called
/path/to/my/php/libs/tools.php.log
rather than
/some/arbitrary/directory/parent.php.log (which is what I'd like).
I'm using __FILE__ which is behaving this way (probably as its intended to). Is there a command for getting the parent's file name so that I can get this to work as I intend? Or will I have to pass FILE as a param into my method from the parent php to get it to write to the correct output file?
TIA
You could probably use $_SERVER["SCRIPT_FILENAME"]
debug_backtrace() will give you what you need.
http://php.net/manual/en/function.debug-backtrace.php
You need to pass __FILE__ to the log class.
Something like:
// file:/some/arbitrary/directory/parent.php
$logger = new Logger(__FILE__);
// file:/path/to/my/php/libs/tools.ph
public function __construct($file) {
// But it is not good idea to save log file same with php files.
$this->log_path = $file.'.log';
}

Categories