Move Uploaded File Using PHP and JavaScript

Introduction

The move_uploaded_file() function moves an uploaded file to a new location. This function returns TRUE on file successful uploaded, or FALSE on file upload error. This function checks to ensure that the file designated by filename is a valid upload file. If the file is valid, it will be moved to the filename given by destination. When the file name is the same the uploaded file will be overwritten by the new file.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. It is not possible to process a file uploaded through the XMLHttpRequest object, becouse JavaScript has no access to your computer's file system. But, there are still ways to do this using Ajax-like functionality without use of the XMLHttpRequest object.

This can be done via a hidden <iframe>, using the following method, which has four main steps; they are:

  • Creates a form and a hidden iframe. The iframe must have a name (name attribute). The <form> tag must have a "target" attribute added whose value is the name of the <iframe> and an onsubmit() event form data is sent to a JavaScript function for the page to be not refreshed when you press the Submit button.
     
  • The JavaScript function uses the submit() event to send the form data to the iframe (as the target attribute indicates). The iframe transmits the data to a PHP script whose address is added in its "src" attribute.
     
  • The PHP script uploads the image file on the server, and returns (in the same Iframe) a BODY tag with an "onload" attribute, which calls another JavaScript function in the main page (parent), transferring as a parameter the address of the file that was just copied to the server.
     
  • This second JS function is used to display the image uploaded. It takes the address of the file loaded on the server and adds in a DIV (with "innerHTML") an <img> tag with the image uploaded.

Syntax

move_uploaded_file ( string $filename , string $destination )

 

Example

 

This is a HTML Page. This file is saved as "a.php". In this file "upload_img.php" is included and is shown in this file in the form tag such as action="upload_img.php". When we upload a file, first we define the enctype in the form tag such as enctype="multypart/data-upload"; without enctype, the file upload code is not supported.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

  <title>Upload - Show Image</title>

  <style type="text/css">

     #uploadframe { display:none; }

  </style>

<script type="text/javascript" src="functions.js"></script>

</head>

<body>

 

    <div id="showimg"> </div>

<form id="uploadform" action="upload_img.php" method="post" enctype="multipart/form-     data" target="uploadframe" onsubmit="uploadimg(this); return false">

    <input type="file" id="myfile" name="myfile" />

    <input type="submit" value="Submit" />

    <iframe id="uploadframe" name="uploadframe" src="upload_img.php" width="8" height="8"     scrolling="no" frameborder="0"></iframe>

</form>

</body>

</html>

 

JavaScript file: this file is "funtions.js"; the "js" indicates JavaScript file. In the file is a JavaScript function that uses Ajax to display the uploaded image.

 

function uploadimg(theform){

  theform.submit();

 

   setStatus("Loading...", "showimg");

  return false;

}

function doneloading(rezultat) {

    rezultat = decodeURIComponent(rezultat.replace(/\+/g,  " "));

 

    document.getElementById('showimg').innerHTML = rezultat;

}

 

function setStatus(theStatus, theloc) {

  var tag = document.getElementById(theloc);

 

  if (tag) {

        tag.innerHTML = '<b>'+ theStatus + "</b>";

  }

}
 

PHP file: this file is saved as "upload_img.php". Create the "imgs" folder in "c/wamp/www/imgs" that shows uploaded images in the "imgs" folder.

 

<?php

$savefolder = 'imgs'; // folder for upload

$max_size = 250;   // maxim size for image file, in KiloBytes

 

          // Allowed image types

$allowtype = array('bmp', 'gif', 'jpg', 'jpeg', 'gif', 'png');

 

$rezultat = '';

 

if (isset ($_FILES['myfile'])) {

    $type = end(explode(".", strtolower($_FILES['myfile']['name'])));

  if (in_array($type, $allowtype)) {

    // check its size

       if ($_FILES['myfile']['size']<=$max_size*1000) {

      if ($_FILES['myfile']['error'] == 0) {

        $thefile = $savefolder . "/" . $_FILES['myfile']['name'];

        // if the file can`t be uploaded, return a message

        if (!move_uploaded_file ($_FILES['myfile']['tmp_name'], $thefile)) {

          $rezultat = 'The file can`t be uploaded, try again';

        }

        else {

          $rezultat = '<img src="'.$thefile.'" />';

          echo 'The image was successfully loaded';

        }

      }

    }

       else { $rezultat = 'The file <b>'. $_FILES['myfile']['name']. '</b> exceeds the maximum permitted size <i>'. $max_size. 'KB</i>'; }

  }

  else { $rezultat = 'The file <b>'. $_FILES['myfile']['name']. '</b> has not an allowed extension'; }

}

 

$rezultat = urlencode($rezultat);

echo '<body onload="parent.doneloading(\''.$rezultat.'\')"></body>';

?>

Output

move_upload.jpg

move_upload1.jpg

move_upload2.jpg

move_upload3.jpg

move_upload4.jpg

move_upload5.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all