Friday, January 5, 2018

Codes for file upload in PHP (Step 4)


  We can set some limitations in uploading file. For example, we don't allow to upload the file size more than 1MB and .pdf files. In this example, we will only allow to upload jpg or jpeg format. Ok, lets start write the following codes and discover how it works.




 <?php

 @$name = $_FILES['file']['name'];
 @$type = $_FILES['file']['type'];
 @$size = $_FILES['file']['size'];
 
 @$extension = substr($name, (strpos($name, '.'))+1);

 @$tmp_name = $_FILES['file']['tmp_name'];

 if(@isset($name) && @!empty($name)){

  if($extension == 'jpg' || $extension == 'jpeg'){

 $location = 'tnw87/';
    if(move_uploaded_file($tmp_name, $location.$name)) {
      echo $name.' is successfully uploaded!';
    } else{
      echo 'Upload Errors';
    }
    }else{
      echo 'Your file type is <strong>'.$extension. ' !</strong></br>';
      echo 'Only <b>jpg</b> or <b>jpeg</b> is allowed to upload!';
    }
 }else{
   echo 'Please select file to upload';
 }



 ?>

 <style type = "text/css">
 form{margin-top : 100px; margin-left : 50px;}
 </style>
 <form action = "upload.php" method = "POST" enctype = "multipart/form-data">
 <input type = "file" name = "file"></br></br>
 <input type = "submit" value = "Upload">
 </form>

No comments:

Post a Comment