How to use function move_uploaded_file in php - php

This code in "upload.php"
<?php
session_start();
$id = $_SESSION['user_id'];
$pic = $_FILES['pic']["name"];
$folder = "../images/users/";
move_uploaded_file($_FILES['pic']["tmp_name"], "$folder".$pic);
$mysqli = connectDB();
upload($id,$pic,$mysqli);
?>
Function upload
function upload($id,$pic,$mysqli)
{
$pic = $mysqli->real_escape_string($pic);
$sql = "UPDATE users SET pic = '$pic' WHERE id = '$id'";
$result = $mysqli->query($sql);
}
and this code in html
<form name="submit" action="include/upload.php" method="post">
<input type="file" value="Choose file" accept="image/*" id="pic" name="pic">
<input type="submit" value="Upload" name="submit">
</form>
It's not working. Image not move folder and image path not insert in database.

Instead of:
move_uploaded_file($_FILES['pic']["tmp_name"], "$folder".$pic);
You can just do:
move_uploaded_file($_FILES["pic"]["tmp_name"], $folder.$pic); // Note the single / double quotes
But even easier:
<?php
session_start();
$id = $_SESSION['user_id'];
$pic = $_FILES["pic"]["name"];
$folder = "../images/users/";
$path = $folder.$pic; // New variable
if( move_uploaded_file($_FILES["pic"]["tmp_name"], $path) ) {
$mysqli = connectDB();
if( upload($id, $path, $mysqli) ) {
echo 'File uploaded';
} else {
echo 'Something went wrong uploading file';
}
} else {
echo 'Something went wrong uploading file';
}
So the function becomes:
function upload($id, $path, $mysqli)
{
$path = $mysqli->real_escape_string($path);
$sql = "UPDATE `users` SET `pic` = '$pic' WHERE `id` = $id";
$result = $mysqli->query($sql);
return $result; // returns true or false
}
Adding backticks around table and column names prevents an error called mysql reserved words. Because the $id is an integer (in most cases). You shouldn't quote it. This is because you make a string from an integer which is something you don't want to do as integers are faster and saver to use.
To make html clear you want to upload a file you need to add something to your form. So the form becomes:
<form name="submit" action="include/upload.php" method="post" enctype="multipart/form-data">
<input type="file" value="Choose file" accept="image/*" id="pic" name="pic">
<input type="submit" value="Upload" name="submit">
</form>

form tag should be in the format :
< form name="submit" action="include/upload.php" method="post" enctype="multipart/form-data" >
(add enctype="multipart/form-data" in form tag, this will solve your problem.)

Related

The image cannot be displayed because it contains errors (php)

I would like to display an image stored in my database but I keep getting that error.
The image is stored in my database as longblob.
I upload it using this piece of code in upload.php:
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" />
<input type="submit" name="submit" value="UPLOAD" />
</form>
<?php
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
/*
* Insert image data into database
*/
//Insert image content into database
$insert = $pdo->query("UPDATE users SET image='".$imgContent."'"."WHERE id_user = ".$posts[0]->get_id());
if ($insert) {
echo "File uploaded successfully.";
} else {
echo "File upload failed, please try again.";
}
} else {
echo "Please select an image file to upload.";
}
}
?>
Then I try to display it in getImage.php:
<?php
$id = $_GET['id'];
$query = $pdo->prepare('SELECT * FROM users WHERE username LIKE :us');
$query->bindValue(':us', $_SESSION['login'], PDO::PARAM_STR);
$query->execute();
$user = $query->fetchAll(PDO::FETCH_CLASS, "User");
header ('Content-Type: image/png');
echo $user[0]->get_image();
?>
When I go however to /getImage.php?id=1, I have the error
The image cannot be displayed because it contains errors
What am I doing wrong?
Solved: I added ob_end_clean(); before the header and it worked.

Unable to upload the images to mySQL database

