My download.php script sends a corrupt file - php

I am having difficulty working out my download.php script. The customer gets a unique download link generated from my database and when they click it on it is meant to send them the file from my server. Only in my case the zip file is always corrupt and bigger then the original file. Original file is 68KB and the downloaded file ends up being 90KB.
Here is my code that sends the file to the browser:
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]";
$post_id = $wpdb->get_results("SELECT transaction_id FROM slx_jomsocial_plugin_orders WHERE (transaction_id ='". $tx ."' and unique_code='". $token ."')");
$rowCount = $wpdb->num_rows;
if($rowCount==1){
$name="Unzip_First_Video_Embedding.zip";
$file_url=$actual_link."/jomsplugins/".$name;
header("Content-type: application/x-file-to-save");
header("Content-Disposition: attachment; filename=".$name);
readfile($file_url);
echo "<h1>Thank you ".$name=$_SESSION['s_name']." For downloading the plugins.</h1><br />";
}else{
echo "<h1>You are not permitted to downlaod, Please purchase plugin first.</h1> <br /><div style=\"margin-left: 25%;margin-top: 1%;\">Click Here</div>";
}
?>
What am I doing wrong here?
UPDATE:
I have been experimenting with the script but still my files come out corrupted (Unzipping them gives a .cpgz file). Here is my current script now:
<?php
$actual_link = "http://$_SERVER[HTTP_HOST]";
$post_id = $wpdb->get_results("SELECT transaction_id FROM slx_jomsocial_plugin_orders WHERE (transaction_id ='". $tx ."' and unique_code='". $token ."')");
$rowCount = $wpdb->num_rows;
if($rowCount==1){
// set example variables
$filename = "Unzip_First_Video_Embedding.zip";
$filepath = $actual_link."/jomsplugins/";
// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
ob_end_flush();
ob_clean();
flush();
#readfile($filepath.$filename);
ob_clean();
flush();
exit;
}

Related

Appearance of user id when downloading to the file

There's this code which I have
function pushfile(&$file) {
header_remove();
if (isset($file["type"])) header('Content-Type: '.$file["type"]);
if (isset($file["name"])) header('Content-Disposition: attachment; filename="'.$file["name"].'"');
print $file["name"];
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: ");
echo $file["content"];
exit;
$h=fopen($filename,"r");
$content = fread($h, filesize($filename));
fclose($h);
$file["type"] = "application/"; //
$file["name"] = $real_filename;
$file["content"] = $content."*".$context['user']['id'];
pushfile($file);
This ID number was well placed into the downloaded file, but it disappeared after converting it (e.g. from pdf to epub). Is there a good solution for that?

How to upload the image into folder

I need to push the image into a folder, here image will generated in for loop according to my query, for each and every loop in need push the $img to a specific folder.
If it's possible..? Kindly give some solution.
<?php
for($i=0;$i<10;$i++)
{
$sql_sub = select_query("select DESPHOT from photo where photoid = ".$i."");
$img = $sql_sub[0][0]->load();
header("Content-type: image/pjpeg");
echo $img;
}
?>
You needs to use file_put_contents function for it.
Try
<?php
for($i=0;$i<10;$i++)
{
$sql_sub = select_query("select DESPHOT from photo where photoid = ".$i."");
$img = $sql_sub[0][0]->load();
$target_folder = 'test';
$filename = $i.'.jpg';
$new_saved = file_put_contents($target_folder.'/'.$filename, $img);
echo "Picture save as ".$new_saved;
}
?>
Note You have to set 0777 permission to target_folder if you are using UNIX/LINUX.
Above code is not tested. What $sql_sub[0][0]->load(); do?
Your going to need move_uploaded_file($tmp_path, $newpath)
more info here: http://php.net/manual/en/function.move-uploaded-file.php
// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $file_type");
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $file_size);

URL Redirect Masking in PHP

