download a file from a prestashop module - prestashop

I am trying to download a file from a prestashop module. For that I have this code. It finds the file (since i receive the mail with the message "el file existe") but doesn't download it.
$directorioActual = _PS_UPLOAD_DIR_;
$filename = $directorioActual."ejemploCsv.csv";
if (!file_exists($filename)) {
mail("luilli.guillan#gmail.com", "el file no existe", "failed");
} else {
mail("luilli.guillan#gmail.com", "el file si existe", "success");
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
readfile($filename);

Related

laravel download excel file from s3 is not working

I am using laravel 5.1 I need to download excel from amazon s3 storage. I done all process correctly and if it is pdf format file means it downloading correctly but for excel file download it is downloading zip format. Can please anyone help me to fix this issue.
$filePath = "CIS/download/format/upload_format.xlsx";
if ( Storage::disk('s3')->has($filePath)) {
$file = Storage::disk('s3')->get($filePath);
$getMimeType = Storage::disk('s3')->getMimetype($filePath);
return Response::make($file, 200, [
'Content-Type' => $getMimeType,
'Content-Disposition' => 'attachement;
filename:upload_format.xlsx',
]);
}
You can give your Content-Type as desired and Content-Disposition as 'attachment' because your files are coming from S3 and you have to download it as an attachment.
$event_data = $this->ticket->where('user_id', $user_id)->first();
$data = $event_data->pdf;
$get_ticket = 'tickets/'. $data;
$file_name = "YOUR_DESIRED_NAME.csv";
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="'. $file_name .'"',
];
return \Response::make(Storage::disk('s3')->get($get_ticket), 200, $headers);

serious error with php move_uploaded_file not working

i have a serious problem with php file upload.
the problem is that the file is not moving from the tmp to the destination directory
this is my html page
<form name="f1" method="post" action="handleUpload.php" enctype="multipart/form-data">
<input type="file" name="htmlfile">
<input type="submit">
</form>
and here is my PHP page handleUpload.php,
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$arrayKeys=array_keys($_FILES['htmlfile']);
foreach($arrayKeys as $s)
echo $s ." : ".$_FILES['htmlfile'][$s]." <br>";
$name = $_FILES['htmlfile']['name'];
$size = $_FILES['htmlfile']['size'];
$tempName= $_FILES['htmlfile']['tmp_name'];
list($filePureName, $ext) = explode(".", $name);
$valid_formats = array("jpg","png", "gif", "bmp","rar","zip");
$fileObject=fopen($tempName,"r") ;
echo "test Text" . fgets($fileObject) ."</br>";
fclose($dstFile) ;
if($_FILES["htmlfile"]["error"] != 0 ) {
echo "file error with code " .$_FILES["htmlfile"]["error"];
}
if( is_uploaded_file($tempName)){
echo "<br> upladed to the tmp directory ";
move_uploaded_file($_FILES["htmlfile"]["tmp_name"],"./".$_FILES["htmlfile"]["name"]) ;
//move_uploaded_file($_FILES["htmlfile"]["tmp_name"],"upload/".$_FILES["htmlfile"]["name"])
}
}
else{
echo "you must visit the HTML upload page first";
}
the output i get is
name : numerical_hw1.rar
type : application/octet-stream
tmp_name : /tmp/phpK7Gmmf
error : 0
size : 34642
test TextRar!Ïs WÅt K„Á &–Gá#3& numerical_hw1\hw1_q1\numerical_hw1.cpp°¸ EÌÌý•½¦~g†¡¹[•Í…Àk#€Qu{Q|0a®'#ÆàM¹%_ûánšF“Q‘Á®ÞÛÅ€ÁEq'‰\—ç9yq%Páðà;áy¹‰ùLx_,Xrh»qüÙ‰ÐO‰ †3JI²†Žc÷“4ˆ ‰‡oɲE³*[⦆sÓè¤Í~·Ö”?ø‘ŒK6"Á¦æF,¼JÇ1rê¼´…BžT5$_sôJäļ†Å$ý˦A:`ë5kέ'3_„}ªœRijÅ3ÎÜøsÛV:÷5ËΰãÚÓžõÌÚK¦œñÕ÷ÚßýT­vÙäÓ
upladed to the tmp directory
the problem is that the file is not moved to the current directory nor to the "upload" directory -of course when it was alone and not commented- !!
as you can see the file is uploaded successfully to the tmp directory and i have open it, and read a line from it. and also i have checked it with the is_uploaded_file function and it pass that check.
i have carefully read php file upload topics from many sites, and found nothing is missing in both php and html !!
the folder permission is 755.
i should mention here that file uploading was working before recently, and i am sure that no body has changed or modified the php.ini file.
Any Help Please?? what should i do?
after exploring the server carefully i found that my website has been hacked, and the hacker upload a hack file !
but really i don't know what to do now and also i cant estimate the damage size caused by that hacker so Any Suggestion ?!!!!
Try that:
$pathDestino=$_SERVER['DOCUMENT_ROOT'] . "\\xxx\\upload\\" . $_FILES["htmlfile"]["tmp_name"];
$tmp_name=$_FILES["htmlfile"]["tmp_name"];
move_uploaded_file($tmp_name, $pathDestino);

