Sunday, December 23, 2012

Upload file in PHP demo



Upload file to a destination in PHP, put upload information in MySQL database and users can download the files.
1) upload.html
<html>
<head>
<title>PHP file upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="description" />
</head>
<body>
  <form enctype="multipart/form-data" action="upload.php" method="post">
    <table border="1" width="55%" id="table1" cellspacing=0>
      <tr>
        <td colspan="2">
            <h1>PHP Upload file Demo, Jiansen Lu:</h1>
        </td> </tr><tr>
        <td width="71%">
            <input name="userfile" type="file">
              <input type="submit" value="upload" >
        </td>
      </tr>
    </table>
    allowed file type:jpg|jpeg|gif|bmp|png|swf|mp3|wma|zip|rar|doc
 </form>
</body>
</html>
2) config.inc.php, connect to a database
<?php
session_start();
define('DB_HOST', 'localhost'); 
define('DB_USER', 'root');            
define('DB_PW', '');                
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');    
define('DB_PCONNECT', 0);            
define('DB_DATABASE', 'mysql');
$con=mysql_connect(DB_HOST,DB_USER,DB_PW) or die('fail to connect to database"');
mysql_query('set names utf8');
mysql_select_db(DB_NAME);
?>
3) Create a table
CREATE TABLE `f_detail` (
  `id` int(11) NOT NULL auto_increment,
  `filename` varchar(100) NOT NULL,
  `des` varchar(64) NOT NULL,
  `fsize` varchar(10) NOT NULL,
  `ftype` varchar(100) NOT NULL,
  `utime` datetime NOT NULL,
  PRIMARY KEY  (`id`)
);
4) upload.php, used in form in upload.html
<?php
header("content-Type: text/html");
include("config.inc.php");
$uptypes=array('image/jpg',  //allowed file type
 'image/jpeg',
 'image/png',
 'image/pjpeg',
 'image/gif',
 'image/bmp',
 'application/x-shockwave-flash',
 'image/x-png',
 'application/msword',
 'audio/x-ms-wma',
 'audio/mp3',
 'application/vnd.rn-realmedia',
 'application/x-zip-compressed',
 'application/octet-stream');

$max_file_size=20000000;   //max file size in BYTE
$path_parts=pathinfo($_SERVER['PHP_SELF']); //current path
$destination_folder="up/"; //upload path for storage
$imgpreview=1;   //if set preview;
$imgpreviewsize=1/2;  //preview ratio


$file=$_FILES['userfile'];
 if( $file["size"] > $max_file_size )
 {
 echo "<font color='red'>FIle too large</font>";
 exit;
  }

if(!in_array(strtolower($file["type"]), $uptypes))
{
 echo "<font color='red'>upload file type not matched</font>";
 exit;
}
//Create upload directory
if(!file_exists($destination_folder)){
mkdir($destination_folder);
}
$filename=$file["tmp_name"];
$image_size = getimagesize($filename);
$pinfo=pathinfo($file["name"]);
// remove image in 'image/jpeg', only keep jpeg
$ftype=$file['type'];
$ftype= explode("/", $ftype);
$ftype= end($ftype);

$destination = $destination_folder.time().".".$ftype;
$fname = time().".".$ftype;
if (file_exists($destination) && $overwrite != true)
{
     echo "<font color='red'>ͬfile exsited</a>";
     exit;
  }
//exit;
 if(!move_uploaded_file ($filename, $destination))
 {
   echo "<font color='red'>file not moved.</a>";
     exit;
  }else{
      //add to database
    $sql = "INSERT INTO `f_detail`
    (`id` ,`filename` ,`des` ,`fsize` ,`ftype` ,`utime` )
    VALUES
 (NULL ,'".$fname."' , '', '".$file["size"]."', '".$file["type"]."',NOW());";
        $result =mysql_query($sql);
        if (!$result) {
                mysql_free_result($result);
                mysql_close($db);
                echo 'Fail to insert in database!';
        exit;
            }
       
}
$pinfo=pathinfo($destination);
$fname=$pinfo['basename'];
echo 'File name:'.$fname;
echo "<table><tr><td>Upload file address:<br />
 http://".$_SERVER['SERVER_NAME'].$path_parts["dirname"].
 "/".$destination_folder.$fname."</td></tr></table>";
echo " Width:".$image_size[0].'px';
echo " height:".$image_size[1].'px';


