Creating a Download Image from URL Form with Preview using PHP and JS Tutorial

In this tutorial, you can learn how to create an Image Preview and Download from an Image URL using PHP and JavaScript. The tutorial aims to provide students and beginners with a reference for learning some useful techniques and features for developing effective web applications. Here, I will be providing the scripts of a simple program that I created that demonstrate the creation of an Image Download and Preview form.

What is an Image Preview?

In a website or web application, Image Preview is a frontend feature that allows the users to view the image first before continuing or proceeding to execute the process that needs to be done. For example, a web application has a form that allows the user to upload images with an image preview container or a panel will output or display the chosen of the user so that the user can confirm it before proceeding with the upload execution.

How to Download and Preview the Image from URL using PHP and JS?

PHP comes with multiple built-in functions or methods that are useful and allow the developer to achieve their desired feature for their requirements. Downloading an Image from an Image URL can be done using the PHP's cURL (Client URL) Library which enables the application to transfer data using various protocols. For the Image Preview, we can simply achieve this using Pure JavaScript. Validating the Image URL is also one of the processes that you have to ensure to avoid or prevent any errors upon downloading and previewing the images. Check out the sample program scripts that I provided below to have a better idea.

Sample Program

The below scripts output a sample web application's form page that allows users to enter the Image URL and preview the images before downloading it. The URL will be validated first before the user can proceed with the download action.

Interface

The following file script is an HTML containing the elements that are needed for the form such as the input field, image preview panel/container, and the download button. Save the file as index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>PHP - Download Image From Link with Preview</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  10. <link rel="stylesheet" href="style.css">
  11. </head>
  12. <main>
  13. <h1 class="text-center page-title"><b>Download Image form URL with Preview using PHP and JavaScript</b></h1>
  14. <!-- Form Wrapper -->
  15. <div class="wrapper">
  16. <form action="download.php" method="POST">
  17. <div class="form-field">
  18. <label for="image_url">Image URL:</label>
  19. <input type="url" class="form-field-input" name="image_url" id="image_url" placeholder="https://imagedomain.com/test-img.png" required>
  20. </div>
  21. <div id="img-preview-panel" class="">
  22. <a href="#" class="prev-close-btn"><span class="material-symbols-outlined">close</span></a>
  23. <div class="img-prev-holder">
  24.  
  25. </div>
  26. <div class="img-prev-default">
  27. </div>
  28. </div>
  29. <div class="form-btn">
  30. <button type="submit" disabled>Download Image</button>
  31. </div>
  32. </form>
  33. </div>
  34. <!-- Form Wrapper -->
  35. </main>
  36. <script src="preview-img-js.js"></script>
  37. </body>
  38. </html>

Stylesheet

