Skip to main content

How to Get the Height and Width of Uploaded Image using PHP

Getting Started

To beautify our view, I've added Bootstrap which is a CSS framework and is included in the downloadable of this tutorial but if you want, you can download bootstrap using this link.

Creating our Form and Script

Finally, we create our upload form and the script if the form is submitted. Create a new file, name it as index.php and paste the codes below.
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>How to Get the Height and Width of Uploaded Image using PHP</title>
  6. <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
  7. <style type="text/css">
  8. .mt20{
  9. margin-top:20px;
  10. }
  11. .mt10{
  12. margin-top:10px;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <h1 class="text-center mt20">Get the Height and Width of Uploaded Image</h1>
  18. <hr>
  19. <div class="row justify-content-md-center">
  20. <div class="col-sm-3 mt20">
  21. <form method="POST" enctype="multipart/form-data">
  22. <input type="file" name="image" class="form-control form-control-lg" required>
  23. <button type="submit" name="upload" class="btn btn-primary mt10">Upload</button>
  24. </form>
  25.  
  26. <?php
  27. if(isset($_POST['upload'])){
  28. $image = $_FILES['image']['tmp_name'];
  29. if(!empty($image)){
  30. $image = $_FILES['image']['tmp_name'];
  31. //first method: using list() function
  32. list($width, $height) = getimagesize($image);
  33. echo "
  34. <div class='alert alert-info mt20'>
  35. <h4>Using list() method:</h4>
  36. <p>Width: ".$width."</p>
  37. <p>Height: ".$height."</p>
  38. </div>
  39. ";
  40.  
  41. //second method: assign to array
  42. $array = getimagesize($image);
  43. echo "
  44. <div class='alert alert-info mt20'>
  45. <h4>From assigned Array:</h4>
  46. <p>Width: ".$array[0]."</p>
  47. <p>Height: ".$array[1]."</p>
  48. </div>
  49. ";
  50. }
  51. else{
  52. echo "
  53. <div class='alert alert-danger mt20'>
  54. Please upload an Image
  55. </div>
  56. ";
  57. }
  58. }
  59. ?>
  60. </div>
  61. </div>
  62.  
  63.  
  64. </body>
  65. </html>
That ends this tutorial. Happy Coding :)

Add new comment