Not receiving the image from database PHP LongBlob - php

Hi i'm trying to receive my images from the database. I already can insert the images, but I don't know if it goes wrong overthere or that I do something wrong with getting the image.
The code for inserting the image:
public function Save(){
/*** check if a file was uploaded ***/
if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
{
/*** get the image info. ***/
$size = getimagesize($_FILES['userfile']['tmp_name']);
/*** assign our variables ***/
$type = $size['mime'];
$imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['userfile']['name'];
$maxsize = 99999999;
/*** check the file is less than the maximum file size ***/
if($_FILES['userfile']['size'] < $maxsize )
{
/*** connect to db ***/
$db = new Db();
/*** our sql query ***/
$sql = "INSERT INTO Foto (image_type ,image, image_size, image_name)
VALUES ('". $type ."',
'". $imgfp ."',
'". $size ."',
'". $name ."');";
$db->conn->query($sql);
$sql = "SELECT * FROM Foto ORDER BY id DESC LIMIT 1;";
$select = $db->conn->query($sql);
$numberofRows = $select->num_rows;
if($numberofRows == 1)
{
while ($oneSelect = $select->fetch_assoc())
{
return $oneSelect;
}
} else {
throw new Exception("Fout");
}
}
else
{
throw new Exception("Bestand is te groot");
}
}
else
{
throw new Exception("Dit extensie is niet ondersteund");
}
}
The code for loading the images:
<?php
include_once("classes/Db.class.php");
//$id = $_GET['id'];
$id = "33";
$db = new Db();
$sql = "SELECT image, image_type FROM Foto WHERE id = '". $id ."';";
$result = $db->conn->query($sql);
$row = $result->fetch_assoc();
if(sizeof($row) == 2)
{
header("Content-type: ".$row['image_type']);
echo $row['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
?>

You're not actually inserting the image data. Read up on the fopen() function, it doesn't return the image data, but a file handle that can then be used for reading from or writing to a file (using, for example, fread() or fwrite()). Easy way out is using file_get_contents().
But take my advice, it's really bad practice to store images in the database. They're files and better off stored on the file system (hence the name). Makes serving them a lot faster too, as no PHP request has to be executed. Store the filename and maybe a relative path to the file in the database instead.

Related

Im trying to show images that i uploaded to the database using longblob and PDO

Im trying to show images that i uploaded to the database using longblob and PDO but i always get a black screen with a small white square in the center.
This is the code:
<?php
include('snippets/startDB.php');
include('snippets/Session.php');
$PicNum = $_GET["PicNum"]; echo($PicNum);
$id = $_SESSION['id'];
$stmt = $dbh->prepare('SELECT imagem FROM aluno WHERE id= ?');
$stmt->execute(array($PicNum));
$row = $stmt->fetch();
Header( 'Content-type: image/gif');
echo $row['imagem'];
?>
I think the save file is working correctly because a file appears in the database when i upload the image.
My save file:
<?php
$imagem = $_FILES["imagem"];
include('snippets/startDB.php');
include('snippets/Session.php');
if($imagem != NULL) {
$nomeFinal = time().'.jpg';
if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)) {
$tamanhoImg = filesize($nomeFinal);
$mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg));
if($_SESSION['tipo']== 'Aluno'){
$stmt = $dbh->prepare('UPDATE aluno SET imagem = ? WHERE id = ?');
$stmt->execute(array($mysqlImg, $_SESSION["id"]));
}else if($_SESSION['tipo']== 'Professor'){
$stmt = $dbh->prepare('UPDATE professor SET imagem = ? WHERE id = ?') ;
$stmt->execute(array($mysqlImg, $_SESSION["id"])) ;
}
header("location:perfil_aluno.php");
}
}
else {
echo"Erro!";
}
?>

validating if imagefile is empty also have a separate query for a file that is not empty

I want to have a separate query that updates only the imagename and imagetext when the imagefile is left blank and update all the imagename,imagetext and the image itself when the user selects a new image here is my query:
if (isset($_POST['update'])) {
$update_id = $_POST["id"];
$update_imagename = $_POST['imagename'];
// Get image name
$update_imagefile = $_FILES['imagefile']['name'];
// Get text
$update_imagetext = mysqli_real_escape_string($db, $_POST['imagetext']);
// image file directory
$target = "images/portfolio/" . basename($update_imagefile);
$update_query = "UPDATE `images` SET `imagename`='$update_imagename',`imagetext`='$update_imagetext',`imagefile`= '$update_imagefile' WHERE `imageid`='$update_id'"; //delete query
$run = mysqli_query($db, $update_query);
if ($run) {
//javascript function to open in the same window
echo "<script>window.open('artworksupdate.php?=image has been updated','_self')</script>";
}
to determine if you have uploadFile, just do !empty($_POST['imagefile']), following you have sample.
if (!empty($_POST)) {
$update_id = $_POST["id"];
// Get image name
$update_imagename = $_POST['imagename'];
// Get image description
$update_imagetext = $_POST['imagetext'];
// Determine if we have input file set
$haveUploadedFile = !empty($_POST['imagefile']);
if( $haveUploadedFile ) {
// [...] do your upload stuff here.
$update_imagefile = 'myAwesomeImage.png';
$update_query = "UPDATE `images` SET `imagename`='$update_imagename',`imagetext`='$update_imagetext',`imagefile`= '$update_imagefile' WHERE `imageid`='$update_id'"; //delete query
}
else {
$update_query = "UPDATE `images` SET `imagename`='$update_imagename',`imagetext`='$update_imagetext' WHERE `imageid`='$update_id'"; //delete query
}
$run = mysqli_query($db, $update_query);
//[...]
}

Stored images in blob is acting strange when user clicks to go to last page ( PHP )

I'm storing in DB only profile and profile heading images. [BLOB]
If i change my profile picture or my header picture its works fine, its storing in my DB.
The funny thing is that when i go back one page the last uploaded image appears again.
I recorded it here in this video
Watch it so you will understand whats going on.
I want to know why this happens?
this are my codes.
function profile_pic(){
//uploads imgs
global $conn;
if(isset($_FILES['proImage']['tmp_name'])){
$img = file_get_contents($_FILES['proImage']['tmp_name']);
$imgName = addslashes($_FILES['proImage']['name']);
$imgSize = getimagesize($_FILES['proImage']['tmp_name']);
if ($imgSize == false){
$_SESSION['empError'] = 'Error';
}else{
$stmt = $conn->prepare("UPDATE users SET ProfileImage=? , ProfileImageName=? WHERE email=?");
$stmt->bind_param("sss",$img, $imgn, $em);
$img=$img;
$imgn=$imgName;
$em = escape_string($_SESSION['useremail']);
$stmt->execute();
$lastId=$stmt->insert_id;
$_SESSION['empError']= "Updated.";
//return $lastId;
}
}
}
display imgs
function display_pic(){
global $conn;
$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->bind_param("s", $em);
$em = $_SESSION['useremail'];
$stmt->execute();
$result = $stmt->get_result();
$rows = $result->fetch_assoc();
$url =$rows['ProfileImage']; //blob row
$b64 = base64_encode($url);
$uri = 'data:image/jpeg;base64,' . $b64;
echo '<img class="avatar border-white" src="' . $uri . '" />';
}

Issue with LONGBLOBs in MySQLi

I'm trying to insert LONGBLOBs to my database. Unfortunately when I click insert nothing is being inserted in the db. When I change the column type to BLOB everything is fine but the blob size capacityis too small so I really need LONGBLOBs. Using blob I can add only a 64kb file. Using longblob I can insert a file which is much larger. What's why I need to use LONGBLOB. I'm using MySQLi and PHP. Could you help me out?
if($_POST && $_FILES['uploadFile']['size'] > 0) {
$name = $_FILES['uploadFile']['name'];
$_SESSION['fileType'] = $_FILES['uploadFile']['type'];
$data = $_FILES['uploadFile']['tmp_name'];
//$data = addslashes($data);
$ifImage = getimageSize($_FILES['uploadFile']['tmp_name']);
$getAuthorID = $_SESSION['userID'];
$_SESSION['ifImage'] = $ifImage;
echo '<pre>'.print_r($_SESSION['ifImage'], true).'</pre>';
$fp = fopen($data, 'rw');
$content = fread($fp, filesize($data));
$content = addslashes($content);
fclose($fp);
/* SELECT FILE ID BY IT'S NAME */
$selectIDname= "SELECT fileID FROM files WHERE fileName = '$name'";
$selectIDnameQuery = mysqli_query($connection, $selectIDname);
$row = mysqli_fetch_array($selectIDnameQuery);
$selectIDname = $row['fileID'];
echo '<pre>ID: '.print_r($selectIDname, true).'</pre>';
$_FILES['uploadFile']['fileID'] = $row['fileID'];
/* INCREMENT FILE ID */
$selectFileIDQuery = mysqli_query($connection, "SELECT fileID FROM filescontent ORDER BY fileID DESC LIMIT 1");
$fetchFileID = mysqli_fetch_assoc($selectFileIDQuery);
$incrementFileID = $fetchFileID['fileID'] + 1;
/* GET AND INCREMENT FILE VERSION */
$getVersionsObject = new File($_FILES['uploadFile']['fileID']);
$fetchVersions = $getVersionsObject->getVersions();
$fetchLastElement = end($fetchVersions);
$incrementVersion = $fetchLastElement + 1;
echo '<pre>Version: '.print_r($incrementVersion, true).'</pre>';
/* SELECT FILE NAME FROM DB */
$selectName = mysqli_query($connection, "SELECT fileName FROM files WHERE fileName='$name'");
$fetchName = mysqli_fetch_assoc($selectName);
$fetchName = $fetchName['fileName'];
if(!strcmp($name, $fetchName)){
echo 'The file exists <br>';
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileExist($selectIDname, $incrementVersion, $content, $getAuthorID);
}
else{
echo 'The file does not exist';
$insertIntoFilesObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFiles = $insertIntoFilesObject->uploadContentIntoFiles($incrementFileID, $name, $getAuthorID);
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileNotExist($incrementFileID, $incrementVersion, $content, $getAuthorID);
}
$mysqliErorr = mysqli_error($connection);
echo '<br>'.$mysqliErorr.'<br>';
//header("Location: listFiles.php");
}
else if($_POST && $_FILES['uploadFile']['size'] == 0) {
echo 'You have not chosen a file';
}
}

how to get picture filename from database?

I want to get the database picture path so that i can used it and store the same file-name path in the image folder so both can be matched up. Actually i am using a unique-id so that pictures have unique names but don't know how to use it rightly. Any help would be appreciated.
$insert = "UPDATE USER_LOGIN SET PICTURE = '".uniqid().$_FILES['file']['name']."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
$UploadDirectory = '/wamp/www/img/Users/Users/'.$row['PICTURE'];
Working Solution:
if($row)
{
$Filename = uniqid().$_FILES['file']['name'];
$DirectoryPath = '/wamp/www/img/Users/Users/'.$Filename;
if(move_uploaded_file($_FILES['file']['tmp_name'], $DirectoryPath))
{
$insert = "UPDATE USER_LOGIN SET PICTURE = '".$Filename."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
if($check)
{
echo "Saved";
// Commit the changes to the table.
oci_commit($con);
}
else
{
// Rollback changes to table.
oci_rollback($con);
}
}
else
{
//die('error uploading File!');
}
}

Categories