Web-hosted file authorization

Im using a PHP based login authentication mechanism to allow/restrict access to some parts of my website (folder module1, module2, etc), but i have a problem with restricting access to files.
I used the documents folder (check below) to host some downloadable files. The links to those files appear in index.php (hosted in the root directory). However if for some reason a non-authorized user get the URL of the files hosed in documents he will be able to download it.
/
/documents/
/module1/
/module2/
PS: as this is an intranet website I restricted the access to documents by IPs, but there is still a small chances that someone use a PC with allowed IP address and he have the URL of the document.
Use some sort of a proxy PHP script that will serve the file for the user without giving the real source location.
The user would then see http://yourdomain.com/download.php?file=mydoc.docx
The real path is still /documents/userid/2342/mydoc.docx or what ever your structure looks like.
Then let your download.php file serve the file by:
<?php
// Validate the user here
// Set document root
$root = 'documents/userid/'.$userID.'/';
// Requested file
$file = $_GET['file'];
// Validate
if (file_exists($root . $file))
{
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".basename($file)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($root . $file));
ob_clean();
flush();
readfile($root . $file);
}
else { echo "File not found"; }
?>
See more here

How to set up download authentication?

I am looking for some sort of download authentication. I am going to give a user a link to a file, and I want to make sure only that person will get it only once. Is there a simple solution without setting up a database?
Even better: if it's possible to have an encrypted web link that will let you download a file from my FTP server just once, after that the link becomes invalid.
You can use simple php script. This script returing inputet in GET file on the brower.
After his excecution you can rename this file to random string.
this only first person download this file.
Your link get somethis like this. www.domain.tld/dir/script.php?file=./usr/123.tar.gz.
You can filename encrypt in base64 too, in this option your link is www.domain.tld/dir/script.php?file=Li91c3IvMTIzLnRhci5neg==
Script without base64:
<?php
$file = $_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
rename($file, "secret_new_filename");
exit;
}
else
{
echo 'File don\'t exist';
}
?>
And with base64:
<?php
$file = base64_decode($_GET['file']);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
rename($file, "secret_new_filename");
exit;
}
else
{
echo 'File don\'t exist';
}
?>

How to force a pdf download automatically?

Is there any way to force the user's download-manager to start a download for .PDF instead of showing the .PDF in a new window/tab?
use the download attribute inside your <a> tag
<a href="content/file.pdf" download > pdf link </a>
<a href="content/file.doc" download > doc link </a>
Set Content-Disposition in your HttpResponse header:
Content-Disposition = 'attachment; filename=filename.pdf'
This needs to be done in the server side. You can't do this at the client side.
How to do it depends on the server side language in question.
PHP:
header('Content-Disposition: attachment; filename="' . $filename . '"');
Java:
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
.NET:
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
If there's no means of any server side code which streams the PDF file, then you need to configure it at webserver level. In for example Apache HTTPD, you can place/expand a .htaccess file in the PDF folder's root with the following entry:
<Files *.pdf>
Header set Content-Disposition attachment
</Files>
or configure it globally in httpd.conf file. Similar approach exist for IIS with web.config file.
For IIS:
Put all files you want to force to download in their own folder.
Then in IIS go that folder and double click HTTP Response Headers.
Add a new header with the following info:
Name:
content-disposition
Value:
attachment
All files in that folder, when accessed, should prompt the save as dialog box for the appropriate browser.
You need to send HTTP headers ( Content-disposition ) in order to do this. You cannot do this on the client side.
.htaccess solution:
AddType application/octet-stream .pdf
<?php
header('Content-disposition: attachment; filename=filename.pdf');
header('Content-type: application/pdf');
readfile('path/to/filename.pdf');
Yes it can be done in JSP page... By giving a Download link in One JSP page on which goes to new script page...and download the PDF file as follows
DownloadPage.JSP code :-
<a href='downloadPdf.jsp?file=FILE.pdf' >Download PDF File</a>
downloadPdf.JSP code :-
<%# page import="java.util.*,java.io.*"%>
<%
File f = new File ("E:/PDFfiles/Downloads/" + request.getParameter("file") );
response.setContentType ("application/pdf");
response.setHeader ("Content-Disposition", "attachment; filename=""+request.getParameter("file")+""");
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
int bit = 256;
int i = 0;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}
}
catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
%>
Source (this is my blog): http://bloggerplugnplay.blogspot.in/2012/05/how-to-create-force-download-link-for.html
<?php
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
}
$reader = fopen($filename, "r");
$contents = fread($reader, filesize($filename));
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_end_clean();
echo $contents;
From vb asp net code found on the internet i made this simple c# download.aspx page.
You can use with the file url passed as "f" querystring parameter. (/folder/download.aspx?f=/folder1/example.pdf).
<!DOCTYPE html>
<html>
<head><title></title>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
String strRequest = "";
try
{
strRequest = Request.QueryString["f"].ToString();
}
catch
{ }
if (strRequest.Length > 0)
{
String path = Server.MapPath(strRequest);
System.IO.FileInfo File = new System.IO.FileInfo(path);
if (File.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + File.Name);
Response.AddHeader("Content-Length", File.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(File.FullName);
Response.End();
};
}
}
</script>
</head>
<body></body>
</html>