473,819 Members | 2,470 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to download a file using php?

127 New Member
this is my upload.php

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>File Upload</title>
  6. </head>
  7. <?php
  8.  
  9. include('config.php');
  10.  
  11. ?>
  12. <body>
  13. <?php
  14. /*if ((($_FILES["file"]["type"] == "/doc")
  15. || ($_FILES["file"]["type"] == "image/jpeg")
  16. || ($_FILES["file"]["type"] == "image/pjpeg"))
  17. && ($_FILES["file"]["size"] < 66000))*/
  18. if(($_FILES["file"]["size"] < 66000) && ($_FILES["file"]["type"] == "application/msword") )
  19.   {
  20.   if ($_FILES["file"]["error"] > 0)
  21.     {
  22.     echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
  23.     }
  24.   else
  25.     {
  26.     echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  27.     echo "Type: " . $_FILES["file"]["type"] . "<br />";
  28.     echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  29.     echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
  30.  
  31.     if (file_exists("upload/" . $_FILES["file"]["name"]))
  32.       {
  33.       echo $_FILES["file"]["name"] . " already exists. ";
  34.       }
  35.     else
  36.       {
  37.       move_uploaded_file($_FILES["file"]["tmp_name"],
  38.       "upload/" . $_FILES["file"]["name"]);
  39.       echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
  40.  
  41.         $filename = $_FILES["file"]["name"]; 
  42. $filetype = $_FILES["file"]["type"];
  43. $filesize = $_FILES["file"]["size"];
  44. $tempfile = $_FILES["file"]["tmp_name"];
  45.  
  46.       $query="insert into resume_upload (name, type, size,tmp_name) values ( '$filename','$filetype','$filesize','$tempfile' )";
  47.  
  48. mysql_query($query);
  49. $candidatename = $_POST['cname'];
  50. $gender = $_POST['gen'];
  51. $email = $_POST['email'];
  52. $phone = $_POST['ph'];
  53. $qualification = $_POST['qual'];
  54. $experience = $_POST['exp'];
  55. $skills = $_POST['skills'];
  56. $industry =$_POST['indus'];
  57.  
  58. $query1="insert into candidate (cname, gen, email, ph, qual, exp, skills, indus, res_title ) values ( '$candidatename','$gender','$email','$phone' ,'$qualification','$experience','$skills','$industry','$filename' )";
  59.  
  60. mysql_query($query1);
  61.  
  62. echo "<br>";
  63. echo "File Details stored in database";
  64.  
  65.       }
  66.  
  67.     }
  68.   }
  69. else
  70.   {
  71.   echo "Invalid file. Please Upload Word Document";
  72.   }
  73. ;
  74. ?> 
  75. </body>
  76. </html>
  77.  
  78.  
document is succesfully uploading to a specific folder. now i want to download the document from that folder.

