Superior University Depalpur

 

Suppose that if you want to create some dynamic pagez in php with some profile photoz for different userz. What will you do???? Uploading the photos directly to your database will make it heavy and difficult to load.Here we will learn how to upload a photo into a directory in your server and save the path in your sql database from a form so that you can display the images in your websites.We will see all things step by step.That will give you clear understanding.


Step 1:Create a form named form.php.
<form action=”insert.php” method=”post” enctype=”multipart/form-data” role=”form”>
<input name=”file” type=”file”>
<input type=submit >
</form>
Now your simple form with a single input is ready.On clicking submit button,you will be redirected to the page ‘insert.php’.
Step 2:Create a file insert.php
<?php
$allowedExts = array(“gif”, “jpeg”, “jpg”, “png”);//you can add more extensions if required
$temp = explode(“.”, $_FILES[“file”][“name”]);
$extension = end($temp);
if ((($_FILES[“file”][“type”] == “image/gif”)
|| ($_FILES[“file”][“type”] == “image/jpeg”)
|| ($_FILES[“file”][“type”] == “image/jpg”)
|| ($_FILES[“file”][“type”] == “image/pjpeg”)
|| ($_FILES[“file”][“type”] == “image/x-png”)
|| ($_FILES[“file”][“type”] == “image/png”))
&& ($_FILES[“file”][“size”] < 200000)
&& in_array($extension, $allowedExts))
{
if ($_FILES[“file”][“error”] > 0)
{
echo “Return Code: ” . $_FILES[“file”][“error”] . “<br>”;
}
else
{
echo “Upload: ” . $_FILES[“file”][“name”] . “<br>”;
echo “Type: ” . $_FILES[“file”][“type”] . “<br>”;
echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” kB<br>”;
echo “Temp file: ” . $_FILES[“file”][“tmp_name”] . “<br>”;
if (file_exists(“upload/” . $_FILES[“file”][“name”]))
{
echo $_FILES[“file”][“name”] . ” already exists. “;
}
else
{
$imgpath=”upload/” . $_FILES[“file”][“name”];
move_uploaded_file($_FILES[“file”][“tmp_name”],
“upload/” . $_FILES[“file”][“name”]); //storing image into upload folder
echo “Stored in: ” . “upload/” . $_FILES[“file”][“name”]; //displaying the path
}
}
}
else //matching the extensions
{
echo “Invalid file”;
}
//here starts the database
$con=mysqli_connect(“localhost”,”root”,”password”,”databasename”);
// Check connection
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}
//query starts here
$imgpath=”admin/upload/” . $_FILES[“file”][“name”];//image path stored in variable imgpath
$query=”insert into tablename(imgpath) values(‘$imgpath’)”; //sql query to upload path to table
//query ends here
if (!mysqli_query($con,$query))
{
die(‘Error: ‘ . mysqli_error($con));
}
echo “1 record added”;
mysqli_close($con);
?>
Note1:All the lines after “//” is a comment line and need not insert it in the script.It is only for your understanding
Note2:You should create a folder “upload” in the same directory
Done..!!now you can enjoy uploading photos smoothly and have fun.

Post a Comment

 
Top