In this chapter we can learn how to upload a file on a server using PHP with some file validation The things, We will learn from scratch will not escape steps in this chapter. 

What we will do in this chapter upload a file?

  1. The HTML Upload Form
  2. Limit the File Size
  3. Limit Files by Type
  4. Uploading the File


here is example code to upload file on server using PHP. See the below example


if (isset($_FILES['image'])) {
    $errors = array();
    $file_name = $_FILES['image']['name'];
    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    $file_ext = strtolower(end(explode('.', $_FILES['image']['name'])));

    // only acceps jped, jpg and png files 
    $extensions = array("jpeg", "jpg", "png");

    if (in_array($file_ext, $extensions) === false) {
        $errors[] = "extension not allowed, please choose a JPEG or PNG file.";

    if ($file_size > 2097152) {
        $errors[] = 'File size must be excately 2 MB';

    if (empty($errors) == true) {
        move_uploaded_file($file_tmp, "images/" . $file_name);
        echo "Success";
    } else {

        <form action="" method="POST" enctype="multipart/form-data">
            <input type="file" name="image" />
            <input type="submit"/>


After successfully uploaded file on your server we need one destination folder in a server here I am giving images folder when you uploaded a file on a server file will goes to this directory images. you can create destination directory in your root folder.


Thanks, May this example will help you.