PHP Image upload not working, no data inserted into MySQL - php

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..

Related

How to upload photos/file to server using PHP

Hi so I'm trying to allow users to upload a photo to a listing. I'm using dropzone.js and I have the form done, it works perfectly! except that photos don't actually upload to the folder "uploads/"
I have tried many many different ways spent days researching and I cannot for the life of me figure out what is wrong.
Kindly note that it is a multipage form so I cannot post the whole form on here but ill try to share the important scripts!
Dropzone code:
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" method="post" type="file" name="file" class="dropzone" id="dropzonewidget" enctype="multipart/form-data">
</div>
</div>
</div>
</div>
<div class="row form-block flex-column flex-sm-row">
<div class="col text-center text-sm-start"><a class="btn btn-link text-muted" href="user-add-2.php"> <i class="fa-chevron-left fa me-2"></i>Back</a>
</div>
<div class="col text-center text-sm-end"><button type="submit" name="save" class="btn btn-primary">save</button><i class="fa-chevron-right fa ms-2"></i></div>
</form>
Now for the PHP script: I have 2 attempts that got close, the first actually makes its way into the database and the second just echo's all error scripts
Script 1: (kinda works)
$uploadDir = 'var/www/uploads';
$tmpFile = $_FILES['file']['tmp_name'];
// upload file to directory
$fileName = $uploadDir.'/'.time().'-'. $_FILES['file']
['name'];
move_uploaded_file($tmpFile,$fileName); {
$sql = "INSERT INTO hosts(id, user_name, name, type,
country, city, state, zip, about, price, photo)
VALUES('$id', '$user_name', '$name',
'$type', '$country', '$city', '$state', '$zip',
'$about', '$price', '$fileName')";
Script 2:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]
["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png"
&& $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are
allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"],
$target_file)) {
echo "The file ". htmlspecialchars( basename(
$_FILES["file"]["name"])). " has been uploaded.";
//$pictureName = "uploads". basename(
$_FILES["fileToUpload"]["name"]);
} else {
echo "Sorry, there was an error uploading your
file.";
}
At the end of both of these attempts I have a simple insert query (p.s. I know about SQL injections, just trying to get it to work first.)
hope I didn't give you a headache
Just a heads up I am new to PHP and to SO so be kind and I hope a more experienced developer can help me out of these troubling times! Thanks in advance, and if you understand my issue please post some code not a vague response :) cheers
For dropzone uploads (multiple file uploads)
a. you do NOT need to specify enctype="multipart/form-data" and method="post" type="file" name="file"
b. No need to use submit button
c. As stated before, make sure there is a sub-folder known as uploads and it is write-permitted
d. To do further db maninpulation (e.g. insert), execute the insert query in the php , make sure using $_FILES['file']['name'] when constructing the insert query
Hence, please amend your code to:
HTML
<head>
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
</head>
<div class="container" >
<div class='content'>
<form action="create.php" class="dropzone" id="dropzonewidget">
</form>
</div>
</div>
create.php
<?php
$target_dir = "./uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir.$_FILES['file']['name'])) {
$status = 1;
// do further update in database
// please note that the file name is $_FILES['file']['name']
// make sure you use parametized prepared statement in your insert query
// to avoid SQL injection attacks
//
}
?>

Can't post data along with large file size upload PHP

I am trying to upload file along with some data in form. It is working perfectly fine for small files. But, when I am trying to submit data along with large files, it is not capturing data.
This is Form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<input type="text" class="form-control" name="title" required placeholder="Title">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<input type="file" class="form-control" name="report" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<center>
<input type="submit" name="upload_report" value="Upload" class="btn btn-primary btn_font">
</center>
</div>
</div>
</form>
PHP Code:
if(isset($_POST["upload_report"])) {
echo $_POST['title']; // giving title index undefined
$max_report_id += 1;
$target_dir = "Reports/";
$file_title = mysqli_real_escape_string($connection,trim($_POST['title']));
$file_name = mysqli_real_escape_string($connection,trim($_FILES['report']["name"]));
//$file_size = mysqli_real_escape_string($connection,trim($_FILES['report']["size"]));
$target_file = $target_dir . basename($file_name); //basename gets filename from path
$uploadOk = 1;
$file_type = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = $target_dir . $max_report_id . "." . $file_type;
// Check if file already exists
if (file_exists($target_file)) {
//echo "Sorry, file already exists.";
$uploadOk = 0;
}
/* Check file size
if ($file_size > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
*/
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$status_fail = true;
$fail_message = "Sorry, there was an error uploading your file.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["report"]["tmp_name"], $target_file)) {
$status_success = true;
$success_message = "The file ". $file_title. " has been uploaded.";
$query = "insert into reports(title,fname,path,platform,added_by,added_on) values ('$file_title','$file_name','$target_file','$platform','$user_id',now())";
$result = mysqli_query($connection, $query) or die($query);
}
else {
$status_fail = true;
$fail_message = "Sorry, there was an error uploading your file.";
}
}
}
I have enough updated max_post_size, memory_limit, max_upload_size in php.ini file.
The default PHP values are 2 MB for upload_max_filesize, and 8 MB for post_max_size. Depending on your host, changing these two PHP variables can be done in a number of places with the most likely being php.ini or .htaccess (depending on your hosting situation).
You need to set the value of upload_max_filesize and post_max_size in your php.ini :
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M (ex. 40MB and you can change more size)
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M (ex. 40MB and you can change more size)
After modifying php.ini file(s), you need to restart your HTTP server to use new configuration.

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

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