How to handle errors exception in laravel snappyPDF? - php

Using Laravel/Snappy to generate PDFs. However this errors:
already exist file name after trying to save it to storage.
How can I handle these errors?
public function saveSnappyHeaderFooter()
{
//dd( storage_path());
$users = \App\User::all();
$data = ['users' => $users];
$SnappyPDF = SnappyPDF::loadView('pdf.snappyPDF.snappyHeaderFooter', $data);
$SnappyPDF->setOption('margin-top', '25mm');
$SnappyPDF->setOption('margin-bottom', '25mm');
$SnappyPDF->setOption('header-html', public_path() . '\pdf-parts\pdf-header.html');
$SnappyPDF->setOption('footer-html', public_path() . '\pdf-parts\pdf-footer.html');
$SnappyPDF->setOption('print-media-type', true);
$SnappyPDF->save(storage_path('app/files/'.Carbon::now() .'_' . 'myname2.pdf'));
}

In general this is how you can handle errors in PHP:
try {
//your code
} catch (Exception $e) {
//handle errors
}
Or you can ask if file exists by using:
if(!file_exists(storage_path('app/files/'.Carbon::now() .'_' . 'myname2.pdf'))){
//ok, code will run
}else{
// not ok, maybe change the name?
}
you can also do it in the laravel way: File::exists
Or maybe you can give us more details.
Note
Its an anti-patteren to not be 100% sure that the files is not exists. I dont know your usecase, but im saying that based on the fact that you are generating the file name. maybe you should use more uniq patterens. like GUIDs...

Related

Search files with prefix on S3 in Laravel 9

I'm working on a project that save file on S3. But I've never worked with S3 before.
I want to retrieve the files that match this pattern: {id}_{YYYYMMDD}.pdf
I could do this Storage::disk('s3')->files(); with Storage, but I think it's not the solution because there are thousand of files.
I search through topics and this is one of the things I've tried so far:
public static function searchS3ByPrefix($path, $prefix) {
try {
$storage = Storage::disk('s3');
$client = $storage->getAdapter()->getClient(); // ** error on this line
$command = $client->getCommand('ListObjects');
$command['Bucket'] = $storage->getAdapter()->getBucket();
$command['Prefix'] = $path . $prefix;
$result = $client->execute($command);
return array_column($result['Contents'], 'Key');
}
catch (\Exception $e) {
Log::error($e);
return [];
}
}
The error message said that getClient() is undefined in League\Flysystem\AwsS3V3\AwsS3V3Adapter
Do you have a solution for this? Thank you very much
On the line where I commented error, just modify it into this:
$client = $storage->getClient();
Note: In my case, the result will be empty if the prefix has slash / at the very beginning, so make sure to remove it. For example: '/data/1_' will not work, change it to 'data/1_'

How to Check file exists in Laravel

