CakePHP 3: How to check if file or image exists - cakephp

I am just trying to check if an image exists or not, I can do it by using PHP. For example:-
$file = WWW_ROOT .'uploads' . DS . 'employee' . DS .'_'.check.jpg;
$file_exists = file_exists($file);
It's working fine for me. But I have tried also tried using elementExists like this:-
if($this->elementExists("../".$employees->front_image))
{
echo $this->Html->image("../".$employees->front_image); // image output fine without condition.
}
// Here $employees->front_image = uploads/employee/employeename.jpg
This check is not working. How can I do this in CakePHP?

CakePHP is written in PHP, so if you already have a simple solution like file_exists() use that. So you can write something like this:-
if (file_exists(WWW_ROOT . $employees->front_image)):
echo $this->Html->image('../' . $employees->front_image);
endif;
elementExists() is intended for checking that a View element exists, not if files exist in the webroot, so should not be used like you are trying. It does do a file_exists() check, but this scans all available View element paths only.

I think this works in Cake 3 (you should do this in afterFind method IMO):
// Create a new file with 0644 permissions
$file = new File('/path/to/file.php', true, 0644);
if ($file->exists()) {
//do something
}
$file->close();
Your way is checking whether view element exists or not.

This worked for me:
Q: How to check if image exists on remote url or not?
Explanation:
$rfile will take url
$check will open the file with read rights
If file exists then it will print "File exists" else "Doesn't exists".
code:
<?php
// Remote file url
$rFile = 'https://www.example.com/files/test.pdf';
// Open the file
$check = #fopen($rFile, 'r');
// Check if the file exists
if(!$check){
echo 'File does not exist';
}else{
echo 'File exists';
}
?>

Related

Rename an image with laravel 5

I have a directory with images and I show to the user,the user can rename a image, I have the file with
$images = File::files('img');
$image = $images[0];
But I don't know how rename an image.
Thanks
You can retrieve it first from the input. and move it using file name you define.
Your image will using the file name you specify.
$picture= $request->file('image');
$fileName = 'what the image you want to call';
$picture->move('image/foo', $fileName);
Brother, This is work for me. And I hope, It'll serve your purpose
$destinationPath = "uploadedImages";
$newName = md5_file($request->file('file_name')->getRealPath());
$guessFileExtension = $request->file('file_name')->guessExtension();
$file = $request->file('file_name')->move($destinationPath, $newName.'.'.$guessFileExtension);

how to check if folder exists cakephp

Is there any instance to return bool? e.g. $folder->exists() => bool
$path = WEBROOT_DIR .'/files/'. $folder_name;
$folder = new Folder('../'.$path);
//DOESN'T WORK
debug($folder->exists());
//I can do it in this way
//returns bool
debug(file_exists($folder->path));
I want to check if directory exists delete it. but I want to use specifically cake method to check if folder exists
Try this:
$path = 'files' . DS . $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) {
$folder->delete();
}
Cakephp Folder class does not have method exists like File class has.
You could check if the folder exists with standard php and then delete it.
if (file_exists('path/to/directory')) {
rmdir('path/to/directory', 777, true);
}
Basically it checks if the folder exists with the file_exists function and if the file does not exist then it will use rmdir function to create the folder.
Though I think you could use cakephp like this. This will delete the folder even if the folder does not exist because the Folder constructor will create the folder if the folder does not exist.
$folder = new Folder('path/to/directory', true, 777);
$folder->delete();

$Email->attachments() does not attach file

