PHP - Need Php Download Script To Redirect To Main Page After Downloading File
Ok, I have a download script. The script is called like:
http://www.site.net/index.php?action=downloadfile&filename=file001.zip&directory=directory12& The download file code is below. My site hosts quite a few files that get linked on other websites. Problem is, when that link is clicked, obviously it just starts the file download, as if it were a direct link to the file. What I need to do, is still have it download the file when the link is clicked, but I would also like it to redirect the browser to my homepage as well. I tried placing this after the download headers but it didn't work. header("Location: http://www.site.net"); Can anyone give me an idea how I can get the code to do that? Keep in mind that I'm not fluent in PHP. case 'downloadfile'; $filename = getGetVar('filename'); $directory = getGetDir('directory'); $current_dir = $uploads_folder_name; if ($directory != '') { $current_dir.="/$directory"; } $filename = basename($filename); if (!$grants[$user_status][DOWNLOAD]) { place_header($mess[111]); show_Contents(); break; } if (!file_exists("$current_dir/$filename")) { place_header($mess[125]); show_Contents(); break; } if (!is_path_safe($directory, $filename)) { place_header($mess[111]); show_Contents(); break; } list($upl_user, $upl_ip, $filestatus, $contents) = get_file_description("$current_dir/$filename", $comment_max_caracters); if ($validation_enabled && $filestatus == UNVALIDATED && !$grants[$user_status][VALIDATE]) { place_header($mess[111]); show_Contents(); break; } $size = filesize("$current_dir/$filename"); $daily_size = get_daydownload(); if (($max_daily_download_mb > 0) && (($size + $daily_size) > ($max_daily_download_mb * 1024 * 1024))) { place_header($mess[212]); show_Contents(); break; } $monthly_size = get_monthdownload(); if (($max_monthly_download_mb > 0) && (($size+$monthly_size) > ($max_monthly_download_mb * 1024 * 1024))) { place_header($mess[213]); show_Contents(); break; } increasefiledownloadcount("$current_dir/$filename"); increasebytecountdl("$destination/$userfile_name"); if (($user_status != ANONYMOUS) && ($logged_user_name != '')) // Update user statistics { list($files_uploaded, $files_downloaded, $files_emailed) = load_userstat($logged_user_name); $files_downloaded++; save_userstat($logged_user_name, $files_uploaded, $files_downloaded, $files_emailed, time()); } header("Content-Type: application/force-download; name=\"$filename\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: $size"); header("Content-Disposition: attachment; filename=\"$filename\""); header("Expires: 0"); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); // Decrypt file if encryption enabled if ($encrypt_filecontent) { decrypt_file("$current_dir/$filename", true); } else { readfile_chunked("$current_dir/$filename"); } exit; break; Similar TutorialsHello, I have the following code to force download mp3 file. the code is working fine but its only downloading 799 bytes. I am new in php and not able to figure out the problem. please help me to sort it out. thanks. Code: [Select] <?php include "dbconnect.php"; $link=dbconnect(); $cat=$_GET['catagory']; $id=$_GET['id']; $query=("select *from $cat where id='$id'"); $result=mysql_query($query); $row=mysql_fetch_array($result); $file = $row["link"]; header ("Content-type: octet/stream"); header("Content-Disposition: attachment; filename=\"".basename($file)."\";" ); header("Content-Length: ".filesize($file)); readfile($file); exit; ?> 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 am using a script for users to download a file, however after the download I want to be able to redirect the user or display a message etc... but I cannot get it to work. My download code is below; if($do_download){ $filename = 'file.zip'; $itemfile = ('/abc/123/htdocs/bin/'.$filename); $filelength = filesize($itemfile); $fp = @fopen($itemfile, "rb"); ob_start(); Header("Pragma: public"); Header("Expires: 0"); Header("Cache-control: private"); Header("Content-Type: application/x-zip-compressed"); Header("Content-Transfer-Encoding: binary"); Header("Content-Length: $filelength"); Header("Accept-Ranges: bytes"); Header('Content-Disposition: attachment; filename="'.$filename.'"'); Header("Connection: close"); ob_end_clean(); while(!feof($fp)){ print stream_get_contents($fp); // for PHP 5+ else use fread } fclose($fp); header('Location: page2.php'); } It doesn't seem to matter what I do whether a redirect or just an echo command nothing continues after the file is downloaded???? Hi,
I have an address on my main server http://www.website.com/directory and would like to redirect it to a subdomain http://subdomain.website.com/directory
The subdomain is not pointing to the same server as the main domain.
How would I set up a redirect in htaccess?
Thanks!
Problem: The page does not redirect the end user to main.php. Notice: Use of undefined constant name_id - assumed 'name_id' in C:\x\xampp\htdocs\pages\form_process.php on line 48 Warning: Cannot modify header information - headers already sent by (output started at C:\x\xampp\htdocs\pages\form_process.php:48) in C:\x\xampp\htdocs\pages\form_process.php on line 87 The error messages displayed above make it seem like they are connected to the problem, but I don't understand why 'name_id' is undefined as its auto increments in mysql. I also think my .htaccess might be preventing me from redirecting, is that possible? " header('Refresh: 5; URL=http://localhost/pages/main.php'); " Goal: redirect user to main.php without error messages being displayed. form_process.php <?php //let's start our session, so we have access to stored data session_start(); if (isset($_POST['terms_and_conditions']) == 0) { // the code was incorrect // handle the error accordingly with your other error checking // or you can do something really basic like this die('You must agree to the terms and conditions to create a profile. Go back and try again.'); } include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php'; $securimage = new Securimage(); if ($securimage->check($_POST['captcha_code']) == false) { // the code was incorrect // handle the error accordingly with your other error checking // or you can do something really basic like this die('The code you entered was incorrect. Go back and try again.'); } else { include 'db.inc.php'; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); $error = array(); $query = 'SELECT name FROM user WHERE ' . 'name = "' . mysql_real_escape_string($_SESSION['values']['name'], $db) . '"' ; $result = mysql_query($query, $db) or die(mysql_error($db)); if(mysql_num_rows($result) > 0) { $error['uname'] = '<p class="errText">Username is taken.</p>'; header('Refresh: 5; URL=form1.php'); } //let's create the query else{ $query = sprintf("INSERT INTO user ( name_id, name, password) VALUES ('%s','%s','%s')", name_id, mysql_real_escape_string($_SESSION['values']['name']), mysql_real_escape_string(md5(SALTY . $_SESSION['values']['password']))); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $name_id = mysql_insert_id(); $query = sprintf("INSERT INTO contact ( name_id, first_name, last_name, email, address, city, county, post, home, mobile) VALUES (LAST_INSERT_ID(),'%s','%s','%s','%s','%s','%s','%s','%s','%s')", mysql_real_escape_string($_SESSION['values']['first_name']), mysql_real_escape_string($_SESSION['values']['last_name']), mysql_real_escape_string($_SESSION['values']['email']), mysql_real_escape_string($_SESSION['values']['address']), mysql_real_escape_string($_SESSION['values']['city']), mysql_real_escape_string($_SESSION['values']['county']), mysql_real_escape_string($_SESSION['values']['post']), mysql_real_escape_string($_SESSION['values']['home']), mysql_real_escape_string($_SESSION['values']['mobile'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $name_id = mysql_insert_id(); $query = sprintf("INSERT INTO profile ( name_id, bi, ex) VALUES (LAST_INSERT_ID(),'%s','%s')", mysql_real_escape_string($_SESSION['pro']['bi']), mysql_real_escape_string($_SESSION['pro']['ex'])); $result = mysql_query($query, $db) or die(mysql_error($db)); $_SESSION['logged'] = 1; header('Refresh: 5; URL=http://localhost/pages/main.php'); } ?> <html> <head> <title>Register</title> </head> <body> <p><strong>Thank you <?php echo $_SESSION['values']['name']; ?> for registering!</strong></p> <p>Your registration is complete! You are being sent to the page you requested. If your browser doesn't redirect properly after 5 seconds, <a href="main.php">click here</a>.</p> </body> </html> <?php session_destroy(); die(); } ?> I have searched for the solution for so long and I still could not solve my problem. I have a localhost server where it stored some pdf files for download.
I implemented the following function to force the download:
if(isset($_POST['dlPDF'])) { $file = $_SERVER['DOCUMENT_ROOT'] .'/Upload/'.$pdfName; header("Content-Type: application/pdf"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$pdfName"); header("Content-Transfer-Encoding: binary"); // read the file from disk readfile($file); }However I could not open the pdf file properly since it says "the pdf file is not correctly encoded". FYI, the downloaded pdf file is always a few Kb larger than the original file. Please kindly let me know if there is anything I can do to make the pdf readable and I appreciate your help. So, I'm learning how to upload pictures into a system from my awesome PHP book. I've looked and looked through the script but I can't figure out whats wrong with it. Goal: The script is meant to save a full version of the image in the images folder and a thumbnail in the thumbnail folder. Bug: The full image does not appear in any folder, and the thumbnail is created but its put in the images folder. I've checked the GD library, and everything is supported. image_effect.php <?php //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // make sure the requested image is valid if (isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir . '/' . $_GET['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_GET['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_GET['capt'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } //add the logo watermark if requested if (isset($_GET['logo'])) { // determine x and y position to center watermark list($width, $height) = getimagesize($dir . '/' . $_GET['id'] . '.jpg'); list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // show the image header('Content-Type: image/jpeg'); imagejpeg($image, '', 100); ?> check_image.php <?php include 'db.inc.php'; //connect to MySQL $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); //change this path to match your images directory $dir ='C:/x/xampp/htdocs/images'; //change this path to match your thumbnail directory $thumbdir = $dir . '/thumbs'; //change this path to match your fonts directory and the desired font putenv('GDFONTPATH=' . 'C:/Windows/Fonts'); $font = 'arial'; // handle the uploaded image if ($_POST['submit'] == 'Upload') { //make sure the uploaded file transfer was successful if ($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch ($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive ' . 'in php.ini.'); break; case UPLOAD_ERR_FORM_SIZE: die('The uploaded file exceeds the MAX_FILE_SIZE directive that ' . 'was specified in the HTML form.'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded.'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded.'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder.'); break; case UPLOAD_ERR_CANT_WRITE: die('The server failed to write the uploaded file to disk.'); break; case UPLOAD_ERR_EXTENSION: die('File upload stopped by extension.'); break; } } //get info about the image being uploaded $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = @date('Y-m-d'); list($width, $height, $type, $attr) = getimagesize($_FILES['uploadfile']['tmp_name']); // make sure the uploaded file is really a supported image $error = 'The file you uploaded was not a supported filetype.'; switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: die($error); } //insert information into image table $query = 'INSERT INTO images (image_caption, image_username, image_date) VALUES ("' . $image_caption . '", "' . $image_username . '", "' . $image_date . '")'; $result = mysql_query($query, $db) or die (mysql_error($db)); //retrieve the image_id that MySQL generated automatically when we inserted //the new record $last_id = mysql_insert_id(); // save the image to its final destination $image_id = $last_id; imagejpeg($image, $dir . '/' . $image_id . '.jpg'); imagedestroy($image); } else { // retrieve image information $query = 'SELECT image_id, image_caption, image_username, image_date FROM images WHERE image_id = ' . $_POST['id']; $result = mysql_query($query, $db) or die (mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width, $height, $type, $attr) = getimagesize($dir . '/' . $image_id . '.jpg'); } if ($_POST['submit'] == 'Save') { // make sure the requested image is valid if (isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir . '/' . $_POST['id'] . '.jpg')) { $image = imagecreatefromjpeg($dir . '/' . $_POST['id'] . '.jpg'); } else { die('invalid image specified'); } // apply the filter $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch ($effect) { case IMG_FILTER_NEGATE: imagefilter($image, IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image, IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image, IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR); break; } // add the caption if requested if (isset($_POST['emb_caption'])) { imagettftext($image, 12, 0, 20, 20, 0, $font, $image_caption); } //add the logo watermark if requested if (isset($_POST['emb_logo'])) { // determine x and y position to center watermark list($wmk_width, $wmk_height) = getimagesize('images/logo.png'); $x = ($width - $wmk_width) / 2; $y = ($height - $wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image, $wmk, $x, $y, 0, 0, $wmk_width, $wmk_height, 20); imagedestroy($wmk); } // save the image with the filter applied imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100); //set the dimensions for the thumbnail $thumb_width = $width * 0.10; $thumb_height = $height * 0.10; //create the thumbnail $thumb = imagecreatetruecolor($thumb_width, $thumb_height); imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); imagejpeg($thumb, $dir . '/' . $_POST['id'] . '.jpg', 100); imagedestroy($thumb); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id']; ?>.jpg" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to our servers:</p> <?php if ($_POST['submit'] == 'Upload') { $imagename = 'images/' . $image_id . '.jpg'; } else { $imagename = 'image_effect.php?id=' . $image_id . '&e=' . $_POST['effect']; if (isset($_POST['emb_caption'])) { $imagename .= '&capt=' . urlencode($image_caption); } if (isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename; ?>" style="float:left;"> <table> <tr><td>Image Saved as: </td><td><?php echo $image_id . '.jpg'; ?></td></tr> <tr><td>Height: </td><td><?php echo $height; ?></td></tr> <tr><td>Width: </td><td><?php echo $width; ?></td></tr> <tr><td>Upload Date: </td><td><?php echo $image_date; ?></td></tr> </table> <p>You may apply special options to your image below. Note: saving an image with any of the options applied <em>cannot be undone</em>.</p> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter: <select name="effect"> <option value="-1">None</option> <?php echo '<option value="' . IMG_FILTER_GRAYSCALE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo ' selected="selected"'; } echo '>Black and White</option>'; echo '<option value="' . IMG_FILTER_GAUSSIAN_BLUR . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="' . IMG_FILTER_EMBOSS . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo ' selected="selected"'; } echo '>Emboss</option>'; echo '<option value="' . IMG_FILTER_NEGATE . '"'; if (isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo ' selected="selected"'; } echo '>Negative</option>'; ?> </select> <br/><br/> <?php echo '<input type="checkbox" name="emb_caption"'; if (isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo '>Embed caption in image?'; echo '<br/><br/><input type="checkbox" name="emb_logo"'; if (isset($_POST['emb_logo'])) { echo ' checked="checked"'; } echo '>Embed watermarked logo in image?'; ?> <br/><br/> <input type="submit" value="Preview" name="submit" /> <input type="submit" value="Save" name="submit" /> </div> </form> </body> </html> <?php } ?> Any help appreciated. Hello, I have a php page from where anyone can download mp3 songs. my database table contain song title and the directory link of every song. the page retrieve song title with the link that people can click and download. but if u click the mp3 started to play on new window. if u right click and save as then it download. but I want that people click and it will start download or give a prompt to save the file in pc. I hv the following code please help me... thankx Code: [Select] <?PHP $artist=$_GET['artist']; $album=$_GET['album']; $query=("select *from Band where artist='$artist' and album='$album'"); $result=mysql_query($query); while ($row=mysql_fetch_array($result)) { ?> <a href="<?php echo $row["link"];?>"><strong><?php echo $row["title"];?></strong></a> <?PHP } ?> How can I make that if I click on the title then it will start download. pls need help. All, I found the following script to do the download: $resultsetpic = mysql_fetch_array($resultpic); $filename = "full_size/$resultsetpic[filename]"; // don't accept other directories $size = @getimagesize($filename); $fp = @fopen($filename, "rb"); if ($size && $fp) { header("Content-type: {$size['mime']}"); header("Content-Length: " . filesize($filename)); header("Content-Disposition: attachment; filename=$filename"); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); fpassthru($fp); exit; } This downloads the file fine. However what I would like to do is also refresh the page that the user was just on. So I tried to add this: $resultsetpic = mysql_fetch_array($resultpic); $filename = "full_size/$resultsetpic[filename]"; // don't accept other directories $size = @getimagesize($filename); $fp = @fopen($filename, "rb"); if ($size && $fp) { header("Content-type: {$size['mime']}"); header("Content-Length: " . filesize($filename)); header("Content-Disposition: attachment; filename=$filename"); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); fpassthru($fp); exit; } $target = "work_queue.php"; header("Location:". $target); However, this doesn't reload the page they were on. Any ideas on how to do this? Thanks in advance. Hello There , I want to download a file from the server to the computer . How can i do this ?? i found out this code: header("Content-type: image/jpg"); header("Content-Disposition: attachment; filename=test.jpg"); the problem is , what i get is the file that the code was executed from saved in the .jpg format. how can i direct to a specified path to select a certain file then download it . example let's say i have a folder that contains 2 files: download.php and image.jpg how can i download the image.jpg from the server with the Save As window?? Thank You Hi, I want that user can only read my article but can't download it. neither with save page as or with view source, even not with selecting text. and copy and paste. is there any solution in php to do that. Please help Thanks I wonder if some kind-hearted person can help me? I am trying to download a video file which has a wmv. The protocol is either mms:// or http:// I can see the video in my browser but I cannot download it using curl or wget in a program and I need to download a few of these. They are publicly viewable so they are not private stuff. The URL is http://210.150.12.140/vod11/tepco/other/1111_01.wmv?MSWMExt=.asf or mms://wmt.stream.co.jp/vod11/tepco/other/1111_01.wmv All I get at the moment is a text file of less than 1K and not the movie itself. How would I download this file please? Thanks Paul Hello everyone. I have a problem with some of my php script. I have some php code that downloads a remote file and directly outputs it to the user. It works and all, it's just that when I do it on my Ubuntu LAMP server, downloading a file takes up a lot of ram. On my Windows WAMP server it works correctly and doesn't use up so much ram. Is this a problem with my code, or is it a server configuration? Below is the code I use to download the file. Code: [Select] public function output_file($file, $name, $mime_type='', $size) { session_write_close(); /* This function takes a path to a file to output ($file), the filename that the browser will see ($name) and the MIME type of the file ($mime_type, optional). If you want to do something on download abort/finish, register_shutdown_function('function_name'); */ if(is_readable($file)) die('File not found or inaccessible!'); /* $size = $size; $name = rawurldecode($name); */ /* Figure out the MIME type (if not specified) */ $known_mime_types=array( "pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg"=> "image/jpg", "jpg" => "image/jpg", "php" => "text/plain" ); if($mime_type==''){ $file_extension = strtolower(substr(strrchr($file,"."),1)); if(array_key_exists($file_extension, $known_mime_types)){ $mime_type=$known_mime_types[$file_extension]; } else { $mime_type="application/x-rar-compressed"; }; }; @ob_end_clean(); //turn off output buffering to decrease cpu usage // required for IE, otherwise Content-Disposition may be ignored if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); header('Content-Type: ' . $mime_type); header('Content-Disposition: attachment; filename="'.$name.'"'); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); /* The three lines below basically make the download non-cacheable */ header("Cache-control: no-cache"); //header('Pragma: private'); // header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // multipart-download and download resuming support if(isset($_SERVER['HTTP_RANGE'])) { list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2); list($range) = explode(",",$range,2); list($range, $range_end) = explode("-", $range); $range=intval($range); if(!$range_end) { $range_end=$size-1; } else { $range_end=intval($range_end); } $new_length = $range_end-$range+1; header("HTTP/1.1 206 Partial Content"); header("Content-Length: $new_length"); header("Content-Range: bytes $range-$range_end/$size"); } else { $new_length=$size; header("Content-Length: ".$size); } /* output the file itself */ $chunksize = 1*(1024)*(1024); //you may want to change this $bytes_send = 0; if ($file = fopen($file, 'r')) { if(isset($_SERVER['HTTP_RANGE'])) fseek($file, $range); while(!feof($file) && (!connection_aborted()) && ($bytes_send<$new_length) ) { $buffer = fread($file, $chunksize); print($buffer); //echo($buffer); // is also possible flush(); $bytes_send += strlen($buffer); } fclose($file); } else die('Error - can not open file.'); die(); } // END OUTPUT_FILE function Hello, Ive got a script that downloads a file to my server. I want to be able to download a file from a site such as FileServe using my premium details. Ive tried http://username:password@fileserve.com/file.rar but that dosent work, It just downloads a tiny small 30kb file. Is there a way i can set a cookie or somthing so my script has access to download file using my premium account? Thanks in advance Hi, I want to download more than one file at a time. But now I can't download any of them that way. I want to solve it the way it is in gmail, i.e. I download either 1 file separately or if there are two or more, it is zipped. Thanks in advanced, T <!-- images --> <section class="card shadow mb-3"> <form action="index.php?lg=<?php echo $lng; ?>&c=text" method="post" enctype="multipart/form-data"> <header class="card-header navbar-custom"><h3 class="text-center"><?php echo $new_document_h3_images; ?></h3></header> <div class="row"> <?php $files = glob('./tekstovi/' . $user_txt_year . '/' . $user_txt_nr . '/' . $text_page . '/' . $user_txt_year . '_' . $user_txt_nr . '_' . $text_nr . '_' . $text_page . '_img_' . '*.{doc,docx,odt,pdf,jpg,JPG,jpeg,png,gif,psd,eps,ai,tiff,tif}', GLOB_BRACE); $dir = './tekstovi/' . $user_txt_year . '/' . $user_txt_nr . '/' . $text_page . '/'; //$index = '0'; for ($i = 0; $i < count($files); $i++) { $image = $files[$i]; ?> <div class="col-sm-4 py-2"> <div class="card h-100"> <input type='checkbox' style="position: absolute; left: 10px; top: 10px;" name='boxes[]' value='<?php echo basename($image); ?>' /> <?php echo '<img class="img-fluid" src="' . $image . '" alt="" />'; ?> <div class="card-body"> <p class="card-title"><?php echo basename($image); ?></p> </div> <div class="card-footer"><?php $stmt_captionreload = $pdo->prepare('SELECT * FROM `sn_images` WHERE sn_images_text_id = :sn_images_text_id AND CONCAT(`sn_images_filename`,`sn_images_basename`) = "' . basename($image) . '" '); $stmt_captionreload->bindValue(':sn_images_text_id', $text_id); $stmt_captionreload->execute(); $row_captionreload = $stmt_captionreload->fetch(PDO::FETCH_ASSOC); $one_caption = stripslashes($row_captionreload['sn_images_caption']); ?> <small class="text-muted"><?php echo $one_caption; ?></small></div> </div> </div> <?php }?> </div><!-- row--> <button type="submit" name="download" value="1" class="btn btn-success float-right">Download selected</button> <input type = 'hidden' name="sn_text_nr" value="<?php echo $text_nr; ?>"> </form> <?php if ($_POST['download'] == '1') { $index = '0'; echo 'Total count: ' . count($_POST['boxes']) . ''; while ($index < count($_POST['boxes'])) { if (isset($_POST['boxes'][$index])) { $file = $_POST['boxes'][$index]; $path = $dir . $file; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($path)); header('Content-Transfer-Encoding: binary'); header('Expires: 600'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($path)); flush(); readfile($path); } else { } $index++; } } ?> </section> <!-- /. images -->
Hello, I am new and am having a hard time with PHP. Scenario: There are PDF files on my website that I want users to register before downloading the files. I do not want them to login but rather provide basic information such as name and email address. Once the form is submitted, I am not sure if I should be using PHPSESSION to validate the user. Also, I am not sure where to place the files: either in the webroot (/var/www/) or outside. I am new to PHP so please forgive me if I use terminology incorrectly. Thank you for reading my question. Hi, I'm trying to figure out the best way to determine if a user is currently downloading a file from my website. The way my site works, is the user waits 30 seconds and views an ad. After the timer is up the download becomes available. I heard that I could probably use a timestamp or something of the sort. I've read up on it but not sure how I could go about this. I have a script that will download a file from my server onto the user's computer. The problem is it's adding the pages HTML to the top of the file. When I actually look at the file on my server it does NOT have the HTML there, so it has to be some sort of problem with my headers. Code: [Select] <?php $fname = "keyword_files/".$this->fileID.".csv"; header('Content-type: application/csv'); header("Content-Disposition: inline; filename=".$fname); readfile($fname); ?> I would appreciate any help! Thanks. |