PHP-MySQL

Upload images to web server using php

The following example shows that how to upload and download images / files [.jpeg/.png/.bmp/ .txt/.doc etc] to web server [localhost or remote server]

1. Create a HTML web page as following screen with code.

<html>
<head>
<title>Image/File Uploading Form</title>
</head>
<body background=bg.jpg>
<h2>File Upload:</h2>
Select a file to upload: <form action="file_uploader.php" method="post"  enctype="multipart/form-data">
<input type="file" name="file" size="50" /><br>
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Output is…


2. Next, create a  PHP file called “file_uploader.php” and add following code to in it.

<html>
<body background=bg.jpg>
<?php
$uploaddir = '/wamp/www/Demo/uploaded/';
$uploadfile = $uploaddir. basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Error in uploading files..!\n";
}
?>
<br><br>
<hr>
<a href="download.php">View Uploaded  files  </a>
<hr>
<br><br><br> <br><br><br><br><a href="home.php"> <img src="home-button-icon.png"> </a>
</body>
</html>

3. Click on “Choose File” button to browse and select file/image then click on upload.

4. Before running this page, create a folder called “uploaded” in the following location.
/wamp/www/Demo/uploaded/

5. Now, Click on “Choose File” button to browse and select file/image then click on upload then it will show as following out put.
6. Now, to download the files from server / create a following PHP page for the same task.
7. Create File called  “download.php” and add following code to it.
<html>
<body background=bg.jpg>
<h1><font color=teal> Download files here </h1>
<hr>
<?php

$directory = 'uploaded'; 

echo "<table border=1 style='border:6px solid teal' cellpadding=5 cellspacing=6 align=center>";

foreach(glob($directory.'/*.*') as $file) 
{
echo "<tr>";
echo "<td>". $file . '-' . date ("m/d/Y", filemtime($file)). "</td>";
echo "<td>". '<a href="'.$file.'">'.$file.' - Size:'.filesize($file).'</a>'. "</td>";

echo "</tr>";
}
echo "</table>";
?>
<br><br><br> <br><br><br><br><a href="home.php"> <img src="home-button-icon.png"> </a>
</body>
</html>
8. Now run the above page to see below output and one can download any files from server.



That’s all for now!
keep browsing here for more on PHP examples!
SKB

Leave a Reply

Your email address will not be published. Required fields are marked *