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");
Related
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.
I have a form in which you can upload an image, which I then save to a folder on the server using php.
I'm storing the other data entered into the form in an xml-file, also using php. I now want to be able to store the pdf-file/the pdf-data in this xml-file as well for later use (the form acts as a template and I later want to store the entire information in another file and display it to the user).
I read about Base64 encoding etc. but I'm not sure if that applies to PDF-files as well because all I could find was how to do that for images or if there's an easier way to do it for my case?
Edit: Here's the HTML:
<form method="post" action="profile.php" enctype="multipart/form-data">
<input type="hidden" name="create_xml" value="true">
<label for="name">Name: </label><br>
<input type="text" name="name"><br>
<label for="email">E-mail: </label><br>
<input type="text" name="email"><br>
<label for="textbox">Write something: </label><br>
<textarea name="textbox" rows="5" cols="40"></textarea><br>
<label for="fileToUpload">Upload a PDF-file: </label>
<input type="file" name="fileToUpload" id="file-select">
<input type="text" name="filename" placeholder="Enter the name of your file"><br>
<input type="submit" value="submit" name="submit">
</form>
php that saves the data to the xml file:
if(isset($_POST['create_xml'])) {
$xml = new DOMDocument();
$newProfile = $xml->createElement('Profile');
$xml->appendChild($newProfile);
$name = $xml->createElement('Name', $name);
$newProfile->appendChild($name);
$email = $xml->createElement('EMail', $emailaddress);
$newProfile->appendChild($email);
$textbox = $xml->createElement('Text', $text);
$newProfile->appendChild($textbox);
$xml->formatOutput = true;
$xml->saveXML();
$xml->save($filename.".xml");
}
If you want to make xml at the time of insert data in DB:
if($this->input->post('submit')){
$name = $_POST['name'];
$email = $_POST['email'];
$filename = $_POST['filename'];
$year = gmdate("Y");
if($_FILES){
$_FILES['fileToUpload']['name'] = $files['fileToUpload']['name'];
$_FILES['fileToUpload']['type'] = $files['fileToUpload']['type'];
$_FILES['fileToUpload']['tmp_name'] = $files['fileToUpload']['tmp_name'];
$_FILES['fileToUpload']['error'] = $files['fileToUpload']['error'];
$_FILES['fileToUpload']['size'] = $files['fileToUpload']['size'];
$ext = pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION);
$mtime = uniqid(microtime());
$uniqueid = substr($mtime, 2, 8);
$pdfname = $uniqueid . '.' . $ext; // pdf file encrypt name here which need to save
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], 'uploads/' . $pdfname);
}
//Your insert query here remember here you should add $pdfname as pdflink
// If successful insertion than
$xml = new DOMDocument();
$newProfile = $xml->createElement('Profile');
$xml->appendChild($newProfile);
$name = $xml->createElement('Name', $name);
$newProfile->appendChild($name);
$email = $xml->createElement('EMail', $email);
$newProfile->appendChild($email);
$textbox = $xml->createElement('Text', $filename);
$newProfile->appendChild($textbox);
$pdflink = $xml->createElement('Text', $pdfname);
$newProfile->appendChild($pdflink);
$xml->formatOutput = true;
$xml->saveXML();
$xml->save($filename.".xml");
}
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 this code for a form that uploads pictures to my website and saves the information to a mysql database:
<form method='post'>
Album Name: <input type="text" name="title" />
<input type="submit" name="submit" value="create" />
</form>
<h4>Add Photo</h4>
<form enctype="multipart/form-data" method="post">
<?php
require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST['upload'])){
$caption = $_POST['caption'];
$albumID = $_POST['album'];
$file = $_FILES ['file']['name'];
$file_type = $_FILES ['file']['type'];
$file_size = $_FILES ['file']['size'];
$file_tmp = $_FILES ['file']['tmp_name'];
$random_name = rand();
if(empty($file)){
echo "Please enter a file <br>";
} else{
move_uploaded_file($file_tmp, 'uploads/'.$random_name.'.jpg');
$ret = mysqli_prepare($mysqli, "INSERT INTO photos (caption, image_url, date_taken)
VALUES(?, ?, NOW())");
$filename = "uploads/" + $random_name + ".jpeg";
mysqli_stmt_bind_param($ret, "ss", $caption, $filename);
mysqli_stmt_execute($ret);
echo "Photo successfully uploaded!<br>";
}
}
?>
Caption: <br>
<input type="text" name="caption">
<br><br>
Select Album: <br>
<select name="album">
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$result = $mysqli->query("SELECT * FROM albums");
while ($row = $result->fetch_assoc()) {
$albumID = $row['albumID'];
$title = $row['title'];
echo "<option value='$albumID'>$title</option>";
}
?>
</select>
<br><br>
Select Photo: <br>
<input type="file" name="file">
<br><br>
<input type="submit" name="upload" value="Upload">
</form>
This successfully uploads the picture to my 'uploads' folder as well as my mysql database, however, I would like to put in image URL "uploads/(random name generated).jpg"
I have failed to do this with my current code, the information recorded in the 'image_url' column of my photos table is just the random number generated. without the "uploads/" in the beginning and ".jpg" in the end.
I should mention that the schema for my photos table is:
caption, image_url, date_taken, imageID
Any help will be very much appreciated!!
thank you in advance
You are using + (plus) signs to concatenate with, in this line:
$filename = "uploads/" + $random_name + ".jpeg";
PHP uses dots/periods to concatenate with, rather than plus signs which is JS/C language syntax:
$filename = "uploads/" . $random_name . ".jpeg";
Error checking would have signaled the syntax error.
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')"