PHP

Image uploading to Data Base using PHP

Image uploading to Data Base using PHP

Here the Simple code For uploading the Image to server in php method. Use this code for Uploading the Image

HTML =>( imageUpload.html )

<!DOCTYPE html>

<html>

<head>

<title> Image upload </title>

</head>

<body>// when upload a file form attribute ( enctype=”multipart/form-data” ) is very important

<form action = “imageUpload.php” method = “post” enctype=”multipart/form-data”>

<label>First Name : </label>

<input type = “text” name = “fname” required />

<br />

<label>Last Name : </label>

<input type = “text” name = “lname” required />

<br />

<label>Date of Birth :</label>

<input type = “date” name = “dob” required />

<br />

<label>Choose File:</label>

<input type = “file” name = “uploadFile” />    // important to note name value

<br />

<input type = “submit” name = “submit” value = “Submit” />

</form>

</body>

</html>

 

PHP =>( imageUpload.php )

<?php

 

If ( $_SERVER [ ‘REQUEST_METHOD’ ] == ‘POST’ ) {

//MySQL db connect

$host=”localhost”;     //Host name of a server ( you are using XAMPP it’s localhost )

$user=”root”;         // DB user name

$pass=””;

$db=”form_data”;     // DB name

$con = mysqli_connect ( $host , $user , $pass , $db );

 

//Getting form data

$fname=$_POST[‘fname’];

$lname=$_POST[‘lname’];

$dob=$_POST[‘dob’];

 

//Getting file information’s using global variable $_FILES

$file_name=$_FILES[‘uploadFile’][‘name’];   //Return uploading file name

$file_size=$_FILES[‘uploadFile’][‘size’];   //Return uploading size in bytes

$file_type=$_FILES[‘uploadFile’][‘type’];   //Return uploading file type (ex. Image/png)

 

// Checking file maximum allowed size

$size=5 * 1024 * 1024;  // I used 5 MB as maximum file size

If ( $file_size > $size ){   //This will allow only maximum of 5MB

die ( “File size to large”);

}

// Checking image or not

$allow=array ( “jpg” => “image/jpg”, “jpeg” => “image/jpeg”, “png” => “image/png” );

If ( in_array ( $file_name , $allow ){     // Function checks specific value exist in array

die ( “Please upload image file”);

}

// Insert in to DB

$sql=”insert into user_data (first,last,dob,photo) values ( ‘ $fname ’ , ’ $lname ’,’ $dob’,’$file_name’)”;

$result = mysqli_query( $con , $sql );

// Finally Move the file to server folder

If($result){

$path=”/images/”;        //directory path to file moved

 move_uploaded_file ( $_FILES[‘uploadFile’][‘tmp_name’] , $path );

echo “File Uploaded Successfully”;

}

else{

echo “Failed to Upload”;

}

}

 

?>

Tagged ,

Leave a Reply