I have a Laravel Controller Function file_fetch()
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
This works if i check for file public/folder/app/index.html and if i check for public/newfolder (newfolder doesnt exist) and hence it executes else function and redirects with error message, but if i search for public/folder/app/ I havent specified the file name, but the directory exists, hence the if(!File::exists($destinationPath)) function is getting executed!
i want to check just and files inside the directory and even if the directory exists, if file is not present, throw a error message, saying file doesnt exists.
add one more additional condition to check given path is file but not a directory
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath) && !is_dir($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
You can probably fix your code by validating the routename input such that it will never be empty (and have a certain file extension maybe?)
, which is nice to do anyhow.
If that fails, you can try File::isDirectory($dir) which basically calls is_dir(...).
Note that it might give you more control on your storage solution if you use the Storage::disk('public') functionalities from Laravel. The API is a bit different but there's a wide range of probabilities associated with it. Read more about that here: https://laravel.com/docs/8.x/filesystem#introduction.
If you in different/multiple buckets.
//Do not forget to import
use Illuminate\Support\Facades\Storage;
if (Storage::disk('s3.bucketname')->exists("image1.png")) {
}

Save output data in image format

I am saving the data as jpeg file but it is not saving properly.
$file= drupal_http_request('https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRvAAAAwMpdHeWlXl-lH0vp7lez4znKPIWSWvgvZFISdKx45AwJVP1Qp37YOrH7sqHMJ8C-vBDC546decipPHchJhHZL94RcTUfPa1jWzo-rSHaTlbNtjh-N68RkcToUCuY9v2HNpo5mziqkir37WU8FJEqVBIQ4k938TI3e7bf8xq-uwDZcxoUbO_ZJzPxremiQurAYzCTwRhE_V0&sensor=true&key=AIzaSyDGsEo0x-oqsIDVn0EaTx6mN1BMXkAhZDs');
$handle=fopen("/public/image.jpeg",'w');
fwrite($handle,$file->data);
fclose($handle);
The output : $file->data is :" IHDRddpâ•TIDATxÚílUåÇkbæ....."
Save yourself the headache - use system_retrieve_file()
$result = system_retrieve_file($url, 'public://image.jpeg');
I imagine your current code isn't working because you're not using a proper URI to the public folder, but you might may as well use the API where available.
Instead file function you can use copy like this:
try{
copy($source, $destination);
}catch(Exception $e) {
echo "<br/>\n unable to copy '$fileName'. Error:$e";
}

Creating a folder when I run file_put_contents()

I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
after I tried this one, I get error result.
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.
Is there a way to solve this problem?
file_put_contents() does not create the directory structure. Only the file.
You will need to add logic to your script to test if the month directory exists. If not, use mkdir() first.
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
Update: mkdir() accepts a third parameter of $recursive which will create any missing directory structure. Might be useful if you need to create multiple directories.
Example with recursive and directory permissions set to 777:
mkdir('upload/promotions/' . $month, 0777, true);
modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)
ps previous answer is awesome
/**
* create file with content, and create folder structure if doesn't exist
* #param String $filepath
* #param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
i have Been Working on the laravel Project With the Crud Generator and this Method is not Working
#aqm so i have created my own function
PHP Way
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
Don't forget to add at top of the file
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
I created an simpler answer from #Manojkiran.A and #Savageman. This function can be used as drop-in replacement for file_put_contents. It doesn't support context parameter but I think should be enough for most cases. I hope this helps some people. Happy coding! :)
function force_file_put_contents (string $pathWithFileName, mixed $data, int $flags = 0) {
$dirPathOnly = dirname($pathWithFileName);
if (!file_exists($dirPathOnly)) {
mkdir($dirPathOnly, 0775, true); // folder permission 0775
}
file_put_contents($pathWithFileName, $data, $flags);
}
Easy Laravel solution:
use Illuminate\Support\Facades\File;
// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');
// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');
I wrote a function you might like. It is called forceDir(). It basicaly checks whether the dir you want exists. If so, it does nothing. If not, it will create the directory. A reason to use this function, instead of just mkdir, is that this function can create nexted folders as well.. For example ('upload/promotions/januari/firstHalfOfTheMonth'). Just add the path to the desired dir_path.
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
#mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}

PHP and Codeigniter - How do you check if a model exists and/or not throw an error?

Example #1
bschaeffer'sanswer to this question - in his last example:
$this->load->model('table');
$data = $this->table->some_func();
$this->load->view('view', $data);
How do you handle this when 'table' doesn't exist?
Example #2
try {
$this->load->model('serve_' . $model_name, 'my_model');
$this->my_model->my_fcn($prams);
// Model Exists
} catch (Exception $e) {
// Model does NOT Exist
}
But still after running this (obvously the model doesn't exist - but sometimes will) it fails with the following error:
An Error Was Encountered
Unable to locate the model you have specified: serve_forms
I am getting this function call by:
1) Getting some JSON:
"model_1:{"function_name:{"pram_1":"1", "pram_2":"1"}}
2) And turning it into the function call:
$this->load->model('serve_' . "model_1", 'my_model');
3) Where I call:
$this->my_model->function_name(pram_1=1, pram_2=1);
SOLUTION
The problem lies in the fact that CodeIgniter's show_error(...) function displays the error then exit; ... Not cool ... So I overrode: model(...) -> my_model(..) (you'll get errors if you just override it) and removed the show_error(...) because for some reason you can't override it - weird for Codeigniter). Then in my_model(...) made it throw an Exception
My personal opinion: the calling function should return
show_error("message"); where show_error returns FALSE --- that or
you could take out the exit; - and make show_error(...)
overridable
You can see if the file exists in the models folder.
$model = 'my_model';
if(file_exists(APPPATH."models/$model.php")){
$this->load->model($model);
$this->my_model->my_fcn($prams);
}
else{
// model doesn't exist
}
Maybe this helper function will help you to check if a model is loaded or not.
function is_model_loaded($model)
{
$ci =& get_instance();
$load_arr = (array) $ci->load;
$mod_arr = array();
foreach ($load_arr as $key => $value)
{
if (substr(trim($key), 2, 50) == "_ci_models")
$mod_arr = $value;
}
//print_r($mod_arr);die;
if (in_array($model, $mod_arr))
return TRUE;
return FALSE;
}
source reference
Don't foget that your application may use pakages. This helper function look through all models (even in packages included in your CI app).
if ( ! function_exists('model_exists')){
function model_exists($name){
$CI = &get_instance();
foreach($CI->config->_config_paths as $config_path)if(file_exists(FCPATH . $config_path . 'models/' . $name . '.php'))return true;
return false;
}
}
Cheers
#Endophage No you do not have to explicitly state what the model you are loading will be. They can be loaded dynamically.
Example:
$path = 'path/to/model/';
$model = 'My_model';
$method = '_my_method';
$this->load->model($path . $model);
return $this->$model->$method();
So you could have a single controller that uses the URL or POST vars.
I use this concept a lot with ajax calls. So OP's question is very valid. I would like to make sure that the model exists before I try to load it.

Categories