Why won't my image files upload in PHP? - 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>

Related

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.";
}
}
?>

Output images stored in database MySQL with 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

PHP: `move_uploaded_file` isn't properly accessing `tmp_name` of user submited file

I've been struggling for the past couple days to submit an image through a form and have my php script save it in the designated directory. I've tried using $.ajax, I've tried using XMLHttpRequest, and now I've just copied a simpler script from here and tweaked it.
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file) evaluates to falseand I don't believe any warnings are given, so according to the documentation, there was a problem accessing the file.
The script response is
/private/var/tmp/phpwwBaBr
Sorry, there was an error uploading your file.
Also, the error code from echo $_FILE['fileToUpload']['error']; is 0, which means the upload is successful, yet still no file in ../includes/galleryImages/.
Here's the code:
<form action="archive_upload.php" id='file_form' method="post" enctype="multipart/form-data" accept-charset='UTF-8'>
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "../includes/galleryImages/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
}
echo $_FILES["fileToUpload"]["tmp_name"].'<br>';
/* This is the line that returns false */
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo basename( $_FILES["fileToUpload"]["name"] ). " has been uploaded.<br>";
} else {
echo "Error uploading file.<br>";
}
?>

Simple PHP/HTML upload page - no files are saving

I'm new to HTML/PHP and I'm trying to create a simple php file upload page.
I have this as my HTML
<!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>
I have this as my php:
<?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(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;
}
}
?>
I've uploaded both of these to the correct folder in my host (000webhost), yet when I check in my /uploads folder nothing is there. I've granted all my files read write and execute permissions to try and debug it - I'll learn about security later.
Any help would be greatly appreciated!
You must add this snippet of code:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
after that:
echo "File is an image - " . $check["mime"] . ".";
You need to move the uploaded file from the temp directory it was uploaded into, into your target directory. See the PHP docs of move_uploaded_files
With the PHP function move_uploaded_file(string $filename, string $destination) you can move the file to your desired path.

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories