I am building a simple website, I want to allow the users to upload and change their avatars. At present I have been able to upload images to a mysql database, stored as blobs with the code as follows:
//connected to DB, userID fetched
$image = $FILES['fileToUpload']['tmp_name'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql = "UPDATE tbUsers SET profileImage = '".$content."' WHERE userID = ".userID;
$result = mysql_query($sql) or die (mysql_error());
When I download the files from phpmyadmin after upload they are saved as .bin files, but can be viewed normally. I'm not sure if this is correct or not.
My code to display the images is as follows:
HTML:
<?php echo '<img src ="showPic.php?q='.$_SESSION['profile'].'"/>'; ?>
PHP:
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
header('Content-type: image/jpeg');
$row = mysql_fetch_object($result);
echo $row['image_data'];
}
I am unsure if I am attempting to display the image in the correct way, any help (corrections/alternative solutions) would be greatly appreciated :)
You can do this :
if (!empty($_GET['profile']) && is_numeric($_GET['profile']))
{
$con = mysql_connect("localhost", "root", "");
$mysql_select_db("projectDB");
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
$result = mysql_query($sql) or die (mysql_error());
$content = mysql_result($result,0,"file_content");
$name = mysql_result($result,0,"file_name");
$type = mysql_result($result,0,"file_type");
$size = mysql_result($result,0,"file_size");
header("Content-type: $type");
echo $content
}
Note : You should have these column in you table where you save your BLOB data
file_name = for save filename
$_FILES['file']['name']
file_type = for save file type
$_FILES['file']['type']
file_size = for save file size
$_FILES['file']['size']
You select this
$sql = "SELECT profileImage FROM tbUsers WHERE userID = ". $_GET['profile'];
and refer to not selected column
echo $row['image_data'];
Related
i try to upload image to phpmyadmin server but in every time i get same error first error : Notice: Undefined index: image_path in /storage/ssd2/750/2564750/public_html/hi.php on line 12
Your Image Has Been Uploaded.
image is uploaded to server but its size =0 "zero"
php code
<?php
include 'DatabaseConfig.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_path'];
$ImageName = $_POST['image_name'];
$GetOldIdSQL ="SELECT id FROM UploadImageToServer ORDER BY id ASC";
$Query = mysqli_query($conn,$GetOldIdSQL);
while($row = mysqli_fetch_array($Query)){
$DefaultId = $row['id'];
}
$ImagePath = "images/$DefaultId.png";
$ServerURL = "https://xxxxx.000webhostapp.com/$ImagePath";
$InsertSQL = "insert into UploadImageToServer (image_path,image_name) values ('$ServerURL','$ImageName')";
if(mysqli_query($conn, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($ImageData));
echo "Your Image Has Been Uploaded.";
}
mysqli_close($conn);
}else{
echo "Not Uploaded";
}
?>
my database (id, image_path,image_name) both path and name datatype is text
i use postman to test my test like the following
https://i.imgur.com/VrIXOsN.png
I am trying to upload a image to MySQL databases using php5 script. And I am receiving an notice error.
Error, query failed
UploadImage.php
<?php
session_start();
?>
<HTML>
<HEAD>
<TITLE> Image Upload</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" METHOD="POST" ACTION="uploadImage2.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
UploadImage2.php
<?php
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
mysql_query($query) or die('Error, query failed'.mysql_errno($dbconn) . ": " . mysql_error($dbconn) . "\n");
$imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
//mysql_close($dbconn);
echo "<br>Image successfully uploaded to database<br>";
echo "View Image";
}else die("You have not selected any image");
?>
I have upload an image file but still have error on it.
But now I have counter another error for view Image.
<?php
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['id']))
{
$id = $_REQUEST ['id'];
$query = "SELECT img_name, img_type, img_size, img_data FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>
The error code:
Notice: Undefined variable: id� in C:\xampp\htdocs\sandbox\Testing\uploadImage2_viewimage.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�' at line 1
Please advise...
Remove the ' ' from table fields in query .use this query :
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
also please start to use PDO or mysqli as your query is open for sql injection
This should work:
$query = "
INSERT INTO `img_tbl`
(`img_name`, `img_type`, `img_size`, `img_data` )
VALUES
('".$fileName."', '".$fileType."', '".$fileSize."', '".$imgContent."')
";
Seems that some special characters in $imgContent is breaking the query string
Please use mysql_real_escape_string to format your data before sending to the database
mysql_real_escape_string
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
UPDATE
If the first solution didn't fix the problem , please check are there any NULL values , you have some database columns which set to NOT NULL . so you cannot insert NULL values to them .
Hope this helps :)
Right now I am inserting blob files into a database. I have read up on the update syntax for mysql I can not figure out how to modify my code to update a row with the BLOB instead of inserting a new row with the BLOB. Could someone help me with this?
Here is my code:
<?php
// Create MySQL login values and
// set them to your login information.
$username = "root";
$password = "";
$host = "localhost";
$database = "test";
$tbl_name="members";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
// Make sure the user actually
// selected and uploaded a file
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 members ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
1° You need to pass a referecence for what Data you are trying to update, like the Primary Key Id From Table.
2° Update SQL should be like it
$image = mysql_real_escape_string($unsafe_image);
$id = mysql_real_escape_string($unsafe_id);
$query = "UPDATE members SET image = '$data' WHERE id_image = $id";
$results = mysql_query($query, $link);
I am trying to display the last 5 images uploaded to my "store" table in MySql.
I'm a complete noob to PHP and databases and i've been reading a lot on how to do this but no luck.
I can store and display pictures one at a time but i'd like to be able to have a gallery of sorts to show the last 5 uploaded.
any advice or help would be greatly appreciated thanks!
p.s. I know it frowned upon to store pictures to a database like this but this project is just for practice.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Project One</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
<form>
<p />
<?php
//connect to database
(connect to server)
(select correct DB)
//file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "please select an image.";
else
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = $_FILES['image']['name'];
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE)
echo "That's not an image.";
else
{
if (!$insert = mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image')"))
echo "Problem Uploading Image.";
else
{
$lastid = mysql_insert_id();
echo "Image uploaded. <p />Your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
<p />
<p />
Go to Gallery
</body>
</html>
get.php
<?php
//connect to database
(connect to server)
(select correct DB)
$id = addslashes($_REQUEST['id']);
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image = $image['image'];
header("Content-type: image/jpeg");
echo $image;
?>
This is what I used when I wanted to do something like that... a long time ago! =P
$sql = "SELECT image FROM table WHERE cond ORDER BY xxxx DESC LIMIT 5";
$result = mysqli_query($db,$sql);
while($arraySomething = mysqli_fetch_array($result))
{
echo "<img src='php/imgView.php?imgId=".$arraySomething."' />";
}
I try the first approach with header('content-type: image/jpeg'); but end up with image not shown. After a few google through website I found the solution which I can display image from database to my page
try this:
mysql_connect("localhost","root","")or die("Cannot connect to database"); //keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56"; // manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/>'
mysql_connect("localhost","root","")or die("Cannot connect to database");
//keep your db name
mysql_select_db("example_db") or die("Cannot select database");
$sql = "SELECT * FROM `article` where `id` = 56";
// manipulate id ok
$sth = mysql_query($sql);
$result=mysql_fetch_array($sth);
// this is code to display
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image_file'] ).'"/> width="xxxx" height="xxxx"';
Add the height and width also
You can also use this function
//Retrieve image from database and display it on html webpage
function displayImageFromDatabase(){
//use global keyword to declare conn inside a function
global $conn;
$sqlselectimageFromDb = "SELECT * FROM `imageuploadphpmysqlblob` ";
$dataFromDb = mysqli_query($conn, $sqlselectimageFromDb);
while ($row = mysqli_fetch_assoc($dataFromDb)) {
echo '<img height="250px" width="250px" src=data:image;base64,'.$row['image'].'/>';
}
Insert it into mysql database like this :
$image = $_FILES['imagefile']['tmp_name'];
$name = $_FILES['imagefile']['name'];
$image = base64_encode(file_get_contents(addslashes($image)));
references : https://mauricemutetingundi.blogspot.com/2019/04/how-to-upload-blob-image-to-mysql.html
I'm trying to create a delete image link if the image is present and when the user clicks the delete image link it should delete the image. But for some reason this is not working can someone help me fix the delete image link problem? Thanks!
Here is the PHP code.
if (isset($_POST['delete_image'])) {
$img_dir = "../members/" . $user_id . "/images/thumbs/";
$img_thmb = "../members/" . $user_id . "/images/";
$image_name = $row['image'];
if(file_exists($img_dir . $image_name)){
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli, "DELETE FROM users* WHERE image_id = '.$image_id.' AND user_id = '$user_id'");
}else{
echo '<p class="error">Sorry unable to delete image file!</p>';
}
}
}
if(isset($_POST['image']) || !empty($image)) {
echo 'Delete Image';
}
"DELETE FROM users* WHERE image_id = '.$image_id.' AND user_id = '$user_id'"
should be
"DELETE FROM users WHERE image_id = $image_id AND user_id = $user_id"
This is assuming $image_id and $user_id are both integers. If they're strings, put the single quotes around them.
Also, double check your link:
Delete Image
Is the user really passing in the link via POST?
Your code is vulnerable to SQL injection attacks. Please consider using parametrized queries.
"DELETE FROM users WHERE image_id = $image_id AND user_id = $user_id"
And also
$path = "Your Image folder Path";
$image_name = "Your Image Name";
unlink($path."$image_name);