Lab #5

7. Write a Program to upload image with extension gif or jpeg in PHP

index.php

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Image</title>
</head>

<body>
<form method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>

</html>

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);

if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
echo "File is an image<br>File Type - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if ($check["mime"] == "image/gif" or $check["mime"] == "image/jpeg") {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "<br>Your file <b>" . basename($_FILES["fileToUpload"]["name"]) . "</b> has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "<h3>Only .gif And .jpeg files allowed</h3>";
}
}
?>

Output

This is simple output. You should try this code with an upload image to see the proper output.


Happy Coding :)