PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: move_uploaded_file
move_uploaded_file - phponwebsites.com
Showing posts with label move_uploaded_file. Show all posts

4 Jun 2015

Ajax upload file or image in PHP using jQuery

     You can upload files and images using PHP. Basically it can be uploaded by form submitting. For more details visit how to upload file or image using PHP. When i tried to upload images using Ajax with jQuery, i can't get it work. All of you may be face this problem. This blog describes how to upload file or image in PHP using jQuery with Ajax.

     Consider the following example for upload files using Ajax and PHP.

Html form for upload image:

   
      To upload file or image, your html form should be like below form:

<form name="multiform" id="multiform" action="#" method="POST" enctype="multipart/form-data">
    Image : <input type="file" name="file" id="file" /></br>
    <input  type="button" id="multi-post" value="Upload"></input>
</form>

      where,
          enctype="multpart/form-data  -  must be present in form. Otherwise file does not upload.
          type="file" in <input>  tag is used to take input as a file.

Ajax and jQuery for upload image:

   
     Before add Ajax code to your html file, you need to add jquery-1.7.2.min.js library file. To upload image, you have to write Ajax code like below:

$(document).ready(function(){
  $("#multiform").submit(function(e) {
    var formObj = $(this);
   
    if(window.FormData !== undefined) {
      var formData = new FormData(this);
      $.ajax({
        url: 'upload.php', //url to process the sent data
        type: 'POST',     //form type
        data:  formData, //form data to send
        mimeType:"multipart/form-data",  //type of form data
        contentType: false,  //content type of form
        cache: false,  //disable cache the request page
        processData: false,  //to send DOMDcoument or non processed data file
        success: function(data, textStatus, jqXHR) {
          $("#er").html(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          $("#er").html('textStatus=' + textStatus + ', errorThrown=' + errorThrown);
        }          
      });
   
      //reset file field after form submitted
      $('#file').val('')
      //prevent the page is refreshed
      e.preventDefault();
      //e.unbind();
    }
  });

  $("#multi-post").click(function() {
    //submit the form and send data
    $("#multiform").submit();
  });

});


      When user click the upload button, the form is submitted, ajax is called and send form data as well.

Html file with Ajax for upload image:


      We need to combine html form and ajax code to make a full html file for upload file or image. You may add some styles to html file in order to give attractive presence to users. After combined above all things, your html code should be like below one:

upload-ajax.html:

<html>
<head>
<style type="text/css">
 body {
 color:white;
 font-size:14px;
 }
 .contact {
    text-align:center;
    background: none repeat scroll 0% 0% #8FBF73;
    padding: 20px 10px;
    box-shadow: 1px 2px 1px #8FBF73;
    border-radius: 10px;
 width:520px;
 }
 #file {
    width: 250px;
    margin-bottom: 15px;
    background: none repeat scroll 0% 0% #AFCF9C;
    border: 1px solid #91B57C;
    height: 30px;
    color: #808080;
    border-radius: 8px;
    box-shadow: 1px 2px 3px;
    padding: 3px 4px;
}
#multi-post
{
    background:none repeat scroll 0% 0% #8FCB73;
    display: inline-block;
    padding: 5px 10px;
    line-height: 1.05em;
    box-shadow: 1px 2px 3px #8FCB73;
    border-radius: 8px;
    border: 1px solid #8FCB73;
    text-decoration: none;
    opacity: 0.9;
    cursor: pointer;
 color:white;
}
#er {
    color: #F00;
    text-align: center;
    margin: 10px 0px;
    font-size: 17px;
}
</style>
</head>
<body> 
<script type="text/javascript" src="../test/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#multiform").submit(function(e) {
    var formObj = $(this);
   
    if(window.FormData !== undefined) {
      var formData = new FormData(this);
      $.ajax({
        url: 'upload.php',
        type: 'POST',
        data:  formData,
        mimeType:"multipart/form-data",
        contentType: false,
        cache: false,
        processData:false,
        success: function(data, textStatus, jqXHR) {
          $("#er").html('<pre><code>'+data+'</code></pre>');
        },
        error: function(jqXHR, textStatus, errorThrown) {
          $("#er").html('textStatus=' + textStatus + ', errorThrown=' + errorThrown);
        }          
      });

      $('#file').val('')
      e.preventDefault();
      //e.unbind();
    }
  });

  $("#multi-post").click(function() {
    //sending form from here
    $("#multiform").submit();
    console.log();
  });

});

</script>
<div class="contact">
  <h1>Upload files using Ajax and PHP</h1>
  <div id="er"></div>
  <form name="multiform" id="multiform" action="#" method="POST" enctype="multipart/form-data">
    Image : <input type="file" name="file" id="file" /></br>
    <input  type="button" id="multi-post" value="Upload"></input>
  </form>
</div>
</body>     
</html>

     
      When you view the upload-ajax.html in browser, it should be like below image:

