TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

PHP Code For Uploading and Displaying an Image

To upload and display an image using PHP, you can use the following steps:

  • Create an HTML form that allows users to select an image file to upload. The form should have a file input field and a submit button.
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="image">
  <input type="submit" value="Upload Image">
</form>
  • In the PHP script (upload.php in this example), use the move_uploaded_file() function to save the uploaded file to a specified location on the server.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);

if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
  echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
} else {
  echo "Sorry, there was an error uploading your file.";
}
?>

  • To display the uploaded image, you can use an tag in the HTML and specify the URL of the image file on the server as the src attribute.
<img src="<?php echo $target_file; ?>" alt="Uploaded image">

Note that this is just an example and may require additional error handling and security measures in a real-world application. Also, make sure that the server has the necessary permissions to save files to the specified location.