I'm trying to display an image stored in mysql database. I store it this way:
if (isset($_SESSION['mod']) && (isset($_GET['upload'])) ) {
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$con = mysql_connect("localhost", "root");
mysql_select_db("psi", $con);
// 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);
//now i use <tmpName> as an actual name of file
$tmpName = $_FILES['image']['name'];
if (isset($_GET['name']))
$tmpName = $_GET['name'];
$uname = $_SESSION['uname'];
$idObj = mysql_query("SELECT id_object AS id FROM tobject WHERE uname = '$uname'");
$idObj = mysql_fetch_assoc($idObj);
$idObj = $idObj['id'];
// Create the query and insert
// into our database.
$query = "INSERT INTO slike ";
$query .= "VALUES ('', '$idObj', '$data', '$tmpName')";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
}
I suppose this is ok.. It does store something in db (appropriate size), but I can't see what it is manually.. So, when I try to fetch it with this code:
else if (isset($_GET['idSlike'])) {
$idSlike = $_GET['idSlike'];
$con = mysql_connect("localhost", "root");
mysql_select_db("psi", $con);
$res = mysql_query("SELECT slika FROM slike WHERE id_slika = '$idSlike'");
if (!$res) {
die("greska: " . mysql_error());
};
$slika = mysql_fetch_array($res);
$slika = $slika['slika'];
header('Content-Type: ' . $slika['mimetype']);
echo $slika;
}
note: both storing and getting images from db are in same file (image.php)...
I don't get anything... I tried displaying it with:
<img src="image.php?idSlike=10"/>
i hardcoded ids but they exist in db
i also tried with
echo "<img src=\"image.php?idSlike=13\">";
through another php file but all i get is an empty image (with correct src)
I'm using xampp (mysql 5.5.16; PHP 5.3.8)...
mysql_*functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information.