this is my search.php code
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. include('lock.php');
  4. include("config.php");
  5.  
  6.  
  7.  
  8.   $var = @$_GET['q'] ;
  9.   $trimmed = trim($var); 
  10.  
  11. // rows to return
  12. $limit=10; 
  13.  
  14.  
  15. if ($trimmed == "")
  16.   {
  17.   echo "<p>Please enter a search...</p>";
  18.   exit;
  19.   }
  20.  
  21.  
  22. /*if (!isset($var))
  23.   {
  24.   echo "<p>We dont seem to have a search parameter!</p>";
  25.   exit;
  26.   }*/
  27.  
  28. $query = "select * from candidate where cname like \"%$trimmed%\" ||  skills like \"%$trimmed%\" ||   exp like \"%$trimmed%\" || indus like \"%$trimmed%\" || qual like \"%$trimmed%\" ORDER BY cid ";
  29.  
  30.  $numresults=mysql_query($query);
  31.  $numrows=mysql_num_rows($numresults);
  32.  
  33.  
  34. if ($numrows == 0)
  35.   {
  36.   echo "<h4>Results</h4>";
  37.   echo "<p>Sorry, your search: &quot;" . $trimmed . "&quot; returned zero results</p>";
  38.  
  39.  }
  40.  
  41.  
  42.   if (empty($s)) {
  43.   $s=0;
  44.   }
  45.  
  46.  
  47.   $query .= " limit $s,$limit";
  48.   $result = mysql_query($query) or die("Couldn't execute query");
  49.  
  50.  
  51. echo "<p>You searched for: &quot;" . $var . "&quot;</p>";
  52.  
  53.  
  54. echo "Results";
  55. echo "<br>";
  56. $count = 1 + $s ;
  57. echo "<center>";
  58. echo "<table CELLPADDING=10 border =1 bgcolor='lightgrey'>";
  59. echo "<tr>";
  60. echo "<th>Candidate Name</th>";
  61. echo "<th>Email Id</th>";
  62. echo "<th>Qualification</th>";
  63. echo "<th>Experience</th>";
  64. echo "<th>Skills</th>";
  65. echo "<th>Resume</th>";
  66.  
  67.   while ($row= mysql_fetch_array($result)) {
  68.  ?>
  69.    <tr>
  70.              <td> <?php echo $row["cname"]; ?></td>
  71.              <td><?php echo $row["email"]; ?></td>
  72.              <td><?php echo $row["qual"]; ?></td>
  73.              <td><?php echo $row["exp"]; ?></td>
  74.              <td><?php echo $row["skills"]; ?></td>
  75.              <td>
  76.              <?php echo ( '<img src="download.gif" /><a href="download.php">Download</a>' ); ?>
  77.              </td><td>
  78.            <?php 
  79.            /*$pid= '$_GET[pid]';
  80.            echo ( '<img src="edit.ico" /><a href="download.php?pid=".$pid."\">Download</a>');*/?>
  81.            </td>
  82. </tr> 
  83. <?php
  84.  
  85.   }
  86.  
  87. $currPage = (($s/$limit) + 1);
  88.  
  89.  
  90.   echo "<br />";
  91.  
  92.  
  93.   if ($s>=1) { 
  94.   $prevs=($s-$limit);
  95.   print "&nbsp;<a href=\"$PHP_SELF?s=$prevs&q=$var\">&lt;&lt; 
  96.   Prev 10</a>&nbsp&nbsp;";
  97.   }
  98.  
  99.  
  100.   $pages=intval($numrows/$limit);
  101.  
  102.  
  103.  
  104.   if ($numrows%$limit) {
  105.  
  106.   $pages++;
  107.   }
  108.  
  109.  
  110.   if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
  111.  
  112.  
  113.   $news=$s+$limit;
  114.  
  115. echo "&nbsp;<a href=\"$PHP_SELF?s=$news&q=$var\">Next &gt;&gt;</a>";
  116.   }
  117.  
  118. $a = $s + ($limit) ;
  119.   if ($a > $numrows) { $a = $numrows ; }
  120.   $b = $s + 1 ;
  121.   echo "<p>Showing results $b to $a of $numrows</p>";
  122.  
  123. ?>
  124.  
  125.  
  126. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  127. <html xmlns="http://www.w3.org/1999/xhtml">
  128. <head>
  129. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  130. <title>Search Results</title>
  131. </head>
  132.  
  133. <body>
  134. </body>
  135. </html>
  136.  
in this [code]echo ( '<img src="edit.ico" /><a href="download. php?pid=".$pid. "\">downloa d</a>');*/?>[code]
when i click this the download link it must download the
resume doc from 'upload' folder...

plz help?
Jul 29 '10 #1
12 3442
johny10151981
1,059 Top Contributor
I developed this script to download CSV file from server (also i got suggestion from other site i cant recall the name)

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3.  if($_GET['filename']==NULL)
  4.  {
  5.   //print_r($_GET);
  6.   error_mail($mail_to,"Unexpected page access above ".__LINE__." in File ".__FILE__,__LINE__." in ".__FILE__);//function to send error message to the developer
  7.   echo "<message>file name missing </message>";
  8.   exit;
  9.  }
  10.  
  11.  $filename=$_GET['filename'];
  12. // error_mail($mail_to,"filename is".$filename,__LINE__." in ".__FILE__);
  13.  if(file_exists("csv_download/".$filename)==false)
  14.  {
  15.   error_mail($mail_to,"Unexpected file missing above ".__LINE__." in File ".__FILE__."\nMissing File Name: csv_download/".$filename,__LINE__." in ".__FILE__);
  16.   echo "<message>file missing in the server</message>"; 
  17.   exit;
  18.  }
  19.  
  20.  
  21.  $rfilename = realpath("csv_download/".$filename); //server specific
  22.  
  23.  $file_extension = strtolower(substr(strrchr($rfilename,"."),1));
  24.  
  25.  switch( $file_extension )
  26.  {
  27.   case "pdf": $ctype="application/pdf"; break;
  28.   case "exe": $ctype="application/octet-stream"; break;
  29.   case "zip": $ctype="application/zip"; break;
  30.   case "doc": $ctype="application/msword"; break;
  31.   case "xls": $ctype="application/vnd.ms-excel"; break;
  32.   case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  33.   case "gif": $ctype="image/gif"; break;
  34.   case "png": $ctype="image/png"; break;
  35.   case "jpe": case "jpeg":
  36.   case "jpg": $ctype="image/jpg"; break;
  37.   default: $ctype="application/force-download";
  38.  }
  39.  
  40.  header("Pragma: public"); // required
  41.  header("Expires: 0");
  42.  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  43.  header("Cache-Control: private",false); // required for certain browsers
  44.  header("Content-Type: $ctype");
  45.  header("Content-Disposition: attachment; filename=".$filename.";" );
  46.  header("Content-Transfer-Encoding: binary");
  47.  header("Content-Length: ".@filesize($rfilename));
  48.  @readfile("$rfilename");
  49.  unlink($rfilename);            //to delete the file after dwonload
  50. ?>
  51.  
