Php-mysql Course

An upload script permits users to upload a file from a client computer to the remote server. It contains two parts: the HTML form and the PHP code.
The HTML code for an upload form field is:

<form action="script.php" method="post" enctype="multipart/form-data">
 <input type="file" name="field_name" /><br />
 <input type="submit" name="submit" value="Submit" />
</form>
- The enctype attribute of the form tag indicates that the form should be able to handle multiple types of data, including files.
- When an user click on the Submit button, the form data are sent to the PHP script specified in the action attribute ("script.php"). If you want form data to be sent to the same page, you can use action="".

In the PHP code, the uploaded file can be accessed using the $_FILES superglobal. This variable is an array with the fallowing elements:   - Example:
<?php
// If is received a valid file from the 'field_name' form field
if (isset($_FILES['field_name'])) {
  if ($_FILES['field_name']['error'] > 0) {
    echo 'Error: '. $_FILES['field_name']['error']. '<br />';
  }
  else {
    echo 'Upload: '. $_FILES['field_name']['name']. '<br />';
    echo 'Type: '. $_FILES['field_name']['type']. '<br />';
    echo 'Size: '. ($_FILES['field_name']['size'] / 1024) . ' Kb<br />';
    echo 'Stored in: '. $_FILES['field_name']['tmp_name'];
  }
}
?>
Assuming that is uploaded a JPEG image (image.jpg), this code will output:
Upload: image.jpg
Type: image/jpeg
Size: 77.6572265625 Kb
Stored in: C:\server\tmp\php7458.tmp

Create an Upload Script with Restrictions on upload

The uploaded file is initially copied in a temporary directory, and disappears when the PHP script ends. The move_uploaded_file() function can transfer it from the temporary directory to anoter folder.
  - Syntax:
move_uploaded_file('temp_file', 'destination')
- "temp_file" is the location and name of the temporary copy of the file, that is stored in $_FILES['field_name']['tmp_name']
- "destination" is the destination and name of the moved file.

You can add restrictions on what the user is allowed to upload, by checking the values of $_FILES array. For example, you can restrict the type or size of the uploaded file.
In this script, the user may only upload .gif, .jpeg or .png files and the file size must be under 100 kb (see also the comments in script code)
<?php
$updir = 'uploads/';       // sets the folder where the uploaded files are copied
$max_size = 100;         // sets maximum file size allowed (in KB)

// file types allowed
$allowtype = array('gif', 'jpg', 'jpeg', 'png');

// If is received a valid file from the 'field_name' form field
if (isset($_FILES['field_name'])) {
  // check for errors
  if ($_FILES['field_name']['error'] > 0) {
    echo 'Error: '. $_FILES['field_name']['error']. '<br />';
  }
  else {
    // get the name, size (in kb) and type (the extension) of the file
    $fname = $_FILES['field_name']['name'];
    $fsize = $_FILES['field_name']['size'] / 1024;
    $ftype = end(explode('.', strtolower($fname)));

    // checks if the file already exists
    if (file_exists($updir. $fname)) {
      echo 'The file: '. $fname. ' already exists';
    }
    else {
      // if the file not exists, check its type (by extension) and size
      if (in_array($ftype, $allowtype)) {
        // check the size
        if ($fsize <= $max_size) {
          // uses  function to copy the file from temporary folder to $updir
          if (!move_uploaded_file ($_FILES['field_name']['tmp_name'], $updir. $fname)) {
            echo 'The file '. $fname. ' could not be copied, try again';
          }
          else {
            echo $fname. ' ('. $fsize. ' kb) was successfully uploaded';
          }
        }
        else {
          echo 'The file '. $fname. ' exceeds the maximum permitted size, '. $max_size. ' KB';
        }
      }
      else {
        echo $fname. ' - invalid file type';
      }
    }
  }
}
?>

<form action="" method="post" enctype="multipart/form-data">
 <input type="file" name="field_name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
- The move_uploaded_file() function will overwrite an existing file, with the same filename, without warning, so the script checks if the file already exists (with file_exists() ), if it does not, it copies the file to the directory specified in the $updir variable (here "uploads").
- The expresion: end(explode('.', strtolower($fname))) splits the name of the file by the "." delimiter and gets the last element (in lowercase), which is the file extension.
- The if (in_array($ftype, $allowtype)) instruction returns TRUE if $ftype is found in the $allowtype array, otherwise, False.
- If the file is successfully uploaded, returns a confirmation message with the name and the size of the file.

• If you want to upload multiple file in the same time, see the Uploading multiple files tutorial.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
File Upload

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)