Skip to content Skip to sidebar Skip to footer

Upload and View Image using php

   First we need to create a form with "Choose File" button, "Caption" textbox and "Upload" button. Create the table for saving file name and caption.

php Image Upload

Index.php

<form action="addexec.php" method="post" enctype="multipart/form-data" name="addroom">
 Select Image: <br />
 <input type="file" name="image" class="ed"><br />
 Caption<br />
 <input name="caption" type="text" class="ed" id="brnu" />
 <br />
 <input type="submit" name="Submit" value="Upload" id="button1" />
 </form>
<br />
Photo Archieve
<br />
<br />
<?php
include('config.php');
$result = mysql_query("SELECT * FROM photos");
while($row = mysql_fetch_array($result))
{
echo '<div id="imagelist">';
echo '<p><img src="'.$row['location'].'"></p>';
echo '<p id="caption">'.$row['caption'].' </p>';
echo '</div>';
}
?>

After that create a php file for database configuration using password username and database name like follow.

config.php

<?php
$mysql_hostname = "localhost";
$mysql_user = "merbin";
$mysql_password = "merbin";
$mysql_database = "test";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>

When the user submit the form the form will send to the addexec.php file and it will process the uploaded image and save the caption and image name.

addexec.php

<?php
include('config.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);

move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);

$location="photos/" . $_FILES["image"]["name"];
$caption=$_POST['caption'];

$save=mysql_query("INSERT INTO photos (location, caption) VALUES ('$location','$caption')");
header("location: index.php");
exit();
}
?>

Download Full Source Code with Database

Post a Comment for "Upload and View Image using php"