PHP Upload Image | Lessoncup Programming Blog

Monday, 17 March 2014

PHP Upload Image

Hi, today i am going to tell you about how to upload the picture into database and move into folder, i have got one request from my reader and i have seen this request in Facebook groups, so i decided to write a small article, it is very easy to send a image into folder and database, let's see how to do this


HTML

take one div inside the div take a form and make sure enctype="multipart/form-data" should be set to form tag, take a input file field tag and give it id name #file, take one submit button to submit the form, take and span tag to display a messaage
<div id="box">
<span><?php echo $msg?></span>
<h1>Upload Image</h1>
  <form action="" method="post" enctype="multipart/form-data" name="form1">
    <input type="file" name="file" id="file">
    <input type="submit" name="submit" id="submit" value="Submit">
  </form>
</div>


CSS

<style>

#box{width:400px; height:auto; margin:0 auto; background-color:#FFF; margin-top:200px;-webkit-box-shadow: 0 0 5px #FFF;box-shadow: 0 0 5px #FFF; border:solid #333 10px; padding:10px;}

h1{color:#333; font-family:Verdana, Geneva, sans-serif;}

span{color:#090;}

</style>

PHP

here connect this file to database and place the code inside the if condition now keep this code $_FILES['file']['name']; inside the $file variable, to move the image inside the folder we must use move_uploaded_file(string filename , string destination) function, now write the query to insert the image name into database along into the images folder
<?php
include("db.php");
extract($_REQUEST);

if($submit){
 
 $file = $_FILES['file']['name'];
 
 move_uploaded_file($_FILES['file']['tmp_name'],"images/".$file);
 
 mysql_query("insert into gallery(image) values('$file')");
 
 $msg= "uploaded success";
 
}

?>

Live Demo   Download Script

3 comments :

  1. storing image in database is not good practice ! use directory structure to save image on server

    ReplyDelete
    Replies
    1. bro i am not storing image in database i thought you didn't read the code.. i am storing the name of image and sending image into directory :-)

      Delete

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons