I am trying to write a script in Yii for downloading files. view file isecho CHtml::link('Major Oilseeds: World Supply and Distribution.','downloadpdf', array('class'=>'btn btn-darkorange')); and the controller code is $path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/download/Major_Oilseeds.csv';
echo $path;
if(file_exists($path)){
Yii::app()->getRequest()->sendFile( 'Major_Oilseeds.csv' , file_get_contents($path) );
}
else{
echo '<br>File not found';
} the code echo $path dispalys the location as http://localhost/projectv2/download/Major_Oilseeds.csv and the download folder contains the file named "Major_Oilseeds.csv" but its always showing "File Not Found" Error. plz somebody help me to solve this. I have also tried the code $path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/download/Major_Oilseeds.csv';
// $filename = 'Major_Oilseeds.csv';
header('Content-Disposition: attachment; charset=UTF-8; filename="'.$path.'"');
$utf8_content = mb_convert_encoding($content, "SJIS", "UTF-8");
echo $utf8_content;
Yii::app()->end();
return; but its also not working :-(
file_exists can only work with local files. In your case you are trying to use file_exists with a URL.
You can find a workaround here: http://uk1.php.net/file_exists (please search for "http" in this page)
Related
I have a method which is responsible for downloading a file.
$attachment = KnowledgeDatabaseAttachments::where('id', $id)->first();
if ($attachment) {
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
After download, when I try to open it (this is an error message from my OS):
Could not load image '88ebb9c0-11af-11e8-b056-b1568dc848cb.jpg'.
Error interpreting JPEG image file (Not a JPEG file: starts with 0x0a 0xff)
File is saved like so:
$filesPath = storage_path('app/knowledge_database_attachments');
$physicalName = Uuid::generate() . '.' . $file->getClientOriginalExtension();
$file->move($filesPath, $physicalName);
KnowledgeDatabaseAttachments::create([
'knowledge_database_id' => $page->id,
'name' => $file->getClientOriginalName(),
'physical_name' => $physicalName
]);
File exist in that directory, and the downloaded file has correct size and name.
Funny part is that I can also create a newsletter which will include this file. When I create newsletter file is copied:
$extension = explode('.', $attachment->physical_name)[1];
$newPhysicalName = Uuid::generate() . '.' . $extension;
File::copy($attachment->getPathAttribute(), $storagePath . DIRECTORY_SEPARATOR . $newPhysicalName);
SendMailAttachments::create([
'mail_id' => $mail->id,
'filename' => $attachment->name,
'physical_name' => $newPhysicalName,
]);
And then, in the newsletter edit view I can as well download this file, with this (identical as above) method:
$attachment = SendMailAttachments::where('mail_id', $mailId)->where('filename', $attachmentName)->first();
if ($attachment) {
$filesPath = storage_path('app/sendmail_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
And it works - file is correctly downloaded and I can open it.
Why I cant open file downloaded with first method?
I use Laravel 5.1 and Ubuntu 16.04 (if that matters).
EDIT
When I run file command on a downloaded file the result is data. When I run it on file in storage, the result is correct JPEG image data.
Try to add headers with response
View docs
$headers = array('Content-Type' => ' image/jpeg');
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath,$attachment->physical_name,$headers);
Note: Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name.
The problem is that I have something being output before the image stream.
Temporary solution:
$response = response()->download($filesPath . '/' . $attachment->physical_name);
ob_end_clean();
return $response;
Permanent solution:
Find whats being output and remove it.
Found this here: https://laracasts.com/discuss/channels/laravel/image-is-being-thrown-as-a-white-blank-image?page=1
I am getting following error, when I try to save data into db after file upload:
finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory
This is the code:
$userFolderPath = \Yii::getAlias('#webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . \Yii::$app->user->getIdentity()->iduser;
$model = new CsFile();
$files = UploadedFile::getInstances($model, 'files');
$errors = [];
if (!file_exists($userFolderPath))
mkdir($userFolderPath, 0777, true);
foreach($files as $file):
$fileModel = new CsFile();
$fileModel->files = $file;
if($fileModel->validate()):
$filename = str_replace(' ', '_', $file->baseName);
if(file_exists($userFolderPath . DIRECTORY_SEPARATOR . $filename . "." . $file->extension)):
$filename .= "-" .uniqid();
endif;
$fileModel->files
->saveAs($userFolderPath .DIRECTORY_SEPARATOR. $filename . '.' . $fileModel->files->extension);
$fileModel->iduser = Yii::$app->user->getIdentity()->iduser;
$fileModel->name = $filename;
$fileModel->extension = $file->extension;
$fileModel->add_date = date('Y-m-d H:i:s');
$fileModel->save();
else:
endif;
endforeach;
var_dump('<pre>', $errors, '</pre>');
I had the same problem a few weeks ago. Turns out, when we rename the file before upload and try to save the model, this error will appear.
If that attribute it's only for handle your upload and have no field in your table, you can just unset this fields before saving: $files Model->files = null.
Let me know if your scenario is different than mine.
Yii2 use UploadFile class through function $model->upload() to save upload file
To fix this use inside your $model->upload function :
return copy($this->YourAttribute->tempName, $newFileName);
instead
return $model->attribute->saveAs($newFileName)
Clyff is right. But in case you are saving the path of the file in database to read later, setting the attribute to null is not going to work.
The problem is when you try to save the model still with result of UploadedFile::getInstance($model, 'file') in the file field which is already used by $model->file->saveAs();
$model->save() cannot save the path of the saved and already removed temporary files path directly.
So after successful $model->file->saveAs($path) you need to do something like:
$model->file = $path;
It was quite unclear to me and spent a bit of time after fileinfo , so hope the answer helps.
I was having same problem, I solved it with this:
$model->file->saveAs($filepath , false)
then...
$model->save(false)
Important: In the saveAs function pass false parameter.
Using false parameter in $model->save(false) that means you are ignoring model validation, which is not right.
But using false as a second parameter in $file->saveAs($path,false) means you are trying to keep the file in the temp folder after being uploaded and allow the model to access the file during validation when trying to save to the database.
If the model fails to access the file (i.e removed from the temp folder after being uploaded), you will getting an ERROR Fail to open a stream, No such file/folder
I want to check exist file with php or yii2
filesize and is_file and file_exists are not working !
filesize error is : filesize(): stat failed for....
is_file and file_exists return false !
This is my code :
$fileI = $urlBase . "$home/../siteImage/$logo";
$fileI is :
http://localhost/iicitySite/web/index.php/../siteImage/parvaz.png
$home is :
$home -> /iicitySite/web/index.php
This is has correct image in view :
echo "
<div class='col-lg-12 col-xs-12 col-sm-12 col-md-12 forsatItem'>
<div class='backItem'>
<div class='rightM col-lg-4'>
<div class='imgForsat'>
<img src='$home/../siteImage/$logo' alt=''/>
</div>
.
.
.
.
Try this
$url = 'http://www.example.com';//or file path
$headers = get_headers($url, 1);
print_r($headers);//$headers[0] u will get the status
Source: link
I have checked and verified below code and it is working fine.
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
If you are not able to do this then the issue with your permission. Try to check file that are in desktop or some other permissible directory.
Hope this helps.
In you path you don't need the index.php but only the path
You can use this to get absolute(whole url including http) url :
echo Url::to('#web/siteImage/parvaz.png', true);
// http://codematrics.com/web/siteImage/parvaz.png
If you want to use relative(relative to current path) path than you can use this :
echo Url::to('#web/siteImage/parvaz.png', true);images/logo.png
// http://codematrics.com/web/siteImage/parvaz.png
If you are checking if file exist into server just you have to give the absolute path, I'm using \Yii::getAlias('#webroot') for get the absolute path and I'm executing this from a Controller.
This is my result into web browser.
Absolute Path:/home/hostinguser/public_html/files/temppdf/benja.pdf
The File /home/hostinguser/public_html/files/temppdf/benja.pdf Exists
$pathFile = \Yii::getAlias('#webroot') .'/files/temppdf/' . 'benja.pdf';
echo "<br>Absolute Path:" . $pathFile;
if (file_exists($pathFile)) {
echo "<br>The File $pathFile Exists";
} else {
echo "<br>The File $pathFile Do Not Exist";
}
$url = 'http://www.example.com'; // or file path
$headers = get_headers($url, 1);
print_r($headers); // $headers[0] will get the status
I have a form to display which have file attachments at the time of form filling, I succeeded in attaching the file, but at the time of displaying the form it also showing the attached file in some binary/etc form, instead I want it to show just a file name and whenever we click on the file name it has to download the file... Please do help for this
My Code is:
<?php
...
$id = htmlentities($_GET['id'], ENT_QUOTES);
// Get the details of the risk
$risk = get_risk_by_id($id);
$status = htmlentities($risk[0]['status'], ENT_QUOTES);
$subject = $risk[0]['subject'];
//file retrival fields
$filename = $risk[0]['name'];
$mimetype = $risk[0]['type'];
$filedata = $risk[0]['content'];
...
?>
<html>
...
<?php
...
echo "<label>Risk Assessment</label>\n";
echo "<textarea name=\"assessment\" cols=\"50\" rows=\"3\" id=\"assessment\" disabled=\"disabled\">" . htmlentities(stripslashes($assessment), ENT_QUOTES). </textarea>\n";
echo "<label>Additional Notes</label>\n";
echo "<textarea name=\"notes\" cols=\"50\" rows=\"3\" id=\"notes\" disabled=\"disabled\">" . htmlentities(stripslashes($notes), ENT_QUOTES) . "</textarea>\n";
echo "<label>Files attached:\n</label>";
echo $filedata;
...
?>
...
</html>
and the o/p is displaying the file content... :(
you are echoing the $filedata content. you should echoing the $filedata location, not its content.
Here's an example of how to download a pdf file instead of displaying it:
You're Page:
<a href="dl.php?filnam=xyz.pdf>Download the file</a>
dl.php
<?php
$filnam = str_replace(" ", "%20", basename($_GET['filnam']));
header ("content-type: application/pdf");
header ("Content-Disposition: attachment; filename*=UTF-8'en'$filnam");
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($_GET['filnam']));
readfile($_GET['filnam']);
?>
So there are a few steps
Get the name of the file
Get the local path of the file
Respond with a link.
It's been a while since I used PHP but I believe you can get the name of the file with
//basename takes /a/b/c/d.jpg and returns d.jpg
$filename = basename($risk[0]['name']);
$localpath = $risk[0]['tmp_name'];
and then for your output do
echo " . $filename . "" . PHP_EOL
That will create a link with the label of the filename and the url of the local path on the server.
Update: Apparently the file doesn't actually exist yet. If this is the case, then you should write the contents of the file stored in your db. To do this, do
$handle = fopen($filename, "wb");
You can use whatever filename you want. You should add something like the timestamp or user ID or something to make the file unique so it's not overwritten by multiple requests. This will create the file. You can then fill in the file by doing
fwrite($handle, $risk[0]['content']);
finally close the file with
fclose($handle);
to output this new link you can just use the same filename if you like
echo " . $filename . "" . PHP_EOL
If you specified the filename by including some unique value then you can get the original name by using
echo " . $risk[0]['name'] . "" . PHP_EOL
Hope that helped!
Can I get an eyeball on my symlink?
I'm trying to download a file from one directory, while the file actually exists in another.
I've got the actual file, and the symlink in seperate subdirectories, but both reside in the public html(both are web accessible).
I've verified the file and file location on my (shared Linux) server by going to the file directly.
The link is being created (I've used readlink, is_link, and linkinfo), and I can see it when I FTP in.
I believe I am probably just having a misunderstanding of the directory structure.
I put the file here: ./testdownload/
I put the symlink here: ./testDelivery/
<?php
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "./testdownload/";//Where the actual file lives
$downloadDirectory = "./testDelivery/";//Where the symlink lives
unlink($downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($fileRepository . $fileName, $downloadDirectory . $fileName);
$checkLink = ($downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
Everything looks right to me....but the link won't work.
Help?
Ultimately, I will put the source data outside the public area...this is just for testing.
(I'm trying to find a better solution for download than chunking out fread which fails for poor connections. (200-400MB files))
My problem (appears) to be not providing the absolute path for the symlink.
I've added the absolute path below to the same code above, to give a working copy:
<?php
$absolutepath = ( $_SERVER['DOCUMENT_ROOT']);
$fileName = "testfiledownload.zip";//Name of File
$fileRepository = "/testdownload/";//Where the actual file lives
$downloadDirectory = "/testDelivery/";//Where the symlink lives
unlink($absolutepath .$downloadDirectory . $fileName); // Deletes any previously exsisting symlink (required)
symlink($absolutepath . $fileRepository . $fileName, $absolutepath. $downloadDirectory . $fileName);
$checkLink = ($absolutepath . $downloadDirectory . $fileName);
if (is_link($checkLink))
{
echo ("<br>Symlink reads: " .readlink($checkLink) . "<br>");
echo ("<br>LinkeInfo reads: " . linkinfo($checkLink));
}
?>
<p><a href="<?php echo ("/testDelivery/" . $fileName); ?>"</a>SymLink</p>
<p><a href="<?php echo ("/testdownload/" . $fileName); ?>"</a>regular link</p>
This original post, is a duplicate (though I didn't see it until now)
Create a valid symlink for PHP file
(Most of the answers given for that question were wrong however--but the original poster figured it out, and it worked for me too)