Sick Gaming
[Tut] Upload and Display Image in PHP - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html)
+--- Thread: [Tut] Upload and Display Image in PHP (/thread-101288.html)



[Tut] Upload and Display Image in PHP - xSicKxBot - 08-24-2023

[Tut] Upload and Display Image in PHP

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/08/upload-and-display-image-in-php.jpg" width="550" height="513" title="" alt="" /></div><div><div class="modified-on" readability="7.047619047619"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on July 5th, 2023.</div>
<p>PHP upload is a single-line, built-in function invocation. Any user inputs, especially files, can not be processed without proper filtering. Why? Because people may upload harmful files to the server.</p>
<p>After file upload, the status has to be shown in the UI as an acknowledgment. Otherwise, showing the uploaded image’s preview is the best way of acknowledging the end user.</p>
<p><a class="demo" href="https://phppot.com/demo/upload-and-display-image-in-php/">View Demo</a><br />Earlier, we saw how to <a href="https://phppot.com/php/extract-content-using-php-and-preview-like-facebook/">show the preview of images extracted from a remote URL</a>.</p>
<p>This article will provide a short and easy <span>example in PHP to upload and display images</span>.</p>
<p><img decoding="async" loading="lazy" class="alignnone size-large wp-image-21343" src="https://phppot.com/wp-content/uploads/2023/06/upload-and-display-image-php-550x513.jpg" alt="upload and display image php" width="550" height="513" srcset="https://phppot.com/wp-content/uploads/2023/06/upload-and-display-image-php-550x513.jpg 550w, https://phppot.com/wp-content/uploads/2023/06/upload-and-display-image-php-300x280.jpg 300w, https://phppot.com/wp-content/uploads/2023/06/upload-and-display-image-php-768x717.jpg 768w, https://phppot.com/wp-content/uploads/2023/06/upload-and-display-image-php.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>Steps to upload and display the image preview on the browser</h2>
<ol>
<li>Show an image upload option in an HTML form.</li>
<li>Read file data from the form and set the upload target.</li>
<li><a href="https://phppot.com/php/php-image-upload-with-size-type-dimension-validation/">Validate the file type size before uploading</a> to the server.</li>
<li>Call the PHP upload function to save the file to the target.</li>
<li>Display the uploaded image on the browser</li>
</ol>
<h2>1. Show an image upload option in an HTML form</h2>
<p>This code is to show an HTML form with a file input to the user. This form is with <code>enctype="multipart/form-data"</code> attribute. This attribute is for uploading the file binary to be accessible on the PHP side.</p>
<pre class="prettyprint"><code class="language-html">&lt;form action="" method="post" enctype="multipart/form-data"&gt; &lt;div class="row"&gt; &lt;input type="file" name="image" required&gt; &lt;input type="submit" name="submit" value="Upload"&gt; &lt;/div&gt;
&lt;/form&gt;
</code></pre>
<h2>Read file data from the form and set the upload target</h2>
<p>This section shows a primary PHP condition to check if the form is posted and the file binary is not empty.</p>
<p>Once these conditions return true, further steps will be taken for execution.</p>
<p>Once the image is posted, it sets the target directory path to upload. The variable $uploadOK is a custom flag to allow <a href="https://phppot.com/php/working-on-file-upload-using-php/">the PHP file upload</a>.</p>
<p>If the validation returns false, this $uploadOK variable will be turned to 0 and stop&nbsp;uploading.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
if (isset($_POST["submit"])) { // Check image using getimagesize function and get size // if a valid number is got then uploaded file is an image if (isset($_FILES["image"])) { // directory name to store the uploaded image files // this should have sufficient read/write/execute permissions // if not already exists, please create it in the root of the // project folder $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Validation here }
}
?&gt;
</code></pre>
<h2>Validate the file type size before uploading to the server</h2>
<p>This example applies three types of validation criteria on the server side.</p>
<ol>
<li>Check if the uploaded file is an image.</li>
<li>Check if the image has the accepted size limit (0.5 MB).</li>
<li>Check if the image has the allowed extension (jpeg and png).</li>
</ol>
<pre class="prettyprint"><code class="language-php">&lt;?php
// Check image using getimagesize function and get size // if a valid number is got then uploaded file is an image if (isset($_FILES["image"])) { // directory name to store the uploaded image files // this should have sufficient read/write/execute permissions // if not already exists, please create it in the root of the // project folder $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); $check = getimagesize($_FILES["image"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if the file already exists in the same path if (file_exists($targetFile)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size and throw error if it is greater than // the predefined value, here it is 500000 if ($_FILES["image"]["size"] &gt; 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Check for uploaded file formats and allow only // jpg, png, jpeg and gif // If you want to allow more formats, declare it here if ( $imageFileType != "jpg" &amp;&amp; $imageFileType != "png" &amp;&amp; $imageFileType != "jpeg" &amp;&amp; $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG &amp; GIF files are allowed."; $uploadOk = 0; }
?&gt;
</code></pre>
<h2>4. Call the PHP upload function to save the file to the target</h2>
<p>Once the validation is completed, then the PHP <code>move_uploaded_file()</code> the function is called.</p>
<p>It copies the file from the temporary path to the target direct set in step 1.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) { echo "Sorry, your file was not uploaded.";
} else { if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) { echo "The file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; }
}
?&gt;
</code></pre>
<h2>5. Display the uploaded image on the browser.</h2>
<p>This section shows the image preview by setting the source path.</p>
<p>Before setting the preview source, this code ensures the upload status is ‘<em>true</em>.’</p>
<pre class="prettyprint"><code class="language-php">&lt;h1&gt;Display uploaded Image:&lt;/h1&gt;
&lt;?php if (isset($_FILES["image"]) &amp;&amp; $uploadOk == 1) : ?&gt; &lt;img src="&lt;?php echo $targetFile; ?&gt;" alt="Uploaded Image"&gt;
&lt;?php endif; ?&gt;
</code></pre>
<p>Create a directory called “uploads” in the root directory of the downloaded example project. Uploaded images will be stored in this folder.</p>
<p><strong>Note:</strong> The “uploads” directory should have sufficient file permissions.<br /><a class="demo" href="https://phppot.com/demo/upload-and-display-image-in-php/">View Demo</a> <a class="download" href="https://phppot.com/downloads/php/upload-and-display-image-in-php.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/upload-and-display-image-in-php/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2023/07/05/upload-and-display-image-in-php/