Search This Blog

2017/01/26

PHP upload file to server

<form method="post" enctype="multipart/from-data">
<input type="file" name="upload_file" >
</form>
Attr:
$_FILES['upload_file']
$_FILES['upload_file']['name']
$_FILES['upload_file']['tmp_name']
$_FILES['upload_file']['type']
$_FILES['upload_file']['size']
Check is file uploaded success:
if(!is_uploaded_file($_FILES['upload_file']['tmp_name'])) {
    unlink($_FILES['upload_file']['tmp_name']); // error
} else {
    // continue do something.
}
Check if file too big:
$maxsize = 10240;
if($_FILES['upload_file']['size'] > $maxsize) {
    unlink($_FILES['upload_file']['tmp_name']); // error
} else {
    // continue do something.
}
Check type:
if($_FILES['upload_file']['type'] != "image/gif") 
Move file:
move_uploaded_file($_FILES['upload_file']['tmp_name'], "path/" . $_FILES['upload_file']['name']);
Full sample(upload by one button):
<!DOCTYPE html>
<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 <script type="text/javascript">
  function upload() {
   var form = document.getElementById("uploadForm");
   form.file.click();

   jQuery("#file").change(function () {
    form.submit.click()
   });
  }
 </script>
</head>
<body>
 <form id="uploadForm" name="upload_form" action="" method="post" enctype="multipart/form-data">
  <input id="file" type="file" name="file" style="display:none;">
  <input class="btn" type="submit" name="submit" style="display:none;">
 </form>
 <input class="btn" type="button" value="click to upload file" onclick="upload()">
</body>
</html>

<?php 
if(!empty($_FILES)) {
    if($_FILES['file']['error'] == 0){
     echo $_FILES['file']['tmp_name'];
        $flag = move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
        if($flag){
         echo $_FILES['file']['name'].' upload success'.'<br/>';
        }else{
         echo $_FILES['file']['name'].' upload fail'.'<br/>';
        }
    }
} else {
 echo "failed";
}
?>

No comments :

Post a Comment