In my code, I have a file input which I use along with textareas, my HTML form looks like this:
<form action="includes/listing1.inc.php" method="post" enctype="multipart/form-data">
<input type="file" name="image_file">
<textarea name="title" cols="30" rows="2" placeholder="Title"></textarea>
<textarea name="description" cols="50" rows="5" placeholder="Description"></textarea>
<textarea name="price" cols="5" rows="1" placeholder="Price"></textarea>
<select multiple="multiple" name="categories">
<option value="bla1">bla1</option>
<option value="bla2">bla2</option>
<option value="bla3">bla3</option>
<option value="bla4">bla4</option>
<option value="bla5">bla5</option>
</select>
<input type="hidden" name="vendor" value="<?php $_SESSION['UserUid']; ?>">
<input type="submit" name="listpost-submit" value="Post listing">
Notice I have the file input and the enctype="multipart/form-data", I have this PHP code:
<?php
if (isset($_POST['listpost-submit'])) {
require 'dbh.inc.php';
$filename = $_FILES['image_file']['name'];
$target = 'site_images/';
$filetarget = $target.$filename;
$tempfilename = $_FILES['image_file']['name'];
$title = $_POST['title'];
$description = $_POST['description'];
$price = $_POST['price'];
$cat = $_POST['categories'];
$vendor = $_POST['vendor'];
$result = move_uploaded_file($tempfilename, $filetarget);
if ($result == true) {
echo '<div>Your file has been uploaded!</div>';
$sql = "INSERT INTO listings
(`image`,`title`,`description`,`price`,`category`,`vendor`,`imgpath`)
VALUES ('$filename', '$title', '$description', '$price', '$cat', '$vendor',
'$filetarget')";
header("Location: ../index.php?listing=posted");
exit();
}
elseif (empty($title) || empty($description) || empty($price) || empty($cat)
|| $vendor) {
echo '<div>Something is missing!</div>';
exit();
}
else {
echo '<div>There was a problem uploading your file!</div>';
exit();
}
}
mysqli_close($conn);
Database structure:
idListings(int) imgListings(varchar(200)) titleListings descriptionListings priceListings categoryListings vendorListings imgpathListings(varchar(250))
At the moment if I run the code it will tell me that the file can't be uploaded, I tried changing to a file with no spaces in between but that didn't work either, my question is how I can fix this so that all files can be stored in the database. Please tell me if the information is inadequate!
Found it. You need to user index tmp_name that is the original filename on the /tmp folder.
Change from:
$tempfilename = $_FILES['image_file']['name'];
To:
$tempfilename = $_FILES['image_file']['tmp_name'];
It should work.
Related
I'm trying to upload an image of my HTML form into my MySQL blob column. the insertion is done successfully but the display of the image does not work properly knowing that images inserted directly into MySQL are displayed correctly.
HTML code:
<form class="form-horizontal" method='POST' action="add_question_submit.php" id="addQuestionForm" enctype="multipart/form-data">
<div class="form-group">
<textarea rows="4" cols="50" name="question" form="addQuestionForm" placeholder="Enter Question in brief.... " required></textarea><br>
<input type="file" class="form-control" id="image" name="image" required><br>
<input type="text" class="form-control" id="answer" placeholder="Enter Correct Answer" name="answer" required><br>
<input type="number" class="form-control" id="category_id" placeholder="Enter category id (only numeric)" name="category_id" required><br>
<input type="number" class="form-control" id="level_id" placeholder="Enter level id (only numeric)" name="level_id" required><br>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</div>
</form>
PHP code:
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)VALUES('$question', '$image','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
display_question.php :
<td><?php echo '<img src="data:image/png;base64,'.base64_encode($row['image']).'" />'; ?></br><br/></td>
Below is the function which will upload the images to specific folder.
You can all below function like:
Param 1: is the folder where we need to store the new image
Param 2: is FILES
Param 3: if any prefix for the image we need to pass it.
Param 4: if there is any previously uploaded image for same record. It should be deleted from the folder. Generally it is usefull when you are editing particluar record.
uploadfile("profile",$_FILES,"profile_pic");
Code is here:
function uploadfile($folder,$data,$preFix = "logo_",$previousImage="") {
$location = (pathinfo($_SERVER['SCRIPT_FILENAME']));
$uploads_dir = $location['dirname'] . "/assets/uploads/" . $folder . "/";
$fileNames = "";
$tmp_name = $data["tmp_name"];
$name = $data["name"];
$fileExtension = pathinfo($name, PATHINFO_EXTENSION);
$newfilename = $preFix . date("ymdhms") . '.' . $fileExtension;
$fulldest = $uploads_dir . $newfilename;
if (move_uploaded_file($tmp_name, $fulldest)) {
if($previousImage != "")
$this->removePreviousImage($folder, $previousImage); //deleting existing image
return $newfilename;
} else {
exit("Error File Uploading");
}
}
First you are storing the wrong information onto the database, you are storing the file size and not the encoded image.
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)
VALUES('$question', '$file_temp','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
Second, if you have stored the base64 encoded version of the file onto the database you do not need encode it again when you retrieve it from the database so your <img> tag should be
<?php echo "<img src='data:image/png;base64,$row[image]'/>"?>
</br><br/></td>
And thirdly and most importantly you need to be using parameterise bound queries to protect your app from SQL Injection Attack
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions
(question_name, image, answer, category_id,level_id)
VALUES(?,?,?,?,?)";
$stmt = $conn->prepare($query);
$stmt->bind_params('sssss', $question,
$file_temp,
$answer,
$category_id,
$level_id);
$result = $stmt->execute();
if (!$result) {
echo $conn->error;
}
header("Location: display_question.php");
Here is how the site looks like to give you an idea.
I would like to show the image he entered instantly after he clicked Bestand kiezen (= translates to chose file). How it works now is that it only shows the filename, how can I show a preview of the image instantly? The image and the other info is only inserted in the DB after clicking the add post button.
Is this supposed to be done with ajax?
The addpost.php code
<?php
include_once('classes/Post.class.php');
include_once('classes/User.class.php');
User::checklogin();
$post = Post::ShowPosts();
if(! empty($_POST)) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if (in_array($fileActualExt, $allowed)){
if ($fileError === 0){
if ($fileSize < 10000000){
$fileNameNew = uniqid('', true).".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
print_r($fileDestination);
move_uploaded_file($fileTmpName, $fileDestination);
$feedback = "Post has been saved.";
$title = $_POST['title'];
$desc = $_POST['description'];
$filter = $_POST['filter'];
$date = date("Y-m-d H:i:s");
$location = "";
$userid = $_SESSION['userid'];
$newPost = new Post();
$newPost->setTitle($title);
$newPost->setPicture($fileDestination);
$newPost->setDescription($desc);
$newPost->setDate($date);
$newPost->setUserId($userid);
$newPost->setLocation($location);
$newPost->setFilter($filter);
$newPost->AddPost();
$postId = Post::getLastId();
$string = $_POST['tag'];
$tags = explode(',' , $string);
foreach($tags as $t) {
$newPost->setTag($t);
$newPost->AddTags($postId);
}
} else{
$feedback = "Your file is too big.";
}
} else{
$feedback = "There was an error uploading your file.";
}
} else{
$feedback = "You cannot upload files of this type.";
}
}
?><!DOCTYPE html>
<html lang="en">
<body>
<form action="" method="post" enctype="multipart/form-data">
<h1 form__title>Add post</h1>
<?php if(isset($feedback)): ?>
<div class="feedback">
<p><?php echo $feedback; ?></p>
</div>
<?php endif; ?>
<div class="form__field">
<label for="title" class="label">YOUR SHOT TITLE:</label> <br/>
<input class="form__input" type="text" name="title">
</div>
<div class="form__field">
<label for="file" class="label">UPLOAD PICTURE</label><br/>
<input class="form__input" type="file" name="file" class="fileToUpload">
</div>
<div class="form__field">
<label for="description" class="label">DESCRIPTION</label><br/>
<textarea name="description" cols="25" rows="5"></textarea>
</div>
<div class="form__field">
<label for="tag" class="label">ADD SOME TAGS TO YOUR SHOT (seperated with , )</label><br/>
<input class="form__input" type="text" name="tag">
</div>
<p>JPG, GIF or PNG. Snapshots are 400 × 300 pixels or 800 × 600 (for HiDPI displays). </p><br/><br/>
<div class="form__field">
<label for="tag" class="label">ADD ONE (Instagram) FILTER TO YOUR SHOT </label><br/>
<select name="filter">
<option value="_1977">1977</option>
<option value="aden">aden</option>
<option value="xpro2">xpro2</option>
</select>
</div>
<div class="form__field">
<input class="btn_style" type="submit" name="submit" value="Add post"">
</div>
</form>
</body>
</html>
The Addpost function
public function AddPost(){
$conn = db::getInstance();
$query = "insert into posts (post_title, picture, description, filter, location, user_id, post_date) values (:post_title, :picture, :description, :filter, :location, :user_id, :post_date)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_title',$this->getTitle());
$statement->bindValue(':picture',$this->getPicture());
$statement->bindValue(':description',$this->getDescription());
$statement->bindValue(':filter', $this->getFilter());
$statement->bindValue(':location',$this->getLocation());
$statement->bindValue(':user_id',$this->getUserId());
$statement->bindValue(':post_date',$this->getDate());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
HTML - Display image after selecting filename
answers the question nicely with a javascript snippet look down at the first answer
I have checked out other questions of same topic on this site and tried to find the solution but unsuccessful. Images are stored in database and loaded in folder successfully but are not displayed
Here is my code:
<html>
<body>
<form action="image.php" method="post" enctype="multipart/form-data">
<input type="text" name="image_description" placeholder="Enter name" required>
<input type="file" name="myfile">
<input type="submit" name="upload" value="upload">
</form>
</body>
</html>
<?php
include("db.php");
if(isset($_POST['upload'])) {
$image_description = $_POST['image_description'];
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
$upload=move_uploaded_file($temp, "uploaded/" . $name);
$query= "INSERT INTO image(image_description,image_name,image_type,image_size) VALUES ('$image_description','$name','$type','$size')";
if(mysqli_query($conn,$query) && $upload) {
echo "successfully uploaded";
}
else
die(mysqli_error($conn));
}
$query = mysqli_query($conn,"SELECT * FROM image");
while($row = mysqli_fetch_array($query))
{?>
<img style="width: 200px;height: 200px;" src="<?php echo 'uploaded/' .$row['image_name'] ?>">
<?php
echo $row['image_description'] . "<br>";
}?>
Images are displayed as in picture
This is database table
The URL of your page is index.php/; notice the trailing slash.
A relative URL (e.g. src="uploaded/..") will resolve to index.php/uploaded/...
That folder obviously does not exist on your disk.
Use root-relative URLs: src="/uploaded/.."
or use relative URLs but go to the right folder: src="../uploaded/.."
or fix your weird URL and make it index.php, from which even relative URLs will resolve correctly.
I have a following code where I can upload a single image. This image gets stored in both database and folder. Now what I want is to add multiple images. How can I do that. Help me to come out of this.
<?php
$uploadDir ="C:/wamp/www/dragongym/customers/";
if(isset($_POST['submit']))
{
$intime =DATE("H:i", STRTOTIME($_POST['intime']));
$outtime =DATE("H:i", STRTOTIME($_POST['outtime']));
date_default_timezone_set('Asia/Calcutta');
$today = date("Y-m-d");
$msg="";
$res = "SELECT customer_id FROM customer ORDER by customer_id DESC LIMIT 1";
$qur = mysql_query($res);
while($row = mysql_fetch_array($qur, MYSQL_BOTH))
{
$last_id = $row['customer_id'];
$plus_id = 1;
}
if( $last_id !="")
{
$cust_id = $last_id + $plus_id;
}
$filePath="";
if($_FILES['cimage']['size'] > 0)
{
// echo $cust_id;
// Temporary file name stored on the server for pdf
$filename = basename($_FILES['cimage']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = $cust_id.'.'.$extension;
$tmpName1 = $_FILES['cimage']['tmp_name'];
$fileSize = $_FILES['cimage']['size'];
$fileType = $_FILES['cimage']['type'];
$filePath = $uploadDir . $new;
$resultes = move_uploaded_file($tmpName1, $filePath);
if (!$resultes)
{
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$new = addslashes($new);
$filePath = addslashes($filePath);
}
}
$sql = 'INSERT INTO customer(customer_name,roll_no,customer_number,customer_address,tariff_id,intime,outtime,customer_image,active,joining_date) VALUES("'.$_POST['name'].'","'.$_POST['roll'].'","'.$_POST['number'].'","'.$_POST['address'].'","'.$_POST['tariff'].'","'.$intime.'","'.$outtime.'","'.$filePath.'","1","'.$today.'")';
$msg="<p style=\"color:#99CC00; font-size:13px;\"> Successfully!</p>";
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<h2>Registration Form</h2><?php echo $msg; ?>
<label>Name</label>
<input type="text" value="" name="name" id="name" required class="txtfield">
<label>Roll Number</label>
<input type="text" value="" name="roll" id="roll" required class="txtfield">
<label>Mobile Number</label>
<input type="text" value="" name="number" required class="txtfield" id="mobnum">
<label>Address</label>
<textarea name="address" class="txtfield"></textarea>
<label>Upload Photo</label>
<input type="file" value="" name="cimage" class="txtfield">
<!-- <label style="display: block">Timing</label>
<input type="text" value="" name="intime" placeholder="Intime" required class="timefield timepicker">
<input type="text" value="" name="outtime" placeholder="Outtime" required class="timefield timepicker">-->
<input type="submit" value="Save" name="submit" class="btn buttonside1">
</form>
You can use jquery plugin for that..
there is lots of plugin available on google..try this one http://blueimp.github.io/jQuery-File-Upload/
to do multiple file upload you should first have multiple="true" in your tab like so
<input type="file" name='files[]' multiple='true'/>
then use foreach loop to upload files.
I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"