I have to show a download link on my site linking it to a file hosted on another domain. I am using the following approach.
1) Pick up the actual URL from the database
$fileDownloadLink = "http://whatever.com/thefile.docx";
2) Encode the url and pass it as parameter to download.php
$shortUrl = base64_encode($fileDownloadLink);
Download Please
3) Download.php decodes the passed string and try reading the file.
<?php
$str = $_GET["session"];
$path = base64_decode($str);
$mm_type="application/octet-stream";
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.basename($path).'"');
header("Content-Transfer-Encoding: binary\n");
readfile($path);
exit();
?>
But I am getting this error from download.php
Not Acceptable!
An appropriate representation of the requested resource could not be
found on this server. This error was generated by Mod_Security.
Please help.
You may just redirect in download.php;
$str = #$_GET["session"];
$path = base64_decode($shortUrl );
header("Location: $path");
exit();

PHP headers putting everything that was output to screen into downloaded file

I have the following PHP code using headers to download a file from the server:
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
This code works fine, however I have it in a file with the HTML form and it is ran using an if isset all of the HTML code is placed in the file, as well as anything I echo out in PHP; and the data I actually want in the file is there at the end.
I can't figure out what in the headers is causing it to write everything that is on screen to the file when downloaded. The file on he server isn't changed and is how it should be.
Thanks for any help.
Heres all the code...
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"><br>
Order Number: <input type="number" name="orderNo" size="10"/>
<input type="submit" name="Download" value="Download" />
</form>
</body>
</html>
<?php
if(isset($_POST['Download'])){download();}
function download()
{
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('amazondb', $conn);
$result = mysql_query("SELECT ID, PurchaseDate, BuyerName, ShipCity, ShipState, ShipPostalCode, ShipCountry,
ShipAddress1, ShipAddress2, ShipAddress3 FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if($row['ID']==($orderNo))
{
echo "Hello";
fwrite($file, $row['BuyerName'].PHP_EOL .$row['ShipAddress1'].PHP_EOL .$row['ShipAddress2'].PHP_EOL .$row['ShipAddress3'].PHP_EOL .$row['ShipCity'].PHP_EOL .$row['ShipState'].PHP_EOL .$row['ShipPostalCode'].PHP_EOL .$row['ShipCountry'].PHP_EOL);
}
}
fclose($file);
$file = 'Order.txt';
header("Cache-Control: private");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
}
else{echo "Please enter a valid Order Number"; echo $orderNo;}
}
move this code at very begin of file, so you will have:
<?php
if (your condition to output file) {
$file = 'Order.txt';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($file);
die();
}
the rest of your file....
another solution, at the very top of file add:
<?php
ob_start() or die('Cannot start output buffering');
... your page
and just before the first header add:
$file = 'Order.txt';
ob_end_clean();
header("Cache-Control: public");
...
readfile($file);
die();

Stream binary file from MySQL to download with PHP

I have Excel spreadsheets stored in a MySQL table longblob field. I need to retrieve this data and then stream it to the user as a downloadable file, preferably without writing it to disk first.
Possible?
Edit - Eh, just figured it out... Posted in answer below.
function getfile($blockid)
{
global $msa_db;
$sql = "select filename, filedata from blocks where blockid = '$blockid'";
$query = mysql_query($sql, $msa_db);
$result['filename'] = mysql_result($query,0,0);
$result['filedata'] = mysql_result($query,0,1);
return $result;
}
function download($fileinfo)
{
$file = base64_decode($fileinfo['filedata']);
header("Cache-Control: no-cache private");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.$fileinfo['filename']);
header("Content-Type: application/vnd.ms-excel");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. strlen($file));
echo $file;
exit;
}
$fileinfo = getfile($blockid);
download($fileinfo);
Just got the solution
http://www.codeproject.com/Articles/831185/CREATE-DOWNLOAD-ZIP-FILE-USING-PHP
$data = base64_decode($data);
header("Cache-Control: no-cache private");
header("Content-Description: File Transfer");
header("Content-disposition: attachment; filename='".$identifier.".zip'");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. strlen($data));
header("Pragma: no-cache");
header("Expires: 0");
ob_clean();
flush();
echo $data;

Categories