php image upload and display code example
Example 1: how to upload image in php and store in database and folder
$Get_image_name = $_FILES['image']['name'];
$image_Path = "images/".basename($Get_image_name);
$sql = "INSERT INTO student_table (imagename, contact) VALUES ('$Get_image_name', 'USA')";
mysqli_query($conn, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $image_Path)) {
echo "Your Image uploaded successfully";
}else{
echo "Not Insert Image";
}
}
Example 2: basic code for file upload in php
//This is the minimal code for an image upload for first time learners
//html portion
<!DOCTYPE html>
<html>
<head>
<title>ImageUpload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label>Username</label>
<input type="text" name="username">
<br>
<label>UploadImage</label>
<input type="file" name='myfile'>
<br/>
<input type="submit" value="upload">
</form>
</body>
</html>
//php portion
<?php
$user=$_POST['username'];
$image=$_FILES['myfile'];
echo "Hello $user <br/>";
echo "File Name<b>::</b> ".$image['name'];
move_uploaded_file($image['tmp_name'],"photos/".$image['name']);
?>
Example 3: how to place the path of an uploaded image in a database on an html file input
<?php
include("config.php");
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$extensions_arr = array("jpg","jpeg","png","gif");
if( in_array($imageFileType,$extensions_arr) ){
$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Example 4: how to upload image in php
<!DOCTYPE html><html><body><form action="upload.php" method="post"
enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit">
</form></body></html>