Here is the CSS script that contains the style scripts of the page layout and form. Save the file as style.css and it is loaded at the index page.

  1. @import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap');
  2. body *{
  3. font-family: 'Rubik', sans-serif;
  4. }
  5. /**
  6. Page Design
  7. */
  8. body,
  9. html{
  10. height: 100%;
  11. width: 100%;
  12. margin: 0;
  13. padding: 0;
  14. }
  15. body{
  16. background-color: #2C3333;
  17. }
  18. main{
  19. height: 100%;
  20. width: 100%;
  21. display: flex;
  22. flex-direction: column;
  23. justify-content: center;
  24. align-items: center;
  25. padding: 1em 0px;
  26. }
  27. section{
  28. width:760px;
  29. padding: 1em 2em;
  30. text-align: center;
  31. }
  32. @media (max-width: 760px) {
  33. section{
  34. width:100%;
  35. }
  36. }
  37. .page-title{
  38. color: #fff;
  39. text-shadow: 1px 1px 3px #000;
  40. font-size: 35px;
  41. }
  42.  
  43. /*
  44. Form Design
  45. */
  46. .wrapper{
  47. width: 450px;
  48. padding: 3em 2em;
  49. background: #fff;
  50. box-shadow: 1px 1px 5px #dadada;
  51. }
  52. @media (max-width:450px){
  53. .wrapper{
  54. width: 100%;
  55. }
  56. }
  57.  
  58. .form-field{
  59. width: 100%;
  60. display: flex;
  61. flex-direction: column;
  62. justify-content: center;
  63. margin-bottom: 1em;
  64. }
  65. .form-field label > *{
  66. width: 100%;
  67. }
  68. .form-field input {
  69. outline: none;
  70. background: padding-box;
  71. padding: 0.5em 0.5em;
  72. border: 1px solid #c9c9c9;
  73. font-size: .9rem;
  74. transition: border .3s ease;
  75. }
  76. .form-field input::placeholder{
  77. color: #cacaca;
  78. font-style: italic;
  79. }
  80. .form-field input:focus {
  81. border: 1px solid #1c9ff97a;
  82. box-shadow: 1px 1px 5px #1c9ff97a;
  83. }
  84. form[disabled] input,
  85. form[disabled] button
  86. {
  87. pointer-events:none;
  88. filter: opacity(0.6);
  89. }
  90.  
  91. /* Image Preview Panel */
  92. #img-preview-panel{
  93. width: 100%;
  94. height: 40vh;
  95. border: 2px dashed #d5d5d5;
  96. position: relative;
  97. display: flex;
  98. flex-direction: column;
  99. align-items: center;
  100. justify-content: center;
  101. margin-bottom: 1em;
  102. }
  103. #img-preview-panel .prev-close-btn{
  104. position: absolute;
  105. top: 5px;
  106. right: 5px;
  107. text-decoration: none;
  108. color: #9d9d9d;
  109. text-shadow: 0px 0px 2px #1a1a1aba;
  110. display: none;
  111. }
  112. #img-preview-panel .prev-close-btn .material-symbols-outlined
  113. {
  114. font-weight: bolder;
  115. font-size: 1.2rem;
  116. }
  117. #img-preview-panel .prev-close-btn:hover,
  118. #img-preview-panel .prev-close-btn:focus{
  119. color: #b7b7b7;
  120. }
  121.  
  122. #img-preview-panel.filled .prev-close-btn{
  123. display: block;
  124. }
  125.  
  126. /* Image preview */
  127. #img-preview-panel .img-prev-holder{
  128. width: 100%;
  129. height: 100%;
  130. top: 0;
  131. left: 0;
  132. background-color: #252525;
  133. overflow: hidden;
  134. display: none;
  135. }
  136. #img-preview-panel.filled .img-prev-holder{
  137. display: block;
  138. }
  139. #img-preview-panel.filled .img-prev-holder>img{
  140. width: 100%;
  141. height: 100%;
  142. object-fit: scale-down;
  143. object-position: center center;
  144. }
  145.  
  146. /* Image Preview Default*/
  147. #img-preview-panel:before {
  148. content: "";
  149. background-image: url(./image-icon.png);
  150. background-size: 80px;
  151. background-repeat: no-repeat;
  152. background-position: center center;
  153. position: absolute;
  154. height: 60%;
  155. width: 100%;
  156. top: 0;
  157. left: 0;
  158. z-index: 1;
  159. }
  160. #img-preview-panel:after {
  161. content: "Please Enter a valid Image URL First to Preview";
  162. position: absolute;
  163. height: 40%;
  164. width: 100%;
  165. bottom: 0;
  166. left: 0;
  167. text-align: center;
  168. z-index: 1;
  169. }
  170. #img-preview-panel:before,
  171. #img-preview-panel:after{
  172. filter: opacity(.5);
  173. }
  174. #img-preview-panel.filled:before,
  175. #img-preview-panel.filled:after{
  176. display: none;
  177. }
  178.  
  179. /*Form Button*/
  180. .form-btn{
  181. display: flex;
  182. justify-content: center;
  183. }
  184. .form-btn button{
  185. width: 60%;
  186. padding: .5em .5em;
  187. text-align: center;
  188. border: unset;
  189. border-radius: 0;
  190. background: #00a1ff;
  191. color:#fff;
  192. font-weight: bolder;
  193. letter-spacing: .09em;
  194. cursor: pointer;
  195. outline: none;
  196. }
  197. .form-btn button:hover,
  198. .form-btn button:focus,
  199. .form-btn button:active
  200. {
  201. background: #009dff;
  202. box-shadow: 1px 1px 3px #009dff;
  203. }
  204. .form-btn button[disabled]{
  205. pointer-events: none;
  206. }

JavaScript

The script below is the JavaScript code which allows the preview feature functional. It also contains the scripts that reset the form. The file script is named preview-img-js.js and loads this file on the index page.

  1. //Selecting the Image URL Input
  2. const URLinput = document.getElementById('image_url')
  3. //Selecting the Image Preview Panel Element
  4. const ImagePreviewEl = document.getElementById('img-preview-panel')
  5. //Selecting the Image Preview Container Element
  6. const previewContainer = ImagePreviewEl.querySelector('.img-prev-holder')
  7. //Selecting the Form Element
  8. const form = document.querySelector('form')
  9. //Selecting the Form Download button
  10. const DownloadButton = form.querySelector('button[type="submit"]')
  11. //Selecting the Image Preview Close/Reset Button
  12. const resetPreviewBtn = ImagePreviewEl.querySelector('.prev-close-btn')
  13.  
  14. /** Event Listener when URL Input is updated */
  15. URLinput.addEventListener('input', async e => {
  16. // Getting the Image URL Input Value
  17. var _url = URLinput.value
  18. // Regular Expresion for validating the Image URL
  19. var validURLRegEx = /^(http|https)\:\/\/(.*?)\.(jpe?g|png|gif)$/i;
  20.  
  21. //Validating the Image URL
  22. var _urlIsValid = validURLRegEx.test(_url)
  23.  
  24. if(_urlIsValid){
  25. // IF URL is valid Then preview Image
  26. var _img = document.createElement('img')
  27. _img.setAttribute('alt', 'Image to Download')
  28. _img.src = _url
  29. previewContainer.innerHTML = ''
  30. previewContainer.appendChild(_img)
  31. if(!ImagePreviewEl.classList.contains('filled'))
  32. ImagePreviewEl.classList.add('filled');
  33. }
  34. //Removing the disabled attribute from the Download Button
  35. if(DownloadButton.hasAttribute('disabled'))
  36. DownloadButton.removeAttribute('disabled')
  37. })
  38.  
  39. /** Event Listener to reset the form */
  40. resetPreviewBtn.addEventListener('click', e => {
  41. e.preventDefault()
  42. //Disabling the download button
  43. DownloadButton.setAttribute('disabled','')
  44. //Remove the url from input
  45. URLinput.value = ''
  46. //Mark Preview panel as unfilled by removing the filled class
  47. if(ImagePreviewEl.classList.contains('filled'))
  48. ImagePreviewEl.classList.remove('filled');
  49. URLinput.focus()
  50. })

PHP Script

Here's the PHP script that contains the cURL request for retrieving the image from the given URL and downloading it if the image URL is valid. Save this file as download.php.

  1. <?php
  2. if($_SERVER['REQUEST_METHOD'] == "POST"){
  3. //Image URL from Request
  4. $imgURL = $_POST['image_url'];
  5. //Initializing cURL
  6. $curl_init = curl_init($imgURL);
  7. //cURL option for capturing or retrieving the image content
  8. curl_setopt($curl_init, CURLOPT_RETURNTRANSFER, true);
  9. //storing the image content to variable
  10. $content = curl_exec($curl_init);
  11. //cURL options to retrieve the HTTP response code
  12. curl_setopt($curl_init, CURLOPT_HEADER, true);
  13. curl_setopt($curl_init, CURLOPT_NOBODY, true);
  14. //Getting the HTTP code status of the request
  15. $httpcode = curl_getinfo($curl_init, CURLINFO_HTTP_CODE);
  16. //closing the cURL
  17. curl_close($curl_init);
  18. if($httpcode == 200){
  19. //Downloading the Image if the request response is OK
  20. header('Content-TypeL image/png');
  21. header('Content-Disposition: attachement; filename="downloadedImage.png"');
  22. echo $content;
  23. header('location:./');
  24. }else{
  25. //Returning Message if the Given Image URL is Invalid
  26. echo "<script>alert('Image URL is not Valid!')</script>";
  27. header('location:./');
  28. }
  29. }
  30. ?>

Snapshots

Here are the snapshots of the sample program using the scripts I provided above.

Preview and Download Image From URL using PHP and JS

Preview and Download Image From URL using PHP and JS

DEMO VIDEO

There you go! I have also provided the complete source code zip file of the sample program I created for this tutorial on this site. The file is free to download. The download button is located below this tutorial's content. Feel free to download and modify the program source code to do some experiments to enhance your programming capabilities.

That's it! I hope this Creating a Download Image from URL Form with Preview using PHP and JS Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment