Fetch an image from database and display it on screen - php

I am using phpmyadmin for creating my database. I have stored images in a folder called - "images". The path of the image is stored in the database.
I now want to fetch an image corresponding to an id and display it on the screen.
This is how I am storing my image.
function GetImageExtension($imagetype)
{
if(empty($imagetype)) return false;
switch($imagetype) {
case 'image/bmp': return '.bmp';
case 'image/gif': return '.gif';
case 'image/jpeg': return '.jpg';
case 'image/png': return '.png';
default: return false;
}
}
if (!empty($_FILES["uploaded_image"]["name"]))
{
$file_name=$_FILES["uploaded_image"]["name"];
$temp_name=$_FILES["uploaded_image"]["tmp_name"];
$imgtype=$_FILES["uploaded_image"]["type"];
$ext= GetImageExtension($imgtype);
$imagename=date("d-m-Y")."-".time().$ext;
$target_path = "images/".$imagename;
if(move_uploaded_file($temp_name, $target_path)) {
$query="insert into users(images_path,submission_date,image_name)values('".$target_path."','".date("Y-m-d")."','$imagename')";
Now, I want to fetch the image and display it on the screen.This is the code I have written -
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project", $connection);
$query = mysql_query("select * from users where _id= '$r'");
$rows = mysql_num_rows($query);
if ($rows == 1 ) {
$row1=mysql_fetch_assoc($query);
$image=$row1["images_path"];
}
What should I write after this so that the image is displayed?

Use the image in an image tag like you normally would with an image URL.
echo '<img src="/'.$image.'" alt="an image"/>';
You may need to adjust the image path to be relative to the site root by prepending /path/to/images/ if your "images" folder is not in the site root.

If you get the correct path after your query, you can use the HTML tag with the parameter src= and the variable holding the path to your image. You need to know the name of the image of course

Simply build up an Image using the $image as the SRC attribute and then echo it back like so:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("project", $connection);
$query = mysql_query("select * from users where _id= '$r'");
$rows = mysql_num_rows($query);
$imgHTML = ""; // INITIALIZE THE IMAGE HTML TO NOTHING SO THAT YOU CAN STILL ECHO THIS VARIABLE IF THERE IS NO IMAGE
if ($rows == 1 ) {
$row1 = mysql_fetch_assoc($query);
$image = $row1["images_path"];
// JUST BUILD AN HTML REPRESENTATION OF YOUR IMAGE LIKE YOU WOULD IN NORMAL HTML BUT WITH PHP
$imgHTML = "<img alt='ALTERNATIVE_IMAGE_NAME' class='img_class' id='img_id' src='" . $image . "' />";
}
// NOW SIMPLY DISPLAY THE IMAGE.....
echo $imgHTML;

echo '<img src="'.$image.'" />';
OR
echo '<img src="'.$yourWebsiteBaseURL.'/'.$image.'" />';

Related

Error saving the path of an image in my database

I want to save the path of an image in my database, these images are generated with html2canvas and are saved in a directory, but when I generate them and save them in my database, a non-existent image name is generated and that is the one that stores me.
This is the code of how the image is saved in the database:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include './save.php';
$file = './images';
$route = $file. "/". $imgName;
$insert = $conexion->query("INSERT INTO images (img) VALUES ('$route')");
if ($insert) {
echo "<script>alert('successfully registered image')</script>";
}
else {
echo '<script>("Ups...Something's wrong")</script>';
}
}
This is the code that decodes the image for me and saves it in the folder:
$image = json_decode(file_get_contents("php://input"));
$image = $image->capture;
$image = str_replace("data:image/png;base64,", "", urldecode($image));
$image = base64_decode($image);
$imgName = "Image_" . uniqid() . ".png";
file_put_contents("images/$imgName", $image);

PHP Mysql - Image not displaying on browser (broken image)

I'm making an upload application and I have a script that once the images are uploaded they are resized but the original dimensions are stored to be used later on. the index.php should should show the images on the screen.
I've stored the image path instead of a blob on the database and using the 'path' variable to show it on the browser.
The search works but the images are not displaying and I can't find the reason why.
Im new to php/mysql so any help is appreciated on why my images are not showing up.
upload.php
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
// Add the heading to output
$output = '<h1>Gallery</h1>';
// Echo the gathered output
echo $output;
// Include the HTML header
include_once 'includes/head.html';
// Check if the form has been submitted...
if (isset($_POST['fileupload'])
&& isset($_POST['title']) && isset($_POST['description'])) {
$title = $_POST['title'];
$description = $_POST['description'];
if (is_uploaded_file($_FILES['userfile']['tmp_name'] )) {
$updir = dirname(__FILE__).'/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
if (move_uploaded_file($tmpname, $newimage)) {
//print if file was uploaded
//echo 'File successfully uploaded';
list($width, $height) = getimagesize($newimage);
//Add values to the DB
$sql = "INSERT INTO Images VALUES(NULL, '$title', '$description', '$width', '$height', '$path')";
$result = mysqli_query($link, $sql);
if(!$result) die ("Database access failed: " . $link->error);
$w = $width;
$h = $height;
resize($newimage, $width, $height);
}
} else {
//print if file failed
echo 'File upload failed';
}
}
//echo debug();
}
// Include the HTML footer
?>
index.php(The sql script is here)
<?php
require_once 'includes/config.inc.php';
require_once 'includes/functions.php';
if (!isset($_GET['page'])) {
$id = 'home'; // display home page
} else {
$id = $_GET['page']; // else requested page
}
switch ($id) {
case 'home' :
include 'uploads.php';
break;
default :
include 'views/404.php';
}
$sql = 'SELECT * FROM Images';
$result = mysqli_query($link, $sql);
if(!$result){
die(mysqli_error($link));
}else{
while($row = mysqli_fetch_array($result)){
echo '<div><a href= "#">
<img src="'.$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';
}
mysqli_free_result($result);
}
/*
Alternative way of showing the right images
$images = glob('uploads/*.jpg');
for($i = 0; $i < count($images); $i++){
list($w,$h) = getimagesize($images[$i]);
$allimages = $images[$i];
echo '<div><a href="'.$allimages.'">
<img src="'.$allimages.'" width="'.$w.'" height="'.$h.'" alt="" /></a>
</div><br/>';
}*/
include_once 'includes/footer.html';
?>
The problem is that you are using dirname(__FILE__) for the start of the path of your image and store that complete path in the database.
According to the manual dirname:
Returns the path of the parent directory.
And __FILE__:
The full path and filename of the file with symlinks resolved.
So you are storing your image using a absolute path on the local file system of the server.
However, that absolute path is not absolute relative to the root of the web-server so the browser will not find the images.
The solution is to use an absolute path when you move the uploaded image, but store a path that is absolute relative to the root of the web-server.
In your case you can probably use the /uploads/ path for that although that would depend on the exact file structure:
...
// no dirname here
$updir = '/uploads/';
//$upfilename = $_FILES['userfile']['name'];
$ext=end(explode(".", $_FILES['userfile']['name']));//gets extension
$newname = $updir.$title;
$tmpname = $_FILES['userfile']['tmp_name'];
$newimage = $newname.'.'.$ext;
$path = $newimage;
//if file is an image, upload it
if($_FILES['userfile']['type'] == 'image/jpeg'){
// only use dirname() here
if (move_uploaded_file($tmpname, dirname(__FILE__) . $newimage)) {
...
You have to add domain of your server to the src attribute of img tag so it'll became an absolute path for users to see the images:
echo '<div><a href= "#">
<img src="'$_SERVER['HTTP_HOST'].$row['path'].'" width=150 height=150 alt="'.$row['title'].'" /></a></div>';

Image uploader to use incremental image names

I am using a php multiple image uploader fine - the code is below. I am trying to modify it to assign incremental image names to the batch of images eg. Image1.jpg, Image2.jpg, Image3.jpg etc rather than a random name. I have tried changing the random code to a variable but no luck. Can anyone please help.
$ThumbSquareSize = 125; //Thumbnail will be 200x200
$BigImageMaxSize = 600; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$Reference_No = $_POST['Reference_No'];
$DestinationDirectory = 'properties/'.$Reference_No.'/'; //Upload Directory ends with / (slash)
$Quality = 75;
//ini_set('memory_limit', '-1'); // maximum memory!
foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName = $file['name'];
$ImageSize = $file['size'];
$TempSrc = $file['tmp_name'];
$ImageType = $file['type'];
if (is_array($ImageName))
{
$c = count($ImageName);
echo '<ul>';
for ($i=0; $i < $c; $i++)
{
$processImage = true;
$RandomNumber = rand(0, 9999999999); // We need same random name for both files.
if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'; //output error
}
else
{
//Validate file + create image from uploaded file.
switch(strtolower($ImageType[$i]))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($TempSrc[$i]);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($TempSrc[$i]);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
break;
default:
$processImage = false; //image format is not supported!
}
//get Image Size
list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
$ImageExt = str_replace('.','',$ImageExt);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
//Set the Destination Image path with Random Name
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
//Get New Image Size
list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
$DestinationDirectory = 'properties/'.$Reference_No;
echo '<li><table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestinationDirectory.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>';
echo '</tr>';
echo '</table></li>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
}else{
echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error
}
}
}
echo '</ul>';
}
}
you have 2 options
save the number to a file and read the file next time and add to it
keep a list of files in database table and get the last files index and add to it
You already have a for loop incrementing the integer variable $i, so change this:
//Construct a new image name (with random number added) for our new image.
$NewImageName = $RandomNumber.'.'.$ImageExt;
to the following code:
//Construct a new image name (with random number added) for our new image.
$NewImageName = 'Image'.$i.'.'.$ImageExt;

php displaying image from stored path?

UPDATE.
I can only display the images inside a query e.g.
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = $row['path'];
echo '<img src="'.$img.'">';
}
}
I want to display them inside a table but this code doesn't work :
<td class="tcgimagecell" colspan="5"><?php echo '<img src="'.$img.'">'; ?></td>
BELOW ISSUE RESOLVED :
I have images stored in a folder (uploads) and the path is stored in a database table in a field named path. I am trying to display the stored images.
$Link = mysqli_connect($Host, $User, $Password, $Database);
$Query = "SELECT * FROM $images";
if($Result = mysqli_query($Link, $Query)){
while($row = mysqli_fetch_array($Result))
{
$img = "uploads/" . $_FILES["file"]["name"];
echo '<img src="'.$img.'">';
}
}
Your folder permissions for "uploads/" might not be set to public read. Have you checked those already? What is the URL that is output for your image? Have you tried Copying URL and linked directly to it from your browser? If the URL is coming back blank, try $row instead of $_FILES since you are just wanting the path to the file.
This line is wrong: $img = "uploads/" . $_FILES["file"]["name"];.
Replace it with $img = "uploads/" . $row[x]; where x is the number of column where file name is
OR
with $img = "uploads/" . $row['columnname'];. Here you have to replace columnname.

Upload a picture with php issues?

so I am just learning PHP and am trying to make it so you can upload a picture. When attempting this on a local host all I get is a picture of a piece of paper being ripped in half (it must be some error/replacement picture). The directory for the image is right its just not being displayed properly.
thanks
Code:
<?php
//connect to the database
$link = mysql_connect("localhost", "root", "root")
or die("Could not connect: " . mysql_error());
mysql_select_db("images", $link)
or die (mysql_error());
//make variables available
$image_caption = $_POST['image_caption'];
$image_username = $_POST['image_username'];
$image_tempname = $_FILES['image_filename']['name'];
$today = date("Y-m-d");
//upload image and check for image type
//make sure to change your path to match your images directory
$ImageDir ="/Users/JohnSmith/Desktop/images/";
$ImageName = $ImageDir . $image_tempname;
if (move_uploaded_file($_FILES['image_filename']['tmp_name'],
$ImageName)) {
//get info about the image being uploaded
list($width, $height, $type, $attr) = getimagesize($ImageName);
switch ($type) {
case 1:
$ext = ".gif";
break;
case 2:
$ext = ".jpg";
break;
case 3:
$ext = ".png";
break;
default:
echo "Sorry, but the file you uploaded was not a GIF, JPG, or " .
"PNG file.<br>";
echo "Please hit your browser's 'back' button and try again.";
}
//insert info into image table
$insert = "INSERT INTO images
(image_caption, image_username, image_date)
VALUES
('$image_caption', '$image_username', '$today')";
$insertresults = mysql_query($insert)
or die(mysql_error());
$lastpicid = mysql_insert_id();
$newfilename = $ImageDir . $lastpicid . $ext;
rename($ImageName, $newfilename);
}
?>
<html>
<head>
<title>Here is your pic!</title>
</head>
<body>
<p>Here is the picture you just uploaded to our servers:</p>
<img src="Users/AdamAshwal/Desktop/images/<?php echo $lastpicid . $ext; ?>" align="left">
<strong><?php echo $image_name; ?></strong><br>
This image is a <?php echo $ext; ?> image.<br>
It is <?php echo $width; ?> pixels wide
and <?php echo $height; ?> pixels high.<br>
It was uploaded on <?php echo $today; ?>.
</body>
</html>
The image isn't being shown because your Desktop is not a public webroot. Make a directory within your app to store the uploaded images and render them from there.
JMC Creative's answer is correct, too -- your image tags don't seem to be looking in the right place for the uploaded images.
On a side note, you have a very obvious SQL injection vulnerability in the code sample that you provided. All user inputs that are being stored in the database should be sanitized with mysql_real_escape_string. See this XKCD comic for a humorous explanation. An example follows:
$image_caption = mysql_real_escape_string($_POST['image_caption']);
Shouldn't your image src be:
<img src="/Users/JohnSmith/Desktop/images/<?php echo $lastpicid . $ext; ?>">
The src should be relative to where the script is.
And don't use align="left" in the html tag, use css instead please.

Categories