PHP - Stream File Download
The other day I noticed someone had post something like this, well this was actually the solution to the problem. But it got me thinking about a project of mine that I am working on and the need to pump out a downloadable file. We are storing most of the files in a database using base64 encoding the 2 key types of files we are storing are images and PDF's mostly pdf's anyway where I am wanting to go with this is, is there anyway to take the base64 encoded file and get it to download through this, or am I tackling the idea in the wrong way?
<?php $filename = 'somename.txt'; //this would obviously be changed according to the file type we would output $data =<<<DATA I know my data would go here for the given file once decoded. DATA; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $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: ' . strlen($data)); echo $data; ?> Similar TutorialsI'm trying to copy an existing file using a php script, run on the command line. I've tried copy() and also a script from the comments on copy() http://www.php.net/manual/en/function.copy.php#102320 No matter how I try to open the file I get " failed to open stream: No such file or directory". I tried changing the name of the file, and the ext, and both. The file does exist, and if I run cp old new, the file gets copied fine. Current code Code: [Select] <?php $source = '/www/documents/myfile.pdf'; $destination = '/www/documents/mypdf.pdf.bak'; copy($source, $destination); ?> Warning: copy(/www/documents/myfile.pdf): failed to open stream: No such file or directory in /www/cron/historic.php on line 3 Code: [Select] ~$ ls /www/hua/compucom113dev/client/documents/ myfile.pdf ~$ cp /www/documents/myfile.pdf /www/documents/myfile.pdf.bak ~$ ls /www/hua/compucom113dev/client/documents/ myfile.pdf myfile.pdf.bak I had chmod in the script at one point to make sure the directory had the permissions needed but it didn't make a difference so I removed it. I can add it back if someone can help explain what to set it to. I was doing 0777 then back to 0755 at the end. Hello, this is my first post I hope you guys can help me out here, basically whats going on is I declare a variable "$diree" then I insert it in a function but its not getting recognized, here is the code: $institutea "some directory"; $dire = str_replace(" ","-",$institutea); # SETTINGS $max_width = 110; $max_height = 130; $per_page = 5; $page = $_GET['page']; $has_previous = false; $has_next = false; function getPictures() { global $page, $per_page, $has_previous, $has_next; if ( $handle = opendir($diree.'/') ) { // done changes here $lightbox = rand(); ?><table border="1"><tr><td> <form action="pro.php" method="post"> <?php echo "<ul id='pictures'>"; $count = 1; $skip = $page * $per_page; if ( $skip != 0 ) $has_previous = true; while ( $count < $skip && ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) $count++; } $count = 1; while ( $count < $per_page && ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) { if ( ! is_dir($dire .'/') ) { // done changes here mkdir($dire .'/'); // done changes here } if ( ! file_exists($dire .'/'.$file) ) { makeThumb( $file, $type ); } echo '<li>'; echo '<img src="'.$dire .'/'.$file.'" alt="" / width="110" height="110"><br/><input type="checkbox" name="food[]" value='.$file.'>'; // done changes here echo '</li>'; $count++; } } echo '</ul>'; ?> </td></tr><tr><td><div align="center"><input type="submit" value="Add"></div></td></tr> </tr></table></form> <?php while ( ($file = readdir($handle)) !== false ) { if ( !is_dir($file) && ($type = getPictureType($file)) != '' ) { $has_next = true; break; } } } } function getPictureType($file) { $split = explode($dire .'/', $file); $ext = $split[count($split) - 1]; if ( preg_match('/jpg|jpeg/i', $ext) ) { return 'jpg'; } else if ( preg_match('/png/i', $ext) ) { return 'png'; } else if ( preg_match('/gif/i', $ext) ) { return 'gif'; } else { return ''; } } function makeThumb( $file, $type ) { global $max_width, $max_height; if ( $type == 'jpg' ) { $src = imagecreatefromjpeg($file); } else if ( $type == 'png' ) { $src = imagecreatefrompng($file); } else if ( $type == 'gif' ) { $src = imagecreatefromgif($file); } if ( ($oldW = imagesx($src)) < ($oldH = imagesy($src)) ) { $newW = $oldW * ($max_width / $oldH); $newH = $max_height; } else { $newW = $max_width; $newH = $oldH * ($max_height / $oldW); } $new = imagecreatetruecolor($newW, $newH); imagecopyresampled($new, $src, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH); if ( $type == 'jpg' ) { imagejpeg($new, $dire .'/'.$file); } else if ( $type == 'png' ) { imagepng($new, $dire .'/'.$file); } else if ( $type == 'gif' ) { imagegif($new, $dire .'/'.$file); } imagedestroy($new); imagedestroy($src); } ?> Hey all, I viewed this tutorial and the guy used $_SERVER['DOCUMENT_ROOT'] to reference a view layout for his specific index file. So I tried to imitate and did exactly what he did, but for me I got the following error: Code: [Select] Warning: include(/Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php) [function.include]: failed to open stream: No such file or directory in /Users/jmerlino/Sites/diet/index.php on line 22 Warning: include() [function.include]: Failed opening '/Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php' for inclusion (include_path='.:/usr/lib/php') in /Users/jmerlino/Sites/diet/index.php on line 22 This is the php code that is causing this error: include($_SERVER['DOCUMENT_ROOT'].'/'.'diet/views/layouts/'.$controller.'.php'); I'm not sure why it's going to: /Users/jmerlino/Sites/mark/public/diet/views/layouts/shop.php instead of: /Users/jmerlino/Sites/diet/views/layouts/shop.php Thanks for any response Is there a way I can readily stream-process a compressed XML file in PHP? Something like this NON WORKING example: Code: [Select] $reader = new XMLReader(); $reader->open(bzopen($planet_file,"r")); while ($reader->read()) { ... See also http://php.net/manual/en/xmlreader.open.php Dear PHPFreak members, I have been searching a solution for serving a file download via my website. The file to be downloaded is actually on a remote server. What i need is a code that serves as a download medium without actually downloading the file to my web server. Something like masking file url Can anyone help me with it ??? Have been trying this since days. But no solution till date. Hello I already know this is possible with php <?php $file = 'monkey.gif'; 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); exit; } ?> But I am wondering is it possible to just send over a string of data stored in like $data and create a file clientside (nothing server side). So i'm guessing readfile() has to be replaced with something My images generator comprises
an array of image names extracted form an images table from a database using a select statement
a random number generator,
and a string that builds the correct pathname for the selected file.
To select one of the images for display, i generate a random number between 1 and the length of the array.
Though the generator is working, I noticed one of the random numbers is throwing up this error:
Warning: getimagesize(images/): failed to open stream: No such file or directory in
An inspection of the array reveals 2 array elements (representing my number of images) but one array element is NULL ( the first entry in the banner table
image_generator.php
require_once('connection.inc.php'); $sql = 'SELECT `filename` FROM banner'; $result = $mysqli->query($sql, MYSQLI_STORE_RESULT) or die(mysqli_error()); $row = $result->fetch_array(MYSQLI_ASSOC);//an array of image names $count = $result->num_rows; for ($i = 1; $i <= $count; ++$i) { $row[$i] = $result->fetch_array(MYSQLI_ASSOC); } $i = rand(1, $count); //a random number generator, //The random number is used in the final line to build the correct pathname for the selected file. $selectedImage = "images/{$row[$i]['filename']}"; if (file_exists($selectedImage) && is_readable($selectedImage)) { $imageSize = getimagesize($selectedImage); }var_dump($row) array (size=1) 'filename' => string 'ginsomin2.jpg' (length=13) nullRANDON IMAGE DISPLAY require_once 'image_generator.php'; <div id="banner" class="wrapper clearfix"> <img src="<?php echo $selectedImage; ?>" alt="banner"> </div>Kindly advice how i may proceed from here? Thanks. 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 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 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 ? Hey! I am trying to get a database table of users but am running into the error: Warning: file_get_contents(http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 500 in get_user_from_parameter(nabble:utilities.naml:890) - <n.get_user_from_parameter.as_user_page.do/> - public v in C:\xampp\htdocs\website4js\stanford\loadUsernames.php on line 32 I have looked it up and it may be a security thing...The urls I am getting are http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=user_nodes&user=68583 but the error adds an nodes& part that screws it up. Any way around this? Code: [Select] <?PHP $maxPage = 0; $mainPage = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136"; $mainContent = file_get_contents($mainPage); $pattern = "/(?<=\"Page )\d\d+/"; preg_match_all($pattern, $mainContent, $pageNumb); //find the max page for($i=0;$i<sizeof($pageNumb[0]);$i++) { if($pageNumb[0][$i] > $maxPage) { $maxPage = $pageNumb[0][$i]; } } //echo('Max page is: '.$maxPage.'\n'); //Get an array of all the pages $pages = array(); for($i=1;$i<$maxPage;$i++) { $pages[$i] = "http://protege-ontology-editor-knowledge-acquisition-system.136.n4.nabble.com/template/NamlServlet.jtp?macro=app_people&node=136&i=".($i*20); } //print_r($userPages); //Get personal page urls and add to MySQL mysql_connect("localhost" , "root") or die("Cant connect"); mysql_select_db("protegeusers") or die("Cant find database"); foreach($pages as $url) { $urlContents = file_get_contents($url); $pattern = "/http:\/\/protege-ontology-editor-knowledge-acquisition-system\.136\.n4\.nabble\.com\/template\/NamlServlet\.jtp\?macro=.+;user=\d+/"; preg_match_all($pattern, $urlContents, $personalPage); foreach($personalPage as $user) { for($i=0; $i<sizeof($user);$i++) { [color=green]$userContents = file_get_contents($user[$i]);[/color] $pattern1 = "/user\/SendEmail\.jtp\?type=user.+;user=\d+/"; $pattern2 = "/(?<=\">Send Email to ).+(?=<)/"; preg_match_all($pattern1, $userContents, $userEmail); preg_match_all($pattern2, $userContents, $username); [color=green]print_r($username); print_r($email);[/color] //$query = "INSERT INTO users (username, userurl) values ('$userName','$userUrl')"; //mysql_query($query); } } } ?> I was able to upload the files to the DB but now am trying to retrieve it from the table but it's not working.
my code below
<?php while($row = mysql_fetch_array($query1)) { (list($id, $name) = mysql_fetch_array($query1)); echo"<tr>"; echo"<td> $row[category]</td>"; echo"<td> $row[description]</td>"; echo"<td> $row[amount]</td>"; ?> <td> <a href="approved_req.php?id=<?php echo urlencode($id);?>" ><?php echo urlencode($name);?></a> </td> <?php echo"<td> $row[status]</td>"; ?> <td><a class="btn btn-success" <?php echo" href='invoice.php?id=$row[id]'> Pay </a></td>";?></a> <?php echo"</tr>"; } // } ?> </table> <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database //$con = mysql_connect('localhost', 'root', '') or die(mysql_error()); //$db = mysql_select_db('test', $con); $id = $_GET['id']; $query = "SELECT name, type, size, content " . "FROM requisition 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"); ob_clean(); flush(); echo $content; mysql_close(); exit; } ?>Thanks in advance Hello everyone! I'm somewhat of a newb in this so anyways I have this script and I try to force a browser to download a file when someone hits a download button. here is what I'm trying: header('Content-Type: application-download'); header('Content-Disposition: attachment; filename=' .basename($dl_id)); readfile($dl_id); It seems to work in Chrome, Firefox, but it doesn't work in IE Any suggestions? Hi 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'm wanting to have users able to download a file, but I'm wanting it to be a file that only users who are logged in can download. Basically, I don't want a user to be able to enter the URL and download it while not being logged in. Does anyone know what I would use to do this? Thanks. Hi there, I have a cronjob for PHP which generates a table with dynamic data and this table is exported to excel when run. When i have one table it downloads one excel file. I want to download multiple excel files using a for loop. Please Help... Any suggestions will be helpful.. Thank you, Regards, Rohit On PHP 5.2.14. I want to make files downloadable from my website. This seems easy enough: <?php $file = "downloads/someFile.txt"; // Set headers header( "Content-Description: File Transfer" ); header( "Content-Type: application/force-download"); header( "Content-Length: " . filesize( $filename ) ); header( "Content-Disposition: attachment; filename=$file"); // header( "Content-Transfer-Encoding: binary"); readfile( $file ); unlink( $file ); ?> You'll notice, however, that I have "unlink" at the end of this file. That's exactly what I want: to remove the file from the server once it has been downloaded, to prevent anyone else from downloading it. Here's the conundrum: When the user navigates to this URL, browsers offer the choice of Open/Save/Cancel. I don't want users to "open", and if the user presses "cancel", well then I probably don't really want the file deleted. In short: I want the file SAVED, only. And I want to delete the file immediately after it has been downloaded. Thoughts? The following code works fine when using chrome or firefox, but fails with IE. Error: Requested site is either unavailable or cannot be found. Question: Does anyone see anything here that is a known bug with IE that I don't know about? Code: [Select] public function download(){ if($this->validateFile()){ if(!headers_sent()){ header('Content-type: '.$this->getType()); header('Content-Disposition: attachment; filename="'.$this->name.'"'); readfile($this->file); } else{ echo 'Headers have already been sent and are preventing the file download from taking place.'; } return true; } return false; } //I felt this function might be relevant to the issue. I know, it's kind of a ghetto function, I'll improve on it some other time though. private function getType(){ $types=array( 'txt' => 'text/plain', 'mp3' => 'audio/x-mp3', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'doc' => 'application/msword', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/flv', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'avi' => 'video/x-msvideo', 'rtf' => 'application/rtf', 'pdf' => 'application/pdf', 'zip' => 'application/zip', 'exe' => 'application/octet-stream', 'xls' => 'application/msexcel', 'xlsxl' => 'application/msexcel'); if(!$types[$this->getExt()]==''){ return $types[$this->getExt()]; } return 'application/octet-stream'; } Hiya guys After getting everything else working how I expected, I'm sort of struggling on the last step. Downloading I have an upload.php file that allows me to upload a file to Mysql, the fields available a upid - Primary id - Need to link this to the logged on user id name type size content The upload works perfectly Can anyone help with implmenting it to the profile.php (1st page after login) On profile page I have: Welcome "username" from Session Dynamic Table display his user id, username and password at the moment, this will be changed as not needed tho. I am using the sessions MM_Username to pass from the login The table for Login looks like: id - primary username password I assume that if I can copy the ID from login and put it in ID in Upload and add colums to dynamic table to show the upload file, will this make that file only available to logged in user? Cheers |