Output images stored in database MySQL with php - php

Snippet:
$connect = //connect to db;
$db = $connect->prepare("SELECT profilepicture FROM user WHERE uname = $uname");
$db->execute();
$db->bind_result($img);
...
echo $img;
Information:
- I have image.bin stored in a column of a table in db
- Opening image.bin in hex editor reveals hex codes (File header says it is a PNG file)
- echo $img doesn't output the image
Question:
- How to output images that are stored in db?

Form
<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>
This is how you upload the file
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$img = basename($_FILES["fileToUpload"]["name"]);
Your insert query
$db = $connect->prepare("UPDATE user SET profilepicture =? WHERE uname = ?");
$db->bind_param("si",$img,$uname);
$db->execute();
Taken from w3schools

Related

PHP Image upload not working, no data inserted into MySQL

I'm just creating a simple image upload to MySQL
<form method="post" action="quanly.php" class="form-group justify-content-center" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="image" name="image">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="col text-center">
<button type="submit" name="submit" id="add_btn" class="btn btn-primary mb-2"> <i class="fas fa-plus"></i>Submit</button>
</div>
</form>
And my php code:
$image = addslashes(file_get_contents($_FILES['image']['name']));
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
The image in MySQl is LONGBLOB.
THE PROBLEM: when I try to submit an image, no data was in the database
Remove file_get_contents from image tags.
$image = addslashes($_FILES['image']['name']);
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
<?php
$target_dir = "quanly/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$target_dir = "quanly/" - specifies the directory where the file is going to be placed.
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Try this..

How to upload two different image with two browse button and single submit button

