how to download a file using php?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • impin
    New Member
    • Jul 2010
    • 127

    how to download a file using php?

    this is my upload.php

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>File Upload</title>
    </head>
    <?php
    
    include('config.php');
    
    ?>
    <body>
    <?php
    /*if ((($_FILES["file"]["type"] == "/doc")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 66000))*/
    if(($_FILES["file"]["size"] < 66000) && ($_FILES["file"]["type"] == "application/msword") )
      {
      if ($_FILES["file"]["error"] > 0)
        {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
      else
        {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
    
        if (file_exists("upload/" . $_FILES["file"]["name"]))
          {
          echo $_FILES["file"]["name"] . " already exists. ";
          }
        else
          {
          move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    	  
    	    $filename = $_FILES["file"]["name"]; 
    $filetype = $_FILES["file"]["type"];
    $filesize = $_FILES["file"]["size"];
    $tempfile = $_FILES["file"]["tmp_name"];
    
    	  $query="insert into resume_upload (name, type, size,tmp_name) values ( '$filename','$filetype','$filesize','$tempfile' )";
    	  	  	 
    mysql_query($query);
    $candidatename = $_POST['cname'];
    $gender = $_POST['gen'];
    $email = $_POST['email'];
    $phone = $_POST['ph'];
    $qualification = $_POST['qual'];
    $experience = $_POST['exp'];
    $skills = $_POST['skills'];
    $industry =$_POST['indus'];
    
    $query1="insert into candidate (cname, gen, email, ph, qual, exp, skills, indus, res_title ) values ( '$candidatename','$gender','$email','$phone' ,'$qualification','$experience','$skills','$industry','$filename' )";
    
    mysql_query($query1);
    
    echo "<br>";
    echo "File Details stored in database";
    
          }
    	
        }
      }
    else
      {
      echo "Invalid file. Please Upload Word Document";
      }
    ;
    ?> 
    </body>
    </html>
    document is succesfully uploading to a specific folder. now i want to download the document from that folder.

    this is my search.php code
    Code:
    <?php
    
    include('lock.php');
    include("config.php");
    
      
    
      $var = @$_GET['q'] ;
      $trimmed = trim($var); 
    
    // rows to return
    $limit=10; 
    
    
    if ($trimmed == "")
      {
      echo "<p>Please enter a search...</p>";
      exit;
      }
    
    
    /*if (!isset($var))
      {
      echo "<p>We dont seem to have a search parameter!</p>";
      exit;
      }*/
    
    $query = "select * from candidate where cname like \"%$trimmed%\" ||  skills like \"%$trimmed%\" ||   exp like \"%$trimmed%\" || indus like \"%$trimmed%\" || qual like \"%$trimmed%\" ORDER BY cid ";
       
     $numresults=mysql_query($query);
     $numrows=mysql_num_rows($numresults);
    
    
    if ($numrows == 0)
      {
      echo "<h4>Results</h4>";
      echo "<p>Sorry, your search: &quot;" . $trimmed . "&quot; returned zero results</p>";
    
     }
    
    
      if (empty($s)) {
      $s=0;
      }
    
    
      $query .= " limit $s,$limit";
      $result = mysql_query($query) or die("Couldn't execute query");
    
    
    echo "<p>You searched for: &quot;" . $var . "&quot;</p>";
    
    
    echo "Results";
    echo "<br>";
    $count = 1 + $s ;
    echo "<center>";
    echo "<table CELLPADDING=10 border =1 bgcolor='lightgrey'>";
    echo "<tr>";
    echo "<th>Candidate Name</th>";
    echo "<th>Email Id</th>";
    echo "<th>Qualification</th>";
    echo "<th>Experience</th>";
    echo "<th>Skills</th>";
    echo "<th>Resume</th>";
    
      while ($row= mysql_fetch_array($result)) {
     ?>
       <tr>
                 <td> <?php echo $row["cname"]; ?></td>
                 <td><?php echo $row["email"]; ?></td>
                 <td><?php echo $row["qual"]; ?></td>
                 <td><?php echo $row["exp"]; ?></td>
                 <td><?php echo $row["skills"]; ?></td>
                 <td>
    			 <?php echo ( '<img src="download.gif" /><a href="download.php">Download</a>' ); ?>
                 </td><td>
               <?php 
    		   /*$pid= '$_GET[pid]';
    		   echo ( '<img src="edit.ico" /><a href="download.php?pid=".$pid."\">Download</a>');*/?>
    		   </td>
    </tr> 
    <?php
    
      }
    
    $currPage = (($s/$limit) + 1);
    
    
      echo "<br />";
    
    
      if ($s>=1) { 
      $prevs=($s-$limit);
      print "&nbsp;<a href=\"$PHP_SELF?s=$prevs&q=$var\">&lt;&lt; 
      Prev 10</a>&nbsp&nbsp;";
      }
    
    
      $pages=intval($numrows/$limit);
    
    
    
      if ($numrows%$limit) {
     
      $pages++;
      }
    
    
      if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
    
     
      $news=$s+$limit;
    
    echo "&nbsp;<a href=\"$PHP_SELF?s=$news&q=$var\">Next &gt;&gt;</a>";
      }
    
    $a = $s + ($limit) ;
      if ($a > $numrows) { $a = $numrows ; }
      $b = $s + 1 ;
      echo "<p>Showing results $b to $a of $numrows</p>";
      
    ?>
    
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Search Results</title>
    </head>
    
    <body>
    </body>
    </html>
    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?
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    I developed this script to download CSV file from server (also i got suggestion from other site i cant recall the name)

    Code:
    <?php
    
     if($_GET['filename']==NULL)
     {
      //print_r($_GET);
      error_mail($mail_to,"Unexpected page access above ".__LINE__." in File ".__FILE__,__LINE__." in ".__FILE__);//function to send error message to the developer
      echo "<message>file name missing </message>";
      exit;
     }
     
     $filename=$_GET['filename'];
    // error_mail($mail_to,"filename is".$filename,__LINE__." in ".__FILE__);
     if(file_exists("csv_download/".$filename)==false)
     {
      error_mail($mail_to,"Unexpected file missing above ".__LINE__." in File ".__FILE__."\nMissing File Name: csv_download/".$filename,__LINE__." in ".__FILE__);
      echo "<message>file missing in the server</message>"; 
      exit;
     }
     
    
     $rfilename = realpath("csv_download/".$filename); //server specific
    
     $file_extension = strtolower(substr(strrchr($rfilename,"."),1));
    
     switch( $file_extension )
     {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpe": case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
     }
    
     header("Pragma: public"); // required
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private",false); // required for certain browsers
     header("Content-Type: $ctype");
     header("Content-Disposition: attachment; filename=".$filename.";" );
     header("Content-Transfer-Encoding: binary");
     header("Content-Length: ".@filesize($rfilename));
     @readfile("$rfilename");
     unlink($rfilename);			//to delete the file after dwonload
    ?>
    hope this will help

    Regards,
    Johny

    Comment

    • impin
      New Member
      • Jul 2010
      • 127

      #3
      Originally posted by johny10151981
      I developed this script to download CSV file from server (also i got suggestion from other site i cant recall the name)

      Code:
      <?php
      
       if($_GET['filename']==NULL)
       {
        //print_r($_GET);
        error_mail($mail_to,"Unexpected page access above ".__LINE__." in File ".__FILE__,__LINE__." in ".__FILE__);//function to send error message to the developer
        echo "<message>file name missing </message>";
        exit;
       }
       
       $filename=$_GET['filename'];
      // error_mail($mail_to,"filename is".$filename,__LINE__." in ".__FILE__);
       if(file_exists("csv_download/".$filename)==false)
       {
        error_mail($mail_to,"Unexpected file missing above ".__LINE__." in File ".__FILE__."\nMissing File Name: csv_download/".$filename,__LINE__." in ".__FILE__);
        echo "<message>file missing in the server</message>"; 
        exit;
       }
       
      
       $rfilename = realpath("csv_download/".$filename); //server specific
      
       $file_extension = strtolower(substr(strrchr($rfilename,"."),1));
      
       switch( $file_extension )
       {
        case "pdf": $ctype="application/pdf"; break;
        case "exe": $ctype="application/octet-stream"; break;
        case "zip": $ctype="application/zip"; break;
        case "doc": $ctype="application/msword"; break;
        case "xls": $ctype="application/vnd.ms-excel"; break;
        case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
        case "gif": $ctype="image/gif"; break;
        case "png": $ctype="image/png"; break;
        case "jpe": case "jpeg":
        case "jpg": $ctype="image/jpg"; break;
        default: $ctype="application/force-download";
       }
      
       header("Pragma: public"); // required
       header("Expires: 0");
       header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
       header("Cache-Control: private",false); // required for certain browsers
       header("Content-Type: $ctype");
       header("Content-Disposition: attachment; filename=".$filename.";" );
       header("Content-Transfer-Encoding: binary");
       header("Content-Length: ".@filesize($rfilename));
       @readfile("$rfilename");
       unlink($rfilename);			//to delete the file after dwonload
      ?>
      hope this will help

      Regards,
      Johny
      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....

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        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.

        Comment

        • impin
          New Member
          • Jul 2010
          • 127

          #5
          Originally posted by johny10151981
          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.
          its just a simple word file. Resume Document... it contains only text...

          Comment

          • impin
            New Member
            • Jul 2010
            • 127

            #6
            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....

            Comment

            • johny10151981
              Top Contributor
              • Jan 2010
              • 1059

              #7
              I found the reason,
              Give me time to sort it out :)

              Comment

              • johny10151981
                Top Contributor
                • Jan 2010
                • 1059

                #8
                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

                Comment

                • impin
                  New Member
                  • Jul 2010
                  • 127

                  #9
                  Originally posted by johny10151981
                  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
                  i used echo to just print an error mgs if the file not in the folder...

                  Comment

                  • johny10151981
                    Top Contributor
                    • Jan 2010
                    • 1059

                    #10
                    There is space above your
                    <?php
                    or
                    after
                    ?>

                    I have checked again. It download file very well

                    Comment

                    • impin
                      New Member
                      • Jul 2010
                      • 127

                      #11
                      this is my code download.php

                      Code:
                      <?php
                      include('config.php');
                      $filename = @$_GET['id'] ;
                        echo "$filename";
                        
                           if('$filename'==NULL)
                           {
                                echo "<message>file name missing </message>";
                            exit;
                           }
                      
                         
                        if(file_exists("upload/".$filename)==false)
                        {
                          echo "<message>file missing in the server</message>"; 
                          exit;
                          }
                        
                        
                        $rfilename = realpath("upload/".$filename); //server specific
                         
                        $file_extension = strtolower(substr(strrchr($rfilename,"."),1));
                          
                          switch( $file_extension )
                          {
                          case "pdf": $ctype="application/pdf"; break;
                           case "exe": $ctype="application/octet-stream"; break;
                           case "zip": $ctype="application/zip"; break;
                          case "doc": $ctype="application/msword"; break;
                         case "xls": $ctype="application/vnd.ms-excel"; break;
                          case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                          case "gif": $ctype="image/gif"; break;
                           case "png": $ctype="image/png"; break;
                           case "jpe": case "jpeg":
                          case "jpg": $ctype="image/jpg"; break;
                           default: $ctype="application/force-download";
                          }
                        
                          header("Pragma: public"); // required
                          header("Expires: 0");
                          header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                      	header("Cache-Control: private",false); // required for certain browsers
                          header("Content-Type: $ctype");
                          header("Content-Disposition: attachment; filename=".$filename.";" );
                          header("Content-Transfer-Encoding: binary");
                          header("Content-Length: ".@filesize($rfilename));
                        @readfile("$rfilename");
                          //unlink($rfilename);            //to delete the file after dwonload
                      ?>

                      Comment

                      • impin
                        New Member
                        • Jul 2010
                        • 127

                        #12
                        its now working buddy. thanks.
                        i used
                        Code:
                        echo "$filename";
                        inside the code. thats why i am not getting the correct contents. i remove that code,now its working.... thank you!

                        Comment

                        • johny10151981
                          Top Contributor
                          • Jan 2010
                          • 1059

                          #13
                          I can see there is 5 new line after your
                          ?>
                          it would change the content of the file. to make sure check the file size in the server and the file size that you upload i guess you will get few bytes differetn

                          Comment

                          Working...