I am on my way to create the feature for users to upload their profile photo to the database. I manage to upload my photo to database in binary form (BLOB) but I am having problem while trying to display it.
upload form code:
<?php //get the posted image when the submit button is clicked
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
// 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);
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);
$student_id=$row_student['student_id'];
// Create the query and insert
// into our database.
$query = "UPDATE student SET student_img='$data' WHERE student_id ='$student_id'";
$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);
?>
<form action="" method="post" enctype="multipart/form-data" name="changer">
<strong style="color: #FFD700;">Upload your image:</strong><br />
<input name="MAX_FILE_SIZE" value="102400" type="hidden"><br /><br />
<input namge="image" accept="image/jpeg" type="file">
<input type="submit" value="Submit">
</form>
Code to display image:
<?php
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}else{
$query = mysql_query("SELECT * FROM student WHERE student_id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];
}
header('Content-type: image/jpeg');
echo $content;
?>
I could see my database table for the image column containing some bits but I just cant seems to display it. Please advise.
Your code to retrieve and display the image looks like it is correct, however I'm guessing you are never getting to the query due to this filtering line:
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}
is_int() tests if the type of a value is an integer, and values coming from $_GET, $_POST, $_REQUEST are always strings. , so your condition is always false. You can test it instead with ctype_digit() or is_numeric(), or intval($id) == $id. Also, empty() calls isset() implicitly, so isset() isn't needed.
// ctype_digit() method...
if (empty($id) || !ctype_digit($id)) {
die("Please select your image!");
}
// intval() method...
if (empty($id) || (intva($id) != $id)) {
die("Please select your image!");
}
Without any errors, it's hard to say, but if it's not the ID problem as suggested by Michael, it might [also] be corruption of your image data on upload. Have you tried downloading the directly (eg wget that URL) and opening it locally? Is the JPEG header there?
Some general comments:
Are you sure you want to store images in the database? It's
generally preferred to store filename / URL fragments, and leave the
binary data on disk, especially if they're larger images. See
php:Store image into Mysql blob, Good or bad?
for a discussion.
Either way that upload code is asking for trouble. addslashes() is
not sufficient to fix the escaping problem, use a specific one like
mysqli::real escape-string
to safeguard against SQL Injection
attacks - this post explores some differences.
If your MySQL DB is hosted on the same box as your webserver, you
could even save effort (and increase speed) by using the MySQL LOAD_FILE function, but this isn't very scalable in the long term.
Consider moving all your login details to a separate file, out of the webroot for security.
Related
** EDIT: I resolved the issue on my own. Thanks for all your help. **
I'm trying to insert image files to my database for testing, and found that my code stopped working (it was able to do what it did before).
When I submit the image to the database it appends the image id, but not the 'username' and 'img_name'(filename) fields - these two fields just show up as empty strings. Can you tell me what's wrong with my code and how I can fix this? Your help is very appreciated
This is a summary of my database:
Database Name: photos
Table Name: images
Row Names: id[primary key], username, img_name
And my HTML and PHP codes for uploading image file to the database:
<form method="post" action="uploadindex5.php" enctype="multipart/form-data">
<input type="file" name="membimg">
<input type="submit" name="membupload">
</form>
if (isset($_POST['membupload'])) {
$username = $_SESSION['username'];
$membupload = $_POST['membupload'];
$membimg = $_POST['membimg']['name'];
$membtarg = "images/".basename($_FILES['membimg']['name']);
$membmuf = move_uploaded_file($_FILES['membimg']['tmp_name'], $membtarg);
$servername = "localhost";
$sroot = "root";
$password = "";
$dbname = "photos";
$conn = mysqli_connect($servername,$sroot,$password,$dbname);
if (mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$sql = "INSERT INTO images (username, img_name) VALUES ('$username', '$membimg')";
$result = mysqli_query($conn, $sql);
if ($membmuf) {
$msg = "Image uploaded";
} else {
$msg = "Upload failed";
}
}
I'd put dummy values in for the session and post values just hard code it and see if the PHP code is working and then determine if those variables are even set once i verified my php code works properly. Once you hard code those questionable variables then you can run the PHP page without submiting it with the form or ajax or however you are calling it. The PHP page will report the errors if you have PHP error reporting on. Javascript console may even tell you if there is a 500 internal server error which indicates the PHP script isn't working.
I am working in php I want browse and upload the image file
this is my php code
<?php
if(isset($_POST['submit']))
{
$link= mysql_connect('localhost','root','');
mysql_select_db('bawa');
if(isset($_FILES['image']) && $_FILES['image']['size'] >0)
{
//Temporary file name stored on the server
$tmpname = $_FILES['image']['tmp_name'];
//read a file
$fp = fopen($tmpname,'r');
$data=fread($fp,filesize($tmpname));
$data=addslashes($data);
fclose($fp);
$query = ("UPDATE user_summary SET image='$data' where user_id=2");
$query .= "(image) VALUES ('$data)";
$results = mysql_query($query,$link);
echo "Working code";
}
else{
echo mysql_error();
}
}
?>
when i click on submit button my image should updated in my database but its not updating in database
any help?
The main problem at the moment is the line...
$query .= "(image) VALUES ('$data)";
This looks more like something that would be part of an INSERT statement. Commenting this out should mean the UPDATE should be correct.
Although as pointed out - you should work towards updating this to use either PDO or mysqli libraries and using prepared statements and bind variables.
I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}
I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.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 = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.
Hi I am newish to php and I have created an update page for Content Management System. I have a file upload in this case a picture. I have other inputs that contain text and I can get them to populate my form and thats fine and works great because the user can see what has already been entered. But the file name for the photo can not have a value so if the user doesn't pick the picture from the directory again it will update minus the picture. What I think I need is a isset function that says if the file (picture) input is left blank don't update this field and use whatever what already in the database for it, that way if it was left blank when created it will still be, and if the user has changed it this time it will change; or if they want to leave it the same it won't leave their picture blank. Hope that makes sence.
Here is my coding currently for the Form:
<p>
Photo:
</p>
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input type="file" name="photo"/>
Below is my php code for my update if the update button is pressed:
$con = mysql_connect("localhost","******","********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
// run this only, once the user has hit the "Update" button
if (isset($_POST['update'])) {
// assign form inputs
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$pic = $_POST['photo'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];
// add member to database
$result = mysql_query("UPDATE dbProfile SET nameMember='".$name."',bandMember='".$position."',photo='".$pic."',aboutMember='".$about."',otherBands='".$bands."' WHERE id='".$id."'");
mysql_close($con);
Header("Location: listMember.php");
exit;
}
else { // read member data from database
$result = mysql_query ("SELECT * FROM dbProfile WHERE id='".$id."'");
while($row = mysql_fetch_array($result))
{
$name = $row['nameMember'];
$position = $row['bandMember'];
$pic = $row['photo'];
$about = $row['aboutMember'];
$bands = $row['otherBands'];
}
}
mysql_close($con);
?>
If you could help I would be very please and greatful.
You have to use the $_FILES variable for uploaded files. For further information, see Handling file uploads in the PHP manual.
Try:
if(is_uploaded_file($_FILES['photo']['tmp_name']))
From the manual:
Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.