hope this will help

Regards,
Johny
Jul 29 '10 #2
impin
127 New Member
@johny10151981
thanks buddy. its works. i am able to download the file. but i cant read the contents. when i try open the word document it shows an error msg " MS word needs a converter to display the file correctly".... why i am getting this msg....
Jul 29 '10 #3
johny10151981
1,059 Top Contributor
hard to explain without examine. Can you manually download the file and try to read?
Please also post the download link so that i can see what in side.
Jul 29 '10 #4
impin
127 New Member
@johny10151981
its just a simple word file. Resume Document... it contains only text...
Jul 29 '10 #5
impin
127 New Member
similarly i cant view the picture too...

No preview available... error.

but that word doc and image file are stored in the folder 'upload'. if i go to that folder and open those files it working. i can view the content.

if i download those file using php, then the downloaded files are not working.... i used the code what u have suggested above...

the word document is not a csv file... its a normal word document....
Jul 29 '10 #6
johny10151981
1,059 Top Contributor
I found the reason,
Give me time to sort it out :)
Jul 29 '10 #7
johny10151981
1,059 Top Contributor
Make sure the very first characters are
<?php

and the very last characters are
?>

And Make sure you didnt print any data anyway
no print_r or print or echo or anything otherwise your data must get destroyed
Jul 29 '10 #8
impin
127 New Member
@johny10151981
i used echo to just print an error mgs if the file not in the folder...
Jul 29 '10 #9
johny10151981
1,059 Top Contributor
There is space above your
<?php
or
after
?>

I have checked again. It download file very well
Jul 30 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3233
by: ASP Spam Fighter | last post by:
Hello all, I don't know how to get around this one... If anybody can help me with this problem, I would appreciate it very much. I've been trying to send a (large) file to the browser via a download page that uses a file download component. The file downloads fine, except that Internet Explorer refuses to browse to a different page while the file is downloading! I don't understand why it does that and I don't know how to fix this...
1
5904
by: Vasu | last post by:
Hi, I have a requirement to download a file from the web site using a client tool. Iam writing a C# program to download using WebRequest, HttpRequest, WebResponse and so on. The problem Iam having is to navigate thru multiple pages. I have to login
0
4082
by: Killingkids | last post by:
hello, everyone...im facing a big problem in my final year project, hope that u all can help me solve the problem ... i was doing a mobile web application which enable student to check the college information through mobile, however i just use simulator to test my system... one of modules or function was enable the student to downloads some notes which in txt file format through mobile.Hence, i tested using IE,it does not appear any problem, i...
0
1707
by: Killingkids | last post by:
hello, everyone...im facing a big problem in my final year project, hope that u all can help me solve the problem ... i was doing a mobile web application which enable student to check the college information through mobile, however i just use simulator to test my system... one of modules or function was enable the student to downloads some notes which in txt file format through mobile.Hence, i tested using IE,it does not appear any problem, i...
3
5488
by: Geethu03 | last post by:
In my application i want to download the files in web by using the java or JSP program. please help me to do this program. Thanks and Regards, Geethu.
35
9369
by: keerthyragavendran | last post by:
hi i'm downloading a single file using multiple threads... how can i specify a particular range of bytes alone from a single large file... for example say if i need only bytes ranging from 500000 to 3200000 of a file whose size is say 20MB... how do i request a download which starts directly at 500000th byte... thank u cheers
3
2728
by: cypherkro | last post by:
Hi I have a requirement to automatically download a file using a WebBrowser control without having the "Download File" pop up windows display. I cannot use Webclient!! I am using VS2005, .net2 and the application is a windows application. Does anyone have a solution to automatically downloading the file from a WebBrowser control. Thanks in Advance
4
1942
by: pplers | last post by:
I have a list of files (zip, rar) that require cookies to download them. So i would like to know how to do it....
5
2267
by: vinodkus | last post by:
dear sir/madam I have to write a code for download file using asp. please help me thanks in advance
3
6494
colinod
by: colinod | last post by:
I am trying to get my site to download mp3 files without having to right click - save as on a link. I have found this code, which works as long as the file names are short, if they get a bit long it just opens a blank page, can anyone help <%@Language="VBScript"%> <%Option Explicit%> <%Response.Buffer = True%> <% On Error Resume Next Dim strPath strPath = CStr(Request.QueryString("file"))
0
9620
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10701
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10425
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10452
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9246
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7699
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6910
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5723
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3044
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.