Still a newb to coding . have almost no idea what im doing . i tried to make a php page which would let me upload and view an image . do not know what is wrong . i tried to do it as correctly as possible . could someone please help me out ?
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post">
<input type="file" name="image"></input>
<input type="submit" name="submit" value="upload"></input>
<?php
if(isset($_POST['submit']))
echo "button has been clicked";
$con = mysqli_connect("127.0.0.1","root","","demo");
if(!$con)
echo "didnt connect to database ";
else echo "connected ";
$imagename= mysqli_real_escape_string($_FILES['image'] ['name']);
$imagefile =mysqli_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$qry = "INSERT INTO image (name,file) VALUES ('$imagename','$imagefile')";
$result = mysqli_query($con,$qry);
if($result)
echo "image has been uploaded";
viewimage();
function viewimage()
{$recon = mysqli_connect("127.0.0.1","root","","demo");
$view = "SELECT * FROM image ";
$data =mysqli_query($recon,$view);
$res2 =mysqli_fetch_assoc($data);
$currimage =$res2['file'];
echo "$currimage <br/>";
}
?>
</body>
</html>
To be able to catch a post variable, you need to submit the form and handle the action. The first problem with your code is that your form is not complete - it's missing a closing tag. Second thing, to be able to send a file through the post, you'll need multipart form. You should add enctype="multipart/form-data" as an attribute of the form.
So, instead of
<form method="post">
<input type="file" name="image"></input>
<input type="submit" name="submit" value="upload"></input>
You'll need
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"></input>
<input type="submit" name="submit" value="upload"></input>
</form>
you must move the uploaded image to server
try this code -- create directory /uploads/
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"></input>
<input type="submit" name="submit" value="upload"></input>
<?php
if(isset($_POST['submit']))
echo "button has been clicked";
$con = mysqli_connect("127.0.0.1","root","","demo");
if(!$con)
echo "didnt connect to database ";
else echo "connected";
$uploads_dir = '/uploads';
$tmp_name = $_FILES["image"]["tmp_name"];
$name = $_FILES["image"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$qry = "INSERT INTO image (name,file) VALUES ('$name','$tmp_name')";
$result = mysqli_query($con,$qry);
if($result)
echo "image has been uploaded";
viewimage();
function viewimage()
{$recon = mysqli_connect("127.0.0.1","root","","demo");
$view = "SELECT * FROM image ";
$data =mysqli_query($recon,$view);
$res2 =mysqli_fetch_assoc($data);
$currimage =$res2['file'];
echo '<img src="'.$currimage.'" /> <br/>';
}
?>
</body>
</html>

PHP Fail to upload image

test.php file
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo "Please select an image";
}
else
{
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveimage($image);
}
}
function saveimage($image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("food",$con);
$query = "INSERT INTO info(image) VALUES ('$image')";
$result = mysql_query($query,$con);
if($result)
{
echo "<br> Image upload";
}
else
{
echo "<br> NOT";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("food",$con);
$query = "SELECT image from info";
$result = mysql_query($query,$con);
$row=mysql_fetch_array($result);
echo '<img src="data:image/jpeg;base64,'.$row["image"].'" width="200" height="200"/>';
}
?>
html file
<form method="post" action="test.php">
<label>Image:</label>
<input type="file" name="image"><br>
<input class="btn btn-primary" type="submit" name="submit" value="Confirm" style="height:50px; width:100px;">
<br><br>
</form>
Now i want to display the picture. But i keep getting a blank picture instead. Is there any problem with my display code there? Thanks
/dummy//aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa//dummy
add enctype="multipart/form-data" in your form
<form method="post" action="test.php" enctype="multipart/form-data">
Your are missing enctype="multipart/form-data" in your form tag.
The enctype attribute specifies how the form data should be encoded when submitting it to the server.
Note: The enctype attribute can be used only with method="post".
Add enctype="multipart/form-data" to your form tag.
you make a POST request, you have to encode the data that forms the body of the request.
When writing client-side code,you need to use multipart/form-data if your form includes any elements.

Upload multiple images to Database MYSQLI

I am planning to have a web gallery. However, it is hard for me to use PHP to insert DB. The following code:
HTML -- I want to make a form which has category and multiple images that can be inserted into DB at the same time.
<form action="upload" method="POST" enctype="multipart/form-data">
<p> Upload : <input type="file" id="file" name="images" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<p> <input type="submit" name="submit" value="Upload!" /> </p>
</form>
DATABASE
I am using imageName as VARCHAR not BLOB TYPE.
PHP
<?php
include ("dbConnect.php");
if(isset($_POST["submit"])) {
$image = $_POST['images']['tmp_name'];
$imageName = $_POST['images']['name'];
$imageSize = $_POST['images']['size'];
$imageType = $_POST['images']['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
?>
The problem is, the category is the only one has inserted into the database successfully. But not with the imageName, imageType, and imageSize. And also i want the image to be stored into database so that I can retrieve the image from DB on the other web page. Any ideas?
You can use 'multiple' property in the 'input' tag like this :
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" multiple='multiple' /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
User can select multiple files and upload them.
And at the server you will do this :
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageName = $_FILES['userfile']['name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
$imageCategory = $_POST['imageCategory'];
$len = count($image);
$path = "images/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType) VALUES ('$imageName[$i]', '$imageCategory', '$imageSize[$i]' , '$imageType[$i]' )");
}
}
}
}
$mysqli->close();
header("location: index");
First off the file information won't be in the $_POST global variable it will be in the $_FILES
From http://php.net/manual/en/features.file-upload.multiple.php (modified):
Form
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<p> <input name="userfile[]" type="file" /> </p>
<p> <input name="userfile[]" type="file" /> </p>
<p> Category : <input type="text" name="imageCategory"> </p>
<input type="submit" value="Send files" />
</form>
Parse the global file variable to an array (we'll assume this is a helper function called parseFiles.php):
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Move the files and insert the file information into the database :
<?php
include ("dbConnect.php");
include ("parseFiles.php");
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$image = $file['tmp_name'];
$imageName = $file['name'];
$imageSize = $file['size'];
$imageType = $file['type'];
$imageCategory = $_POST['imageCategory'];
$result = $mysqli->query("INSERT INTO imageTable (imageName, imageCategory, imageSize, imageType)
VALUES ('$imageName', '$imageCategory', '$imageSize' , '$imageType' );")
or die(mysqli_error($mysqli));
}
} else {
echo "<p> It is not working </p>";
}
header("location: index");
$mysqli->close();
Hopefully that should do the job. I've not tested this I've just blind coded it so there may be some bugs

file upload script not working with variables

I have a PDF uploader that is supposed to save a file to a file path that is based off of a username variable selected from a drop down menu.
Everything works but the uploader, as it displays the usernames and the directories are created upon registration. So there is no issue with that. My issue lies within the code below with the uploader:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pdf" /><br />
<select name="folder">
<?php
$con=mysqli_connect("host","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `first_name`, `last_name`, `username` FROM `cw_users` WHERE 1");
$user = 'username';
while($row = mysqli_fetch_array($result)) {
echo "<option value='". $row["username"] ."'>";
echo " $row[username] ";
echo "</option>";
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit'])) {
$pdfDirectory = "Users/".$_POST['folder']."/uploaded/";
//get the name of the file
$filename = basename( $_FILES['pdf']['name'], ".pdf");
//remove all characters from the file name other than letters, numbers, hyphens and underscores
$filename = preg_replace("/[^A-Za-z0-9_-]/", "", $filename).".pdf";
if (move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfDirectory.$filename)) {
//the path to the PDF file
$pdfWithPath = $pdfDirectory.$filename;
}
}
?>
</select>
<input type="submit" value="Upload pdf" name="upload_pdf" />
</form>
P.S. if this could be adjusted to upload multiple files at the same time that would be great.
Your conditional statement if(isset($_POST['submit'])) is looking for a submit button named "submit", yet yours is named "upload_pdf".
<input type="submit" value="Upload pdf" name="upload_pdf" />
^^^^^^^^^^^^^^^^^
That should either read as if(isset($_POST['upload_pdf'])) or rename your submit button to:
<input type="submit" value="Upload pdf" name="submit" />

Categories