We are using Cake's E-Mail class to send emails with attachments. It works fine for all cases except one and we are not able to figure out where the problem is.
Process:
A pdf-File is created & written to the file-system (file is written correctly and exists)
when the Email is sent the attachment is 0bytes in size (whereas the file to attach is created correctly in the file-system)
Working code:
// Write invoice as file
$CakePdf->write(APP . 'tmp' . DS . 'invoices' . DS . $invoiceNo . '.pdf');
[...]
// Send invoice to customer
$Email = new CakeEmail('invoice');
$Email->attachments(APP . 'tmp' . DS . 'invoices' . DS . $invoiceNo . '.pdf');
$Email->to($this->Invoice->Customer->getEmailAdress($customerId));
$Email->viewVars(array('invoice_no' => $invoiceNo));
$Email->send();
Not working code (attachment is zero bytes in size):
$CakePdf->write(APP . 'tmp'. DS .'certificates' . DS . $certLoginId . $certCourseId . '.pdf');
[...]
// Send certificate to customer
$Email = new CakeEmail('certificate');
$Email->attachments(APP . 'tmp'. DS .'certificates' . DS . $certLoginId . $certCourseId . '.pdf');
$Email->to($emailOfUser);
$Email->viewVars(array('courseName' => $certCourseName, 'probandName' => $probandName));
$Email->send();
Edit - there is no typo it is all correctly set. The problem seems to be, that the generation of a PDF by tcpdf runs asycnronously in the background. So when Cake tries to attach the file it is not written to the file system completly. So it cannot be attached.
If tried to let the script sleep for a while with no success:
echo '<br>';
echo $path_to_certificate;
echo '<br>';
echo filesize($path_to_certificate);
sleep(10);
echo '<br>';
echo $path_to_certificate;
echo '<br>';
echo filesize($path_to_certificate);
echo '<br>';
sleep(10);
echo $path_to_certificate;
echo '<br>';
echo filesize($path_to_certificate);
Outputs:
C:\xampp\htdocs\www\eflux_frontend\app\tmp\certificates\13750.pdf
0
C:\xampp\htdocs\www\eflux_frontend\app\tmp\certificates\13750.pdf
0
C:\xampp\htdocs\www\eflux_frontend\app\tmp\certificates\13750.pdf
0
Whereas the file is generated in the meantime, because I can see & access the file in the filesystem. It isn't a locking Problem because the other code works in a different place, but the file generated is smaller so it does not take up so much time to process.
How can I now ensure that the generation process is complete?
It seems that we are not able to ensure, that the PDF is properly created before attaching it to an email (maybe someon can give me a hand here).
Due to the fact, that the created PDF is written to a database an ugly workaround is possible: After the PDF is written to database, we can take it out of the database, write a file using the CakeFileHandler and attach this to the email which works for me:
// Workaround
$this->Certificate->recursive = -1;
$data = $this->Certificate->findById($cert_id);
$pdf = base64_decode($data['Certificate']['certificate_pdf']);
$path_to_certificate = APP . 'tmp'. DS .'certificates' . DS . $certLoginId . $certCourseId . '.pdf';
$certificate_file = new File($path_to_certificate);
$certificate_file->write($pdf);
[do mail stuff]
$certificate_file->delete();
$certificate_file->close();

Cakephp ghost file

I am facing a curious situation. I am using CakePHP 2.0 (locally), XAMPP and I wanted to add a simple hit counter in my homepage so I added the following code (very very simple)
<?php
$filename = 'hitcount.txt';
$handle = fopen($filename, 'r');
$hits = trim(fgets($handle)) + 1;
fclose($handle);
$handle = fopen($filename, 'w');
fwrite($handle, $hits);
fclose($handle);
echo $hits;
There is a text file named hitcount.txt which contains the number of hits (everytime I visit the page it should increase the number of hits). It works. The problem appeared when I tried to access the hitcount.txt file. It was empty but the echo of $hits returned the exact result! I deleted the file and it still shows me the expected result! I used a different browser, the same. I deleted CakePHP's cache, no change. I used the same piece of code in another page and it did not complain with some error, returning the expected result.
How is it possible for Cakephp to "see" a file that does not exist? Has it anything to do with Apache?
You probably view the file at the wrong location as CakePHP's. My guess is CakePHP's referring to the file at app/webroot/hitcount.txt.
You might want to define a full path for hitcount.txt so you can be sure that you and CakePHP are both referring to the same location.
<?php
$filename = TMP.'hitcount.txt';
This would locate the file at `app/tmp/hitcount.txt'.

CakePHP copy file to new directory

The cakephp documentation is a bit poor according the File api and I would like to use it to copy one file to another directory and if the directory does not exist to create it.
Thanks!
You can do something like this:
$file = new File('your_file.ext');
if ($file->exists()) {
$dir = new Folder('folder_inside_webroot', true);
$file->copy($dir->path . DS . $file->name);
}
API about these classes:
Folder;
File;
I hope it helps.

Resources