PHP - Php Download From My Sql Database
Hi Guys,
I'm putting together a project which requires members of a site to upload files(mostly word files) into a mysql db. I can get the files uploaded successfully but when it comes to downloading them i do have a bit of trouble. When i click on the download link i just get a file called 'download.php' instead of the actual file in the database. I have been working on this link for the past two weeks and think maybe its time for some help, here's my code if you wouldn't mind having a look? upload.php: <?php session_start(); ?> <html> <head> <link href="default.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> <!-- start header --> <div id="header"> </div> <div id="menu"> <ul> <li><a href="#">Home</a></li> <li><a href="member.php">Member</a></li> <li><a href="logout.php">Log Out</a></li> </ul> </div> <div id = "content"> <form method="post" enctype="multipart/form-data"/> <input type="hidden" name="MAX_FILE_SIZE" value="2000000"/> <input name="userfile" type="file" id="userfile"/> <input type="submit" name="upload1" id="upload1" value=" Upload "/> </form> </div> <?php if(isset($_POST['upload1']) && $_FILES['userfile']['size'] > 0) { $connect = mysql_connect ("localhost","root","") or die ("Couldn't connect!"); mysql_select_db("upload") or die ("Couldn't find db"); $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = "INSERT INTO upload (name, size, type, content ) ". "VALUES ('$fileName', '$fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); echo "<br>File $fileName uploaded<br>"; } ?> <div id = "nav"> </br> <a href = "upload.php"><img src = "images\add-itemGreen.gif"/></a><b>Upload</b></br> </br> <a href = "download.php"><img src = "images\download.gif"/></a><b>Download</b></br> </br> <a href = "discussion.php"><img src = "images\chat-.gif"/></a><b>Discussion Board</b></br> </div> <div id="footer"> </div> </body> </html> View.php: <?php ini_set('display_errors', E_ALL); //include "open_db.inc"; $connect = mysql_connect ("localhost","root","") or die ("Couldn't connect!"); mysql_select_db("upload") or die ("Couldn't find db"); $sql = "SELECT * FROM upload "; $sql .= "ORDER BY name ASC"; $result = mysql_query($sql, $connect); $rows = mysql_num_rows($result); echo "<table>\n"; echo " <tr>\n"; echo " <td>id</td>\n"; echo " <td>name</td>\n"; echo " <td>type</td>\n"; echo " <td>size</td>\n"; echo " <td>Description</td>\n"; echo " <td> </td>\n"; echo " </tr>\n"; while ($rows = mysql_fetch_object($result)) { echo " <tr>\n"; echo " <td>$rows->id</td>\n"; echo " <td>$rows->name</td>\n"; echo " <td>$rows->type</td>\n"; echo " <td>$rows->size</td>\n"; echo " <td>" . stripslashes($rows->description) . "</td>\n"; echo " <td>( <a href='download.php?id=$rows->id'>Download</a> )</td>\n"; echo " </tr>\n"; } mysql_free_result($result); mysql_close($connect); ?> download.php: <?php ini_set('display_errors', E_ALL); if (isset($_GET['id'])) { $id_files = $_GET['id']; // include "open_db.inc"; $connect = mysql_connect ("localhost","root","") or die ("Couldn't connect!"); mysql_select_db("upload") or die ("Couldn't find db"); $sql = "SELECT id, name, type, size, content FROM upload WHERE id=$id"; $result = @mysql_query($sql, $connect); $dataT = @mysql_result($result, 0, "bin_data"); $name = @mysql_result($result, 0, "name"); $size = @mysql_result($result, 0, "type"); $type = @mysql_result($result, 0, "size"); header("Content-type: $type"); header("Content-length: $size"); header("Content-Disposition: attachment; name=$name"); header("Content-Description: PHP Generated Data"); header("Content-transfer-encoding: binary"); echo $dataT; } else { echo 'id_files not set'; } ?> I'm thinking that it could be something to do with the bin_data on the download.php page. Any help would be great. Thanks Similar TutorialsHi PHP freaks!!
I have manage to make a script to upload file in database and its working. I will share to you the codes so for other viewers and readers to use also.
if($result){ if($_FILES['LRCard']['name'] != ""){ $filename = $_FILES['LRCard']['name']; $ext = strrchr($filename,"."); $LRCardname = $student_id; $LRCardname .="_". $filename; if($ext ==".jpg" || $ext ==".jpeg" || $ext ==".JPG" || $ext ==".JPEG" || $ext ==".gif" || $ext ==".GIF"){ $size = $_FILES['LRCard']['size']; if($size > 0 && $size < 5000000){ $archive_dir = "LRCards"; $userfile_tmp_name = $_FILES['LRCard']['tmp_name']; if(move_uploaded_file($userfile_tmp_name, "$archive_dir/$LRCardname")){ /* if LRC is successfully uploaded then LRC is stored in database. */ mysql_query("update student_information set LRCard='$LRCardname' where student_id='$student_id'", $link_id); $flag = "success"; if(mysql_error()!=null){ die(mysql_error()); } } else{ if(file_exists('LRCard/' . $LRCardname)) { unlink('LRCards/' . $LRCardname); } rollbackData(); } } else{ if(file_exists('LRCards/' . $LRCardname)) { unlink('LRCard/' . $LRCardname); } rollbackData(); die("You can upload LRCard of 5 MB size only. Please, try again."); } } else{ if(file_exists('LRCards/' . $LRCardname)) { unlink('LRCards/' . $LRCardname); } rollbackData(); die("You can upload LRCard of .jpg, .jpeg, .gif extensions only. Please, try again. "); } } } else{ $flag="error"; } if($flag == "success"){ mysql_query(" COMMIT "); $flag="success"; if(mysql_error() != null){ die(mysql_error()); } }Now, my problem is how to make a Php script to DOWNLOAD this uploaded file considering the 1. file path 2. file name 3. file extension. 4. student_id (to determine the specific file from a specific student) My plan is to make a download button which hyperlink to download.php and after clicking that button the specified file to a specific student id will automatically be downloaded by the browser. I have a Joomla website having one folder for audio files in it and their links are saved in database. Now I want to show two calendars to the user at front end, so that they can choose that from when to from he want to download the audio files? for e.g he can select june-2-2014 in one calendar and august-2-2014 in second calendar, now on clicking download button the files residing between the two specific dates must get archived into one zip file and then start downloading... i have a reference link for creating a zip and downloading the zip :http://coursesweb.ne...-archive-php_cs now i am stuck that how to get the selection of user from calendar , save it into the array , and from the array get the files from the folder matching the array indexes and then zip , download them. please tell me how to achieve this task ? Hi Guys, I have been contacted by a client who wants me to develop an application which performs the following functionality: Lets say the domain name is xyz.com . We provide an email of our domain to the person who signup on our website for our services. Lets say the email that is given to the customer is email@xyz.com The client wants to built PHP application in which if an email is sent to email@xyz.com it gets downloaded and is stored in the MySql Database. After the download there is going to be a set of algorithms which will decided whether to forward this email to the client or not on his email address. I have no idea how to accomplish this functionality. Any suggestions would be appreciated. Thanks Sadan Masroor. Hi, this is my first post:) pretty sure i will be posting here in the future. Anyway i am having trouble with a php script which downloads a file from a mysql database. This php script works for text files and should work for most files from what i understand. When downloading a text file, the whole file is downloaded from the server. When downloading an mp3 file, only 16kb are downloaded and the file does not play. When looking at the data in the database, it displays that the full file is there (correct amount of bytes, so there is nothing wrong with my upload php script). Does anyone have any suggestions as to what I can change to make this work? Code: [Select] <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database $link=mysql_connect('localhost', 'root', ''); @mysql_select_db('filemgr') or die ("<p>Could not connect to mysql!</p>"); $id = $_GET['id']; $query = "SELECT name, type, size, content " . "FROM upload WHERE id = '$id'"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($result); header("Content-length: $size"); header("Content-type:$type"); header("Content-Disposition: attachment; filename=$name"); echo $content; mysql_close($link); exit; } ?>
Basically I would like to place a link on my website and have the user download a file, but rather than just right clicking and choosing save target as, the link must be clicked, on the next page the file is fetched and then the client can download the file. How would I go about setting this up please? I have made a Php program that downloads an Inno setup installation file for installing a program. However, if I for one or another reason want to make a new download of the same Inno setup installation file, the previous file will still be found in the Download folder. Each of the downloads get a number in parenthesis, setup(1), setup(2), setup(3) etc. However, I wondered if it is posible to erase the previous file in the same process as I download a new one, so that however many downloads I do, there will all the time only be one occurence of this file in the Download folder. The download code is as follows: $exe = "Inno script/Test_setup.exe"; header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"Test_setup.exe\""); header("Content-Length: " . filesize($exe)); readfile($exe); Thanks in advance. Sincerely
Hi,i will like to know how to put a file on my website for people to download..please how should i go about it? thanks merry christmass How do I make it so when a user clicks download, it will download the image from the path to their computer? I've written the following code: Code: [Select] <?php echo '<img src="Sheph.png" />'; function Wad(){ if (file_exists("Sheph.png")) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename("Sheph.png")); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize("Sheph.png")); ob_clean(); flush(); readfile("Sheph.png"); exit; } } Wad(); ?> What I want to do is show the image AND show a file download window. The problem is that it shows the download window but the image doesn't appear. and if I comment the function and keep the echo part only,the image appears normally. What's wrong ? I have a small program that is to be used to export data from some MYSQL tables into an Excel spreadsheet. It does the export successfully, the first pass, but each subsequent download selection causes the browser to display the html code as text to the browser. If I disable the excel output, the page redraws successfully un subsequent requests. The header definition I have is ias follows: Code: [Select] $FileInfo = pathinfo(filename); // fix for IE catching or PHP bug issue header("Pragma: public"); header("Expires: 0"); // set expiration time header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // browser must download file from server instead of cache // force download dialog header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-type: application/x-msexcel"); header("Content-Type: application/download"); // use the Content-Disposition header to supply a recommended filename and // force the browser to display the save dialog. if ($download_filename == "") $download_filename = "download.xlm"; header("Content-Disposition: attachment; filename=".$download_filename.";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); @readfile($filename); I did not setup this header, because to be honest, these things confuse the heck out of me. Can anyone see what may be wrong with this? Can you give me some suggestions? I can post more of the code if needed, but i believe that this is the area of interest for this issue. Thanks in advance. I put this in the wrong forum and copied it to this one. I apologize ahead of time for the double post. (quote author=radi8 link=topic=333351.msg1569942#msg1569942 date=1305654626) One more question for you all: We just installed a new Linux Ubuntu V 11.04 server with LAMP (Apache2, PHP 5.3.x, MySQL 5.1.4, etc...) all out of the box stuff. I developed (locally) and app where I am exporting some data from MySQL, putting it into a spreadsheet and then sending the Excel file to the client. This all worked fine in my dev setup. BUT... (you know whats coming next) after deploying the app to the new Web Server, when I attempt to export the data, I am successfully creating the Excel file but rather than opening the download dialogue box, the data is being read and sent to the browser window as text! As I mentioned before, this is a new web server, so there may be something missing on the Apache2 setup, or my code may just be crap. Either way, my head hurts and cannot find out what is happening. Here is my header type configuration: Code: [Select] <?php function save($filename, $download=false, $download_filename="") { if (!$download) { return $this->domXML->save($filename); } elseif ($this->domXML->save($filename)) { $realFileInfo = $_SERVER['DOCUMENT_ROOT'].'/truck/admin/export/'.$download_filename; $FileInfo = pathinfo($filename); ob_end_clean(); // fix for IE catching or PHP bug issue header("Pragma: public"); header("Expires: 0"); // set expiration time header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); header('Cache-Control: no-store, no-cache, must-revalidate'); // HTTP/1.1 header('Cache-Control: pre-check=0, post-check=0, max-age=0'); // HTTP/1.1 header ("Pragma: no-cache"); //header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // browser must download file from server instead of cache // force download dialog header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header('Content-Type: application/vnd.ms-excel;'); // This should work for IE & Opera header("Content-type: application/x-msexcel"); header("Content-Type: application/download"); // use the Content-Disposition header to supply a recommended filename and // force the browser to display the save dialog. if ($download_filename == "")$download_filename = "download.xls"; //header("Content-Disposition: attachment; filename=".$download_filename.";"); header("Content-Disposition: attachment; filename=".$realFileInfo.";"); header("Content-Transfer-Encoding: binary"); //header("Content-Length: ".filesize($filename)); header("Content-Length: ".filesize($realFileInfo)); //@readfile($filename); @readfile($realFileInfo); return true; } return false; } ?> I added a screen cap for you to see the output. Can you see anything wrong? Hello! I'm making a interface in a website do manage files in a ftp hosted on other server. I'm using the function ftp_get() to download a file but I've tried different aways but I dosent seem do be able to download the file directly from the FTP server do the user the only way it works is if I download the file to the website server first then to the client. Is there any way that I can download the file directly to the user without have to hosting it permanently on the website server? Thank you i am trying to let users download images, but it seems to only be working for only a png image. i've tried .txt, word, and mp3. here is my code for getting the path of the file: // get full file path (including subfolders) $file_path = $fileName; find_file(BASE_DIR, $fname, $file_path); if (!is_file($file_path)) { die("File does not exist. Make sure you specified correct file name."); } these other files that i am getting, are in the same folder as the image. the error that i am getting, is "File does not exist. Make sure you specified correct file name." here are the allowed extensions of the files: Code: [Select] $allowed_ext = array ( // archives 'zip' => 'application/zip', // documents 'pdf' => 'application/pdf', 'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', // executables 'exe' => 'application/octet-stream', // images 'gif' => 'image/gif', 'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', // audio 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav', // video 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo' ); I have the following code, but wish to allow admin members to download the short WMV video without having the page reload. My page can have anything to to 20 videos on the page. I can place a button there but how to I get the video files to download and not play when clicked. Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Admin</title> <link href="style2010.css" rel="stylesheet" type="text/css"> </head> <body style="width:1000px; width: 50%; margin-left: auto; margin-right: auto;"> <div style="width:1000px; padding-right: 3px; padding-left: 3px; height:100%; min-height: 500px;"> <div align="center"><h2>Admin</h2><br /></div> <div style="float: left; padding-left: 5px;"> <form name="delete" method="post" action=""> <div align="center" style="float: left; padding: 0 10px 50px 10px;"> <object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" id="MediaPlayer1" standby="Loading Windows Media Player components..." width="300" height="300"> <PARAM NAME="url" value="67.wmv" /> <param name="src" value="67.wmv" /> <param name="showcontrols" value="true" /> <param name="autostart" value="false" /> <!--[if !IE]>--> <object type="video/x-ms-wmv" data="67.wmv" width="300" height="300"> <param name="src" value="67.wmv" /> <param name="autostart" value="false" /> <param name="controller" value="true" /> </object> <!--<![endif]--> </object> <br />67.wmv<br />Delete above file? <input name="67---wmv" type="checkbox" value="delete"> </div> <br clear="all"/><input type="submit" name="Delete Selected" value="Delete Selected"> </form> <br /><br /> </div> </div> <br style="clear:both" /> </body> </html> Hi all, I'm trying to make a PHP script that downloads a file off a remote FTP server and serves the file to the visitor with a limited download speed. Right now I'm using fopen() like this: Code: [Select] $path = "ftp://".$username.":".$password."@".$server."/"; $fullPath = ($path.$fileName); $speed = 400; // 400 kb/s download rate header("Cache-control: private"); header("Content-Type: application/octet-stream"); //header("Content-Length: ".filesize($fullPath)); header("Content-Disposition: filename=\"".$fileName."\""); flush(); $fd = fopen($fullPath, "r"); while(!feof($fd)) { echo fread($fd, round($speed*1024)); flush(); sleep(1); } fclose ($fd); The file does download but with the wrong speed (8kb/s), does anyone know why? When I run the same code with a local file instead of a file on FTP it works fine and downloads at the speed I set it to.. Thanks Hi, I don't want to reveal the real download link to my users for some reason, so I place the file here, for example: http://www.domain.com/download/secure-file.exe Now I want to write a simple php code and link to this address, for example: http://www.domain.com/download/download.php Now this php script read that file and send it to user, without revealing the real file location to user. Of course there is no resume download now, but I don't care. Anyone knows a code snippet for that, or can help me to the right position? I am a newbie in PHP. Thank you. I created this php class which recieves an sql query from flash and then produces a csv file for download. The code in its current form produces a csv file on the server. However, I want it to save on the client computer with a 'Save As' dialog box. I am testing on localhost. Here is the class: <?php class CSVExport { public function __construct() { require_once 'Zend/Date.php'; require_once 'DatabaseConnection.php'; } public function exportCSV($query) { $result = mysql_query($query); $fname = 'CSVFile.csv'; $headers = array(); $rowArray = array(); $numFields = mysql_num_fields($result); for ($i = 0; $i < $numFields; $i++) { $headers[] = mysql_field_name($result , $i); } $fp = fopen($fname, 'w'); if ($fp && $result) { header('Content-Type: application/csv'); header('Content-Disposition: inline; filename='.$fname); fputcsv($fp, $headers); while ($thisrow = mysql_fetch_row($result)) { fputcsv($fp, $thisrow); } readfile($fname); fclose($fp); } die; } } Thanks Hello, I made that script for previewing all the images in the directory: Code: [Select] $dir = "../images"; $images = glob($dir . "*.jpg"); foreach($images as $image) { echo $image; } Now what i would like to do is to put checkbox to every image. And when i press download button, all the selected images are downloaded. (as .zip, .rar) Thank you very much for your help On my website, I have a download folder containing several files ranging in size from 6Mb to 700Mb. Users have no problems downloading the smaller files but often have problems downloading the files over 500Mb. We also have an archive of all the files located on a sub-domain on a server in England. Those users that are having problems downloading large files from the main site usually have no problem downloading the large files if we send them the URL for the archive. I've added a button that calls the following script so the users can choose where to download from but have no idea how to code the script. Here's what I've tried: // ukdloader script <?php $php_scripts = '../../php/'; require $php_scripts . 'PDO_Connection_Select.php'; require $php_scripts . 'GetUserIpAddr.php'; function ukdloader($l_filename=NULL) { $ip = GetUserIpAddr(); if (!$pdo = PDOConnect("foxclone_data")) { exit; } if( isset( $l_filename ) ) { echo <a href="http://foxclone.org/".$l_filename"> /* This is the archive site */ $ext = pathinfo($l_filename, PATHINFO_EXTENSION); $stmt = $pdo->prepare("INSERT INTO download (address, filename,ip_address) VALUES (?, ?, inet_aton('$ip'))"); $stmt->execute([$ip, $ext]) ; $test = $pdo->query("SELECT id FROM lookup WHERE INET_ATON('$ip') BETWEEN start AND end ORDER BY start DESC, end DESC"); $ref = $test->fetchColumn(); $ref = intval($ref); $stmt = $pdo->prepare("UPDATE download SET ref = '$ref' WHERE address = '$ip'"); $stmt->execute() ; } else { echo "isset failed"; } } ukdloader($_GET["f"]); exit; Thanks in advance. How can i create a download page that allows you to download *.php files on your server. Because if you just click on it it sends you to the page but I just want it to download it. Also i want to be able to do that on the .jpeg files. Thanks Jragon |