How to upload images using PHP, and Ajax with jQuery

 

PHP snippet for upload file:


      When ajax is called, url which is in ajax call received form data. Then the file or image is to be uploaded using following PHP code.

upload.php:

<?php
 $file=$_FILES['file']['name'];
 if($file!='')
 {
  //upload file
  move_uploaded_file($_FILES['file']['tmp_name'],$_SERVER['DOCUMENT_ROOT'].'/test/uploaded_img/'.$file);
  //check whether file is exists or not in a folder
  if(file_exists($_SERVER['DOCUMENT_ROOT'].'/test/uploaded_img/'.$file)) {
   echo'Uploaded successfully';
  }
  else {
   echo'File is not uploaded';
  }
 }


     Where,
        move_uploaded_file() - used to upload the file
        file_exists() - used to check whether the file is already exists in a folder or not after upload the file
        $_SERVER['DOCUMENT_ROOT'] - used to represent the directory 

        Now you can add either file or image using PHP and jQuery with Ajax.


1 Jun 2015

Upload multiple files/images using PHP

                        You can upload single file and image easily in PHP. Now we are going to know how to upload multiple files and images using PHP. You can upload more than one images or files at the time using PHP. It can done using by array concepts.

Form for upload multiple images:

               
                     First you need to make form for upload more images. Your form should be like following:

<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="file" multiple="multiple">
<input type="file" name="file[]" id="file" multiple="multiple">
 <input type="submit" id="submit" name="submit" value="submit">
 </form>

                  You should add enctype="multipart/form-data" for upload files. You can see above where the name of file tag should be array like name="file[]" for store multiple values.

Upload multiple images using PHP:


                       Similarly upload single image, you will get image values by $_FILES['file']['name'] in PHP while submitting a form. You need temporary name of image to pass one of the parameter in move_uploaded_file() in order to upload files. If you've a single image, then you can upload easily by move_uploaded_file($_FILES['file']['tmp_name'],$name). But you need to upload multiple images. So you've to get values as an array. Then upload each image using loop. Consider the following example. Here it describes how to get temporary name of each image one by one using loop in PHP.


<?php
if(isset($_POST['submit']))
{
 $name=$_FILES['file']['name'];
 foreach($name as $val => $name1)
 {
   $file_name=$name1;
   $tmp=$_FILES['file']['tmp_name'][$val];
  move_uploaded_file($tmp,$_SERVER['DOCUMENT_ROOT'].'img/'.$file_name);
 }
}

?>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
<table>
<tr><td><input type="file" name="file[]" id="file" multiple="multiple"></td></tr>
<tr><td><input type="file" name="file[]" id="file" multiple="multiple"></td></tr>
<tr><td><input type="submit" id="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</body>
</html>

             
     
     Where,
                move_uploaded_file() - to upload files to desired location.
                $_SERVER['DOCUMENT_ROOT'] gives the root directory of current script executing.
You can upload multiple files as well as images using this PHP script.

Related Posts:


29 Oct 2014

Upload files using PHP

                       You can see upload files at all social media sites to upload your photos. You can upload files using php. You can upload both text and binary files in php. You can upload any files such as .txt, .png, .jpg, .gif, .doc, .csv. At the same time you control the file extensions and file size while uploading files using php. For example, you allows the user can upload only .doc and docx file with particular file size.

PHP script for upload file:


                       Your form should be like this:

<form action="#" method="post" enctype="multipart/form-data">
File: <input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>

                where,
                          enctype="multpart/form-data  -  must be present in form. Otherwise file does not upload.
                         type="file" in <input>  tag is used to take input as a file.

The php script for upload file is:

<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
File: <input type="file" name="file">
       <input type="submit" name="submit" value="Upload">
</form>
<?php
 if(isset($_POST['submit']))
 {
   $name=$_FILES['file']['name'];
   if(file_exists(dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/files/'.$name))
   {
    echo'file is already present';
   }
   else
   {
    move_uploaded_file($_FILES['file']['tmp_name'],dirname($_SERVER['DOCUMENT_ROOT']).'/oops/upload/files/'.$name);
     echo'file added';
}
 }
?>
</body>
</html>

  where,

  

$_FILES:


                   It is the php global variable. It keeps information about uploaded file like below.
  $_FILES['file']['name'] - name of uploaded file.
  $_FILES['file']['type'] - type of uploaded file.
  $_FILES['file']['size'] - size of uploaded file.
  $_FILES['file']['tmp_name'] - temporary name of uploaded file which is in server.
  $_FILES['file']['error'] - errors while uploadeding file.
 ' file' is the name of <input> tag
  $_SERVER['DOCUMENT_ROOT'] - return the directory.
  move_uploaded_file()
 - uploaded file to specified directory.

                  Now you can upload any file without any restriction using php. The file is stored in '/upload/file/' directory already if it is not present in the directory. Otherwise you'll get error message ' file is laready present'.