I want to upload two images, one of the user and second of his ID, using one submit button using mysqli. Here is my HTML.
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
your image: <input type="file" name="img"><br/>
your Id card: <input type="file" name="img2">
<input type="submit" name="publish" value="upload">
</form>
</body>
</html>
All I know is to upload the single image at a time but what if want to upload these image into the database with single submit. I am not writing PHP because I don't know how to do this. I can upload multiple images at a time using an array but I want to use this method. Is it possible to do with PHP??
PHP for single upload:
<?php
$dir = "uploads/";
$t_file = $dir . basename($_FILES["img"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($t_file,PATHINFO_EXTENSION));
if(isset($_POST["upload"])) {
$check = getimagesize($_FILES["img"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I can do it by using javascript. All respected users, please be more helpful for those who are new to any language. Or make this website only for experts, not for beginners.
So I use PHP for my first upload and JS for my second image upload.
here is js:
<script>
function startUpload(){
document.getElementById('uploadProcess').style.visibility = 'visible';
document.getElementById('uploadForm').style.visibility = 'hidden';
return true;
}
function stopUpload(success,uploadedFile){
var result = '';
if (success == 1){
result = '<span class="sucess-msg">The file was uploaded successfully!<\/span><br/><br/>';
//Uploaded file preview
var embed = document.getElementById("UploadedFile");
var clone = embed.cloneNode(true);
clone.setAttribute('src',uploadedFile);
embed.parentNode.replaceChild(clone,embed);
}else {
result = '<span class="error-msg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('uploadProcess').style.visibility = 'hidden';
document.getElementById('uploadForm').innerHTML = result + '<label>File:<input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('uploadForm').style.visibility = 'visible';
return true;
}
</script>
The html:
<form action="upload.php" method="post" enctype="multipart/form-data" onsubmit="startUpload();">
<p id="uploadForm">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="file" name="myfile" id="fileToUpload1">
<input type="submit" value="submitBtn" name="submit">
</p>
</form>
and the upload.php:
<?php
$success = 0;
$uploadedFile = '';
//File upload path
$uploadPath = 'uploads/';
$targetPath = $uploadPath . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $targetPath)){
$success = 1;
$uploadedFile = $targetPath;
}
sleep(1);
?>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

Unable to upload image in wordpress admin page

I am trying to add a form to upload images in the user profile admin page in wordpress, i had tried this code before and it was working fine in a normal php page but when i tried it in this wordpress function it is not working.
Can someone help with this?
function image_up_gall(){
?>
<form action="#" 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>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
add_action('edit_user_profile', 'image_up_gall');
add_action('show_user_profile', 'image_up_gall');
First of all edit_user_profile and show_user_profile action hooks don't have to save the image, you can just add a field there. So
function image_up_gall(){
?>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
<?php
}
add_action('edit_user_profile', 'image_up_gall');
add_action('show_user_profile', 'image_up_gall');
It is because WordPress has its own form tag already, just make sure that it has enctype="multipart/form-data"
Second step, using personal_options_update and edit_user_profile_update you can save the form/upload imag, to do so, use this code:
function save_profile_fields( $user_id ) {
$target_dir = "uploads/"; // I recommend to use wp_upload_dir() to get the correct path
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// here the image is uploaded and we can save it to user profile with:
update_usermeta( $user_id, 'profile_pic', $target_file );
}
}
add_action( 'personal_options_update', 'save_profile_fields' );
add_action( 'edit_user_profile_update', 'save_profile_fields' );
But I recommend you to use WordPress default media library to do that, there is a lot of code, so I better give you a link to the tutorial: https://rudrastyh.com/wordpress/customizable-media-uploader.html
you can try this bellow
if (isset($_FILES["file"]["name"])) {
$destination = $_POST["dir"];
$name = $_FILES["file"]["name"];
$tmp_name = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
//echo $name;
//echo $tmp_name;
//echo $error;
move_uploaded_file($_FILES['file']['tmp_name'], $destination.$name);
}

Why won't my image files upload in PHP?

I want my users to be able to upload images to their account (my MySQL database). However, when I try to encode it and upload it, it appears that the file was never uploaded and is empty. I have checked the maximum upload size etc. in my PHP settings. Thanks in advance!!
$data = "";
if(isset($_FILES["up"])) {
$data = file_get_contents($_FILES['up']['tmp_name']);
$data = base64_encode($data);
$data = $connection->real_escape_string($data);
} else {
echo '<div style="position:absolute;height:100px;top:0px;left:0px;
border-top-right-radius:20px;border-top-left-radius:20px;
width:100%;background:white;z-index:100;"
>
<font style="color:#BB0000;font-size:2.2vw;">'.$_FILES['up']['error'].'</font>
</div>';
die('');
}
My HTML is: (And the form submits correctly)
<input type="file" accept=".jpg,.png,.jpeg" name="up" id="up"/>
Suggestion: store the images in a directory.
why not DB you ask?
read/write to a DB is always slower than a filesystem
your DB backups will become more time consuming
so, here is my solution.
STEP 1: create a directory userPhotos
STEP 2: create a form
<form action="upload.php" method="post" enctype="multipart/form-data">
Select your profile picture:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="Upload" value="Upload Image" name="submit">
</form>
STEP 3: create a file called upload.php which handles file uploads.
<?php
$target_dir = "userPhotos/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$newfilename = ;//assign unique user ID
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
if (move_uploaded_file($_FILES["fileToUpload"][$newfilename.$imageFileType], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";$uploadOk = 1;
}
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
if($uploadOK==1){
store the path of image in DB as "/userPhotos/".$newfilename
echo "uploaded photo : <img src='userphotos/".$newfilename."'">
}
//to display the image fetch the path using user ID as put it in src of img tag.
?>
Let me know if anyone has a better solution. thanks and Good luck.
PHP Code
$data = "";
if(isset($_FILES["up"])) {
$data = file_get_contents($_FILES['up']['tmp_name']);
$data = base64_encode($data);
$data = $connection->real_escape_string($data);
} else {
echo '<div style="position:absolute;height:100px;top:0px;left:0px;
border-top-right-radius:20px;border-top-left-radius:20px;
width:100%;background:white;z-index:100;"
>
<font style="color:#BB0000;font-size:2.2vw;">'.$_FILES['up']['error'].'</font>
</div>';
die('');
}
HTML Code
<form method="POST" enctype="multipart/form-data">
<input type="file" accept=".jpg,.png,.jpeg" name="up" id="up"/>
</form>

Wordpress: PHP multiple file upload

I have a HTML form for a file upload, which sends the uploaded file to the backend directory of my wordpress site. How can I enable multiple file uploads? I tried simply adding multiple="multiple" to my file upload form (which allowed me to select multiple files) but in the directory only one file is uploaded. Here is the form:
<form action="http://www.aerex.co.uk/php-upload/" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" multiple="multiple">
<input type="submit" value="Upload Image" name="submit">
</form>
The PHP for the action page:
<?php
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/';
$target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
You change this
<form action="http://www.aerex.co.uk/php-upload/" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload[]" id="fileToUpload" multiple="multiple">
<input type="submit" value="Upload Image" name="submit">
</form>
and your php
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/';
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['fileToUpload']['name'] as $f => $name) {
if(isset($_POST["submit"])) {
$target_file = $target_dir . '/' . basename($_FILES["fileToUpload"]["name"][$f]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$f], $target_file);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$check = getimagesize($target_file);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
}
}

Categories