Here's a basic example of how you can create a simple image upload functionality in PHP:
1. HTML Form (index.html):
Create a simple HTML form with an input field of type file to allow users to choose an image file for upload.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
</head>
<body>
<h2>Image Upload</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="image">Choose Image:</label>
<input type="file" name="image" id="image" accept="image/*">
<button type="submit" name="upload">Upload</button>
</form>
</body>
</html>
2. PHP Script (upload.php):
Create a PHP script to handle the image upload. This script will move the uploaded file to a specified directory.
<?php
if (isset($_POST['upload'])) {
$uploadDir = 'uploads/'; // Specify the directory to save the uploaded files
// Check if the directory exists, create it if not
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
// Get the file details
$fileName = basename($_FILES['image']['name']);
$targetFilePath = $uploadDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
// Check if the file is an image
$allowTypes = array('jpg', 'jpeg', 'png', 'gif');
if (in_array($fileType, $allowTypes)) {
// Upload the file
if (move_uploaded_file($_FILES['image']['tmp_name'], $targetFilePath)) {
echo "The file $fileName has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
} else {
echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
}
}
?>
Create an "uploads" Directory:
Create a directory named "uploads" in the same directory as your PHP script to store the uploaded images.