if($imgpreview==1)
{
echo "<br>Upload Preview:<br>";
echo "<a href=\"".$destination."\" target='_blank'>
<img src=\"".$destination."\" width=".($image_size[0]*$imgpreviewsize).
" height=".($image_size[1]*$imgpreviewsize);
echo " alt=\"preview:\r filename:".$fname."\r
uploadtime:".date('m/d/Y h:i')."\" border='0'></a>";
}
?>
5. list.php list all the files uploaded
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>File list</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8"><LINK
href="base.css" type=text/css rel=stylesheet>
<STYLE>.bodytitle {
    CLEAR: both; MARGIN-TOP: 8px; BACKGROUND: url(../plus/img/body_title_bg.gif) repeat-x left top; MARGIN-LEFT: auto; WIDTH: 96%; MARGIN-RIGHT: auto; HEIGHT: 33px
}
.bodytitleleft {
    BACKGROUND: url(../plus/img/body_title_left.gif) no-repeat right bottom; FLOAT: left; WIDTH: 30px; HEIGHT: 33px
}
.bodytitletxt {
    PADDING-RIGHT: 8px; MARGIN-TOP: 6px; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 14px; BACKGROUND: url(../plus/img/body_title_right.gif) #fff no-repeat right bottom; FLOAT: left; LINE-HEIGHT: 27px; LETTER-SPACING: 2px; HEIGHT: 27px
}
.np {
    BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px
}
</STYLE>
<BODY>
<DIV class=bodytitle>
<DIV class=bodytitleleft></DIV>
<DIV class=bodytitletxt>File list table</DIV></DIV>
<TABLE class=tbtitle style="MARGIN-TOP: 6px; BACKGROUND: #e2f5bc" height=31
cellSpacing=1 cellPadding=1 width="96%" align=center border=0>
  <TBODY>
  <TR>
    <TD class=tbtitletxt><STRONG>&nbsp;Please select files to download:</STRONG></TD>
  </TR></TBODY></TABLE>
<TABLE class=tblist
style="BORDER-RIGHT: #e2f5bc 1px solid; BORDER-TOP: #e2f5bc 1px solid; MARGIN: 0px 0px 6px; BORDER-LEFT: #e2f5bc 1px solid; BORDER-BOTTOM: #e2f5bc 1px solid"
cellSpacing=1 cellPadding=1 width="96%" align=center border=0>
  <TBODY>
  <TR align=middle>
    <TD class=tbsname
    style="PADDING-RIGHT: 6px; PADDING-LEFT: 6px; PADDING-BOTTOM: 20px; PADDING-TOP: 6px"
    vAlign=top align=left height=120>
      <TABLE cellSpacing=0 cellPadding=6 width="90%" border=0>
        <TBODY>
        <TR>
          <TD><STRONG>Download:</STRONG><BR>
            1. Click download link;</TD>
        </TR></TBODY></TABLE>
      <TABLE cellSpacing=1 cellPadding=3 width="98%" bgColor=#cae886 border=0>
        <TBODY>
        <TR align=middle height=20>
          <TD width="8%" bgColor=#dcf4bd><STRONG>ID</STRONG></TD>
          <TD width="17%" bgColor=#dcf4bd><STRONG>File name</STRONG></TD>
          <TD width="11%" bgColor=#dcf4bd><strong>File size</strong></TD>
          <TD width="18%" bgColor=#dcf4bd><strong>File type</strong></TD>
          <TD width="18%" bgColor=#dcf4bd><strong>Upload time</strong></TD>
          <TD width="10%" bgColor=#dcf4bd><STRONG>Download link</STRONG></TD>
           <TD width="18%" bgColor=#dcf4bd><STRONG>Preview</STRONG></TD>
          </TR>
        <?php
include("config.inc.php");
$sql = "SELECT * FROM `f_detail`";
$result = mysql_query($sql, $con);

    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
        <!--loop start-->
        <TR align=middle bgColor=#ffffff height=20>
          <TD><?php echo $row[0]?></TD>
          <TD><?php echo $row[1]?></TD>
          <TD><?php echo $row[3]?></TD>
          <TD><?php echo $row[4]?></TD>
          <TD><?php echo $row[5]?></TD>
          <TD><A href="download.php?id=<?php echo $row[0]?>">file download
              </A> </TD>
        <TD><img src="<?php echo 'up/'.$row[1]?>" width="40px" /></TD>
        <!--loop end-->
        <?php
            }
         mysql_free_result($result);
       
        ?>
        </TBODY></TABLE>
      <TABLE cellSpacing=0 cellPadding=0 width="90%" border=0>
      </TABLE></TD></TR></TBODY></TABLE>
<DIV align=center>&nbsp;</DIV></BODY></HTML>
6. download.php, used in download link
<?php
       include("config.inc.php");
        $sql = "SELECT * FROM `f_detail` WHERE `id` ='".$_GET['id']."' LIMIT 0 , 30";
        $result = mysql_query($sql,$con);
                $row=mysql_fetch_row($result);
                if (!$result) {
                mysql_free_result($result);
                mysql_close($db);
                echo 'Select failed';
        exit;
            }

$file_name = $row[1];

$file_dir = "up/";

if (!file_exists($file_dir . $file_name)) {
    echo "file not exsited";
    exit;
    }else {
    $file = fopen($file_dir . $file_name,"r");
    Header("Content-type: application/octet-stream");
    Header("Accept-Ranges: bytes");
    Header("Accept-Length: ".filesize($file_dir . $file_name));
    Header("Content-Disposition: attachment; filename=" . $file_name);
// read file to export
    echo fread($file,filesize($file_dir . $file_name));
    fclose($file);
    exit;
}
?>
video for this demo

1 comment: