I would like to ask you how can I properly stored an image both in mysql and in a folder at the moment with this code:
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$data')";
$results = mysql_query($query, $conn);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
?>'
Also how properly to display it.
My database for the images is id, images. Do I need anything more for the job or that is enough.
Thank you.
From the above code, image will be saved in database not in folder.
To save in folder you have to use a below code after insert query.
move_uploaded_file($tmpName,"upload/" .$filename );
here upload is folder name.
If you want to store image in database you can use base64_encode method
$image = file_get_contents('filename.gif');
$imencoded = base64_encode($image);
$query = "INSERT INTO tbl_images ";
$query .= "(images) VALUES ('$imencoded')";
But storing image in db is not recommended and it will not support in IE6 & 7.
Related
I have an image upload index for a project. An link to the image is created and saved to a phpMyAdmin DB and the image is supposed to save to my /image folder in the project files. The index saves the link/directory access in the DB but the image itself is not saved. So essentially I have a link to an empty image in my image folder!
I had no issues with the code until I moved from a localhost to a blacknight server.
Any suggestions would be greatly appreciated.
I have tried using BLOB instead of TEXT for images in the database and that has not worked.
I have given permissions to access that for Read/Write in FileZilla.
I have corrected all the DB connections and file paths.
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I expected that this line would submit the file into the /images folder
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
No need of specifying full path to folder
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "./images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I have successfully uploaded pdf files to the database but now when I am trying to read the files I'm getting issue "Failed to load PDF" when I click on the link. I have checked my browser plugins there is no issue with it.
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mahmood_faridi");
$query = "SELECT id, name FROM upload";
$result = mysqli_query($con,$query) or die('Error, query failed');
if(mysqli_num_rows($result)==0){
echo "Database is empty <br>";
}
else{
while(list($id, $name) = mysqli_fetch_array($result)){
echo "$name<br>";
}
}
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT content FROM upload WHERE id = '$id'";
$result = mysqli_query($con,$query) or die('Error, query failed');
$row = mysqli_fetch_row($result);
$content=$row['content'];
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $content . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
ob_clean();
ob_flush ();
#readfile($content);
}
mysqli_close($con);
?>
This is the “save file” code:
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = mysqli_real_escape_string($con,$content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = mysqli_real_escape_string($con,$fileName);
}
mysqli_select_db($con,"mahmood_faridi");
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysqli_query($con,$query) or die('Error, query failed');
mysqli_close($con);
echo "<br>File $fileName uploaded<br>";
}
else
echo "File not uploaded"
?>
I was going to post this as a comment, but it got a bit too long.
When saving the file to the database, try base64_encoding the content, and then base64_decoding it when reading it out. PDFs look odd when viewed in text, and the collation of the database can affect the way it saves, or even what is saved. If one single character changes, you'll have a corrupt PDF.
Also make sure that error reporting is turned off, and that you have no spaces being output alongside the PDF which will also show as the file being corrupt.
I'd also consider splitting the functionality you have out into different files. It looks like everything is in one file there, which can lead to output happening when you don't fully expect it, again corrupting a download.
As an alternative, can you not save the PDF to disk and store the location in the database. You can then read the file as needed and output it, and then there's no issue of the PDF content being corrupted within the database. If you go down this route, make sure you give them unique names as two files could be uploaded with the same name and you might accidentally overwrite one.
Oooooops!
We all concentrated about encoding and database storing, but the problem is another!
When you output your PDF, you get the content from database, but you send this content to the user through:
#readfile($content);
readfile($content) outputs the contents of the file with filepath $content, but in $content there is not any filepath!
You simply change this line of code in
echo $content;
and your script will works.
(Read more about readfile)
I am currently having problems with displaying image from mysql database. I am able to upload an image to mysql database, however if i want to retrieve it from the database, it is displayed in Gibberish text.
Here is upload.php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$filename = mysqli_real_escape_string($mysqli,$_FILES['image']['name']);
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO `TABLES` (`image`)
VALUES( NULL,'$data')";
$result = $mysqli->query($query);
}
View.php
$mysqlquery = "SELECT * FROM TABLE";
$results = $mysqli->query($mysqlquery);
if($results->num_rows > 0){
while ($row = $results ->fetch_assoc()){
echo '<div align = "center">';
echo "<b>".$row["image"]. "<br></b>";
header("Content-type: image/jpeg");
}
}
Try this and do not forget to give image path before source
echo "<img src='your image location directory/". $row['image'] .'" >";
Oooooh... I just wish I had the answer to this one...
Some thoughts, though.
First, from personal experience I urge against storing images in the database. For one thing, your database backups will quickly become ridiculous. A more common, and better, approach is to store the images in the file system and store only the location (e.g. /img/pic03.jpg ) of the image in the database.
Next, I see you are modifying the received binary data:
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
Perhaps you know something that I don't (it's not difficult), but generally, if you gerfingerpoke with binary image data you get ... um... gibberish. Try disabling those lines and see what happens.
Found several examples online on how to upload an image to a mysql database table, in binary
NOT a link or a folder in the server.
the imag isn't viewable when i try to print it
when I check the database table,it shows a bunch of data in weird format, i'm assuming the image data
here is code
if(!empty($_FILES['image']) && $_FILES['image']['size'] > 0 && !empty($_POST['name']))
{
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
code for displaying image
$sql = "SELECT * FROM `photos` WHERE userName = '$currentUser'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$content = $row['image'];
echo $content;
echo '<p id="caption">'.$row['caption'].' </p>';
}
when i try to display the image i get nothing as output, i check the database via putty, and i see a massive amount of weird characters, i'm assuming the items for the image.
ideas?
you could eventually try to replace these two lines:
$content = $row['image'];
echo $content;
with:
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';
I have a classifieds website where users must fill in a form in order to put a ad. The form consists of name, password, category, specifications etc etc.
Now, I need to add a image upload function into this form, which must have the following:
1- Upload up to 5 images.
2- A 'remove image link' beneath each image if the user wants another image instead.
How would you do this?
Thanks
Best would be if there was a plugin or something to Jquery which is easy to modify...
jQuery Multiple File Upload
You can limit the number of uploads using the max option or passing a number as the only parameter. More info on the Examples tab.
If you want to upload it as a file to an SQL database, have something like this in the form (in php echo format):
echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"2000000\">
<input name=\"userfile\" type=\"file\" id=\"userfile\">";
Then in your form's receiving php page put something like this:
if ($_FILES['userfile']['size'] > 0) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO files (name, size, type, content ) VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
$thisq = mysql_query("SELECT * FROM `files` WHERE 1 ORDER BY `id` DESC LIMIT 1");
$fileidnumber= mysql_fetch_array($thisq);
}
That will store the file to a database and then return the key for you to save or use however you'd like. You can then create a page to download the files like this:
<?php
import_request_variables(gp);
if(isset($_GET['id'])) {
// if id is set then get the file with the id from database
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM `files` WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
?>