php | Upload image

HTML

<form method="POST" class="form-horizontal" autocomplete="on" enctype="multipart/form-data">

<input type="file" id="file_icon_img" name="file_icon_img" class="form-control" />

</form>

Function – Upload

if (array_key_exists('btn_add', $_POST)) {
    save_icon_image(1);    
}


function save_icon_image($att_id)
{

    $target_dir = PATH_system . "\assets\img\artwork\\";
    $target_file = $target_dir . basename($_FILES["file_icon_img"]["name"]);
    $uploadOk = 1;

    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // rename the file
    $target_file = $target_dir . $att_id . "." . $imageFileType;


    // Check if image file is a actual image or fake image
    if (isset($_POST["submit"])) {
        $check = getimagesize($_FILES["file_icon_img"]["tmp_name"]);
        if ($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }

    // Check if file already exists
    if (file_exists($target_file)) {
        //echo "Sorry, file already exists.";
        //$uploadOk = 0;
        unlink($target_file);

    }

    // Check file size
    if ($_FILES["file_icon_img"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    
    if ($imageFileType != "png") {
        echo "Sorry, only PNG files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
        // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file_icon_img"]["tmp_name"], $target_file)) {
            //  echo "The file " . htmlspecialchars(basename($_FILES["file_icon_img"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *