display image from folder based on stored path - php

I'm storing images in a folder, and saving their path encoded to base64 in database. The problem is, my images don't display, only their 'broken icons'. I don't know what I'm doing wrong there. Here's a stored image:
data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAQCAwMDAgQDAwMEBAQEBQkGBQUFBQsICAYJDQsNDQ0LDAwOEBQRDg8TDwwMEhgSExUWFxcXDhEZGxkWGhQWFxb/2wBDAQQEBAUFBQoGBgoWDwwPFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhb/wAARCAQ4B4ADASIAAhEBA
and my code:
<?php
require_once "db_connect.php";
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
if ($stmt = $conn->prepare("SELECT image FROM cardimages WHERE id=?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$image = $row['image'];
$image_src = "uploads/" . $image;
echo $image_src;
}
$stmt->close();
}
$conn->close();
?>
and in the html:
<img class="card-img-top" src="imageView.php?id=<?php echo $row["id"]; ?>" /

Related

Rebuilding a jpg from blob

Edited and started over to better describe my issue.
I have this code that displays an image from a database using blob data.
function getContent($db) {
$query = "SELECT name, animalid, image, thumb FROM images ";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent($db);
foreach($data as $row) {
$id = $row['id'];
$image = $row['image'];
$thumb = $row['thumb'];
echo '<img src="data:thumb/jpg;charset=utf8;base64,'.$image.'">';
}
This code displays a image on the page, when viewing the source code i see the blob data that the image is made from, what i need is to actually make an image that i can name properly.
How do i make a ******.jpg from the blob data?
Use base64_encode. You should use image/jpeg MIME type without charset.
function getContent($db) {
$query = "SELECT name, animalid, image, thumb FROM images ";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent($db);
foreach($data as $row) {
$id = $row['id'];
$image = $row['image'];
$thumb = $row['thumb'];
// $image is the BLOB
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}

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 . '" />';
}

loop to check and remove image if not exist

I'm trying to make a loop which checks if an image with filename from database exists, if not to unlink all images because I have many duplicates in folder but folder is 50gb. I can't check each one.
So here's what I've tried
$id = $_GET['id'];
$sql = "SELECT thumbnail FROM files WHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
$thumb = $row['thumbnail'];
$records = "../upload/images/";
foreach ($records as $record) {
if (file_exists('../upload/images/'.$thumb)) {}
else {
#unlink('../upload/images/'.$thumb);
}
}
Update
$sql = "SELECT thumbnail FROM filesWHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetchAll();
foreach($sql as $search_result) {
if(file_exists($search_result['thumbnail'])) {
$img_source = ('../upload/images/'.$search_result['thumbnail']);
} else {
#unlink('../upload/images/'.$search_result);
}
}
That's the logic I've understood. Checking if there are files in the folder that aren't present in database, and if so, delete it.
$directory = "../upload/images/";
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$sql = "SELECT thumbnail FROM files WHERE thumbnail =?";
$stmt = $mysqli->prepare($sql);
if($stmt) {
$stmt->bind_param('s', $image);
$stmt->bind_result($result);
$stmt->execute();
$stmt->fetch();
if(!$result) {
if(unlink($image)) {
echo "Image deleted $image <br>\n";
}
}
} else {
echo "Unable to prepare SQL";
}
}

php script does not show all images stored in a table

in mysql Datbase there is images stored using php Script (image got from a form.html/POST method) let's cal them (phpImages). and there is others stored using android application ( by converting Bitmap to String and using StringBuilder ). let's call them (androidImages).
with this php script i can load and display phpImages, but i cannot display androidImages.
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo ( $result['image']);
mysqli_close($con);
}
?>
with this php script i can load androidImages, but i cannot load phpImages :
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo base64_decode( $result['image'] );
mysqli_close($con);
}
?>
i wan't a php script that could display the both. because i want to load all images in a ListView of an android Apps.
**This is php script relied to android Application : **
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$con=mysqli_connect("localhost","root","","othmane")or die(mysqli_error($con));
$sql = "INSERT INTO images (image,image_type) VALUES (?,'android')";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
this is php Script relied with Form.html post method :
<?php
echo ini_get( 'file_uploads' );
if(!isset($_POST['submit'])){
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
function upload(){
$imgfp = fopen($_FILES['photo']['tmp_name'], 'rb');
print_r($_FILES);
$dbh = new PDO("mysql:host=localhost;dbname=othmane", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO images (image,image_type) VALUES (?,'php')");
$stmt->bindParam(1, $imgfp, PDO::PARAM_LOB);
$stmt->execute();
}
?>
Add a column called image_type in your table and pass one of the following values to determine what the source of the image is upon uploading: phpImage or androidImage
So you can do:
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = $_GET['id'];
$sql = "SELECT image, image_type FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));
$result = mysqli_fetch_array($r);
header('Content-Type: image/jpeg');
if ($result['image_type'] == 'phpImage') {
echo ( $result['image']);
} else if ($result['image_type'] == 'androidImage') {
echo base64_decode( $result['image'] );
}
mysqli_close($con);
}
?>

Use a variable from one IF - Statement into the other IF - Statement in PHP

I have a variable $target inside an IF - Statement in my login.php. I created the folders and sub-folders based on this variable. Now i want to move the uploaded file to this location. How can I do that?
here is the code
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
}
else if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
//$target4 = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
else
{
echo "asdfg";
}
Userid and Pid comes from login.html and Image value comes from upload.html
Nest the else-if as an if in the first if. Otherwise it won't be executed.
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
}
$upload = "Your desired location";
//comes from the login.html page
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "Whatever coloumn you wish to echo from database".'<br/>';
echo $row['col1'].'<br/>'.'<br/>';
echo "Second Coloumn".'<br/>';
echo '<a href="upload.html"/>'.$row['col2'].'</a>'.'<br/>';
//create the folders and subfolders based on the data from the database
$target = $upload.'/'.$row['col1'].'/'.$row['col2'].'/'.$row['col3'].'/'.$row['col4'].'/'.$row['col5'].'/';
//for renaming the image.
$imagename = $row['col1'].'.'.$row['col2'].'.'.$row['col3'].'.'.$row['col4'].'.'.$row['col5'].'.'.'jpg';
//create the folders and subfolders
if(!file_exists($target))
{
mkdir($target,null,0777);
}
//start session and store the value of $target and $imagename in a variable
session_start();
$_SESSION['str'] = $target;
$_SESSION['img'] = $imagename;
//This comes from other HTML page but to the same PHP.
if(isset($_FILES['image']))
// image upload from upload.html
// Want the value of target here.
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
//Move the uploaded file to the desired location.
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Successful";
Hope this would be helpful for all.

Categories