PHP - Downloading File - Adding Html To Top
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. Similar TutorialsI 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. 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. 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 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 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'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. 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 want the user to get authenticated before file download starts
Here is my code:
<?php if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Your request is cancelled'; exit; } else { //check $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] if (isset ($valid)) { //start download $path = './data/negative_seq_60.txt'; $type = "text/plain"; header("Expires: 0"); header("Pragma: no-cache"); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: pre-check=0, post-check=0, max-age=0'); header("Content-Description: File Transfer"); header("Content-Type: " . $type); header("Content-Length: " .(string)(filesize($path)) ); header('Content-Disposition: attachment; filename="'.basename($path).'"'); header("Content-Transfer-Encoding: binary\n"); readfile($path); // outputs the content of the file exit(); } else { //show error } } ?> But on clicking download link, I am getting the following error : " Undefined variable: valid at line no 9". Please help. 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. Hello, 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; ?> 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; Hi Everyone, I have been successful to parse out some data out of an html page that I am downloading using CURL. I used arrays and preg_match to get the data I need. However, some part of the data has a great deal of SPACE charecters and it seems that my arrays method doesn't work. Can someone please point out how I can parse the following to get only the information out and not tags (****quoted excerpt including all the space characters like it was downloaded): Code: [Select] <span class="basic_serial">(777) 777-7777</span> <br /> 1111 ABCD, EFGH, IJKL <br /> Thanks, Hi all i have stumbled across an issue and really need some help i have got a function below which i am using in a wordpress plugin. here is the code. // Base function function isd_s3player() { // Plugin Url $s3url = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__)); echo '<object type="application/x-shockwave-flash" data="'.$s3url.'dewplayer-playlist.swf" width="235" height="200" id="dewplayer" name="dewplayer"> <param name="wmode" value="transparent" /> <param name="wmode" value="transparent" /> <param name="movie" value="'.$s3url.'dewplayer-playlist.swf" /> <param name="flashvars" value="showtime=true&autoreplay=true&xml='.$s3url.'playlist.php&autostart=1" /> </object>'; } ok the problem i am having is i cant passed the database variable to the playlist.php which the dewplayer needs to call within the function. is their a way to somehow use or set the playlist.php in this function without having to call it seperatly??? Here is my playlist.php <?php $bucket = get_option("isd-bucket"); $folder = get_option("isd-folder"); //include the S3 class if (!class_exists('S3'))require_once('s3/S3.php'); //AWS access info if (!defined('awsAccessKey')) define('awsAccessKey', 'amazon key'); if (!defined('awsSecretKey')) define('awsSecretKey', 'amazon secret key'); //instantiate the class $s3 = new S3(awsAccessKey, awsSecretKey); // Get the contents of our bucket $bucket_contents = $s3->getBucket($bucket,$folder); header("Content-type: text/xml"); $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; $xml_output .= '<playlist version="1" xmlns="http://xspf.org/ns/0/">\n'; $xml_output .= "<trackList>\n"; foreach ($bucket_contents as $file){ $fname = $file['name']; $furl = "http://$amazon_bucket.s3.amazonaws.com/".urlencode($fname); if(preg_match("/\.mp3$/i", $furl)) { if (isset($outputted[$furl])) { continue; } $xml_output .= "\t<track>\n"; $xml_output .= "\t\t<location>" . $furl . "</location>\n"; $xml_output .= "\t\t<creator>" . $fname . "</creator>\n"; $xml_output .= "\t\t<album>" . $fname . "</album>\n"; $xml_output .= "\t\t<title>" . basename($fname) . "</title>\n"; $xml_output .= "\t\t<annotation>I love this song</annotation>\n"; $xml_output .= "\t\t<duration>32000</duration>\n"; $xml_output .= "\t\t<image>covers/smetana.jpg</image>\n"; $xml_output .= "\t\t<info></info>\n"; $xml_output .= "\t\t<link>" . $furl . "</link>\n"; $xml_output .= "\t</track>\n"; $outputted[$furl] = true; } } $xml_output .= "</trackList>"; echo $xml_output; ?> ok so as you can see right at the top i am trying to grab two option from the database but it doesnt allow you to do it this way within wordpress. So i guess what i am asking is their a way to completely skip the playlist.php file and do everything within the function??? Any help?? hello. im trying to get the following to work. any ideas for me? Code: [Select] Text[12]=["Job Description","$description it "] it is in a .js file. Hey anybody can please guide me where I m wrong in this php code please reply here is the code Only variables should be passed by reference on line 3 in that function area function get_file_extension($file_name) main error I guess is the explode one Aand yeah I checked adding $file_name = $_FILES['fld']; before the function is started <?php require("include/dbconn.php"); //$username = mysql_real_escape_string($_POST['username1']); function get_file_extension($file_name) { return end(explode('.',$file_name)); } function errors($error){ if (!empty($error)) { $i = 0; while ($i < count($error)){ $showError.= '<div class="msg-error">'.$error[$i].'</div>'; $i ++;} return $showError; }// close if empty errors } // close function if (isset($_POST['submit'])){ $username = "Sunny"; $date1 = date("d m y"); mysql_select_db("deals") or die(mysql_error()); if($username == "") { //header("location:newnewuser1.php"); echo "Username empty"; //header("location:newnewuser1.php"); } else { function createRandomPassword() { $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= 7) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } // Usage $password = createRandomPassword(); //$password = mysql_real_escape_string($_POST['Password']); $date = strtotime("+2hours"); $date1 = date("d-m-y",$date); if(get_file_extension($_FILES["fld"]["name"])!= 'csv') { $error[] = 'Only CSV files accepted!'; echo "Wrong Input"; }//get_file_extension if (!$error) { $tot = 0; $handle = fopen($_FILES["fld"]["tmp_name"], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { for ($c=0; $c < 1; $c++) { try { mysql_query("INSERT INTO newusers (email,password,location,company,name,contact,sourcename,date)VALUES('".mysql_real_escape_string($data[0])."','$password','".mysql_real_escape_string($data[1])."', '".mysql_real_escape_string($data[2])."','".mysql_real_escape_string($data[3])."','".mysql_real_escape_string($data[4])."','$username1','$date1')"); $tot++; } catch(Exception $e) { PRINT 'ERROR:' +$e; } }//for }//while fclose($handle); }// end no error }//close if isset upfile } ?> and this is the form code <form name="f1" action="" method="POST" enctype="multipart/form-data"> <table><tr><td><input type="file" value="Browse" name="fld" onselect="CheckExtension(fld)"><br/></td><td> </td></tr><tr><td>Username :<input type="text" name="username1" value="" id="user" onfocus="validateForm1()"></td> <td><input type="submit" name="submit" value="submit" id="submit"></td></tr></table> </form> Please help me I m stuck in this quite badly Please [attachment deleted by admin] Hi, I was wondering if this is possible as I've been tasked (uni project) with creating a blog site that displays entries in order of creation. From what I've seen, when modifying the file I can only add entries from the bottom line and not from the top without replacing the previously stored content. Thank you. Hi, Is it possible to add PHP code into a TPL file? Ive tried adding my code in as standard PHP and also tried it with the {php}.....{/php} tags but it still doesnt work. Any help appreciated! Thanks Tom Hi all, I am trying to add 3 images to a file on the server. The form is posted to a php page where I am trying to put the images in to a folder named aircraft. I have tried echoing the values and they are correct. But it is not working for some reason. Any help will be appreciated. The html form is: Code: [Select] <li> <label for="image">Main Image</label> <fieldset id="image1"> <input type="file" name="image" id="image" /> </fieldset> <label for="image2">Second Image</label> <fieldset id="image 2"> <input type="file" name="image2" id="image2" /> </fieldset> <label for="image3">Third Image</label> <fieldset id="image 3"> <input type="file" name="image3" id="image3" /> </fieldset> </li> The PHP page is: <?php $destination='aircraft/'.$reg."1.jpg"; $temp_file = $_FILES['image']['tmp_name']; move_uploaded_file($temp_file,$destination); $destination2='aircraft/'.$reg."2.jpg"; $temp_file2 = $_FILES['image2']['tmp_name']; move_uploaded_file($temp_file2,$destination2); $destination3='aircraft/'.$reg."3.jpg"; $temp_file3 = $_FILES['image3']['tmp_name']; move_uploaded_file($temp_file3,$destination3); ?> |