image does not fetch from database using path - php

I'm trying to upload and fetch images from database using path. Upload process working perfectly. But, I cannot able to fetch image from db. I've tried print_r($row['image']);. I'm getting the path like this C:/xampp/htdocs/xampp/htdocs/www/images/0d13808ad672c2713d306efbb0e42918. I don't know why this code doesn't fetch image from db?
fetch.php
<?php
include('config.php');
ini_set('display_startup_errors',1); a
ini_set('display_errors',1);
error_reporting(-1);
try
{
$stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
$conn->errorInfo();
// $stmt->bindParam('1', $imgid, PDO::PARAM_INT);
$stmt->execute();
// $path = "/xampp/htdocs/www/images/";
// $imgpath = $_SERVER['DOCUMENT_ROOT'].$path;
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<img src=".$row['image']." height='100' width='100'/>";
print_r($row['image']);
}
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
?>
upload.php
<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
include('config.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
// echo "Upload: " . $_FILES["file"]["name"] . "<br>";
// echo "Type: " . $_FILES["file"]["type"] . "<br>";
// echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
// echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
$filename = basename($_FILES['file']['tmp_name']);
$newname = md5($filename);
$final_save_dir = '/xampp/htdocs/www/images/'.$newname ;
if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name']))
{
echo "Uploaded";
}
else
{
echo "File was not uploaded";
}
$imgid = $_SERVER['DOCUMENT_ROOT'].$final_save_dir;
try
{
$stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
$stmt->bindParam('1', $imgid, PDO::PARAM_STR);
$conn->errorInfo();
$stmt->execute();
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
?>

Try this and compare with yours, I don't know if it works because I didn't tested, but it should.
upload.php
include('config.php');
if ($_FILES["file"]["error"] > 0 )
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$filename = basename($_FILES['file']['tmp_name']);
$ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$new_file_name = md5($filename).'.'.$ext;
$final_save_dir = $_SERVER['DOCUMENT_ROOT'].DS.'www'.DS.'images'.DS;
if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $new_file_name))
{
echo "Uploaded";
}
else
{
echo "File was not uploaded";
}
try
{
$stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
$stmt->bindParam('1', $new_file_name, PDO::PARAM_STR);
$conn->errorInfo();
$stmt->execute();
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}
}
fetch.php
<?php
include('config.php');
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
try
{
$stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
$conn->errorInfo();
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<img src='images/".$row['image']."' height='100' width='100'/>";
}
}
catch (PDOException $e)
{
echo 'Database Error'.$e->getMessage();
}

When you link the image, you have to link to an HTTP accessible path.
Use '/' instead of $_SERVER['DOCUMENT_ROOT'] to have a path relative to the web root of your page or 'http://' . $_SERVER['HTTP_HOST'] . '/' (first one is better as the protocol is not defined so it will work on both http and https connections)

Two things
move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $_FILES['file']['name']) moves the file from the temp location to $final_save_dir.$_FILES['file']['name'] which is different from the value you are storing in the db which is $_SERVER['DOCUMENT_ROOT'].$final_save_dir. You will need to sync these two variables.
Just like #mrgeek pointed you are trying to retrieve an image using the absolute filesystem path not using a http url. if you are using filesystem path you need to use file:/// prepended to the location. But i'm sure this is going to be hosted somewhere so that will not help. so best bet is to use relative urls so that the browser will be able to access it

Have been trying to retrieve image from my database with this code, but it just displays a blank page. Need help
$user="root";
$host="localhost";
$pass="name";
$db="name";
$link=mysql_connect($host,$user,$pass);
if(!$link)die(mysql_error());
mysql_select_db($db,$link) or die("could not select database.");
$query_image = "SELECT * FROM img WHERE id=12";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="upload/'.$row["img_base_name"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

Related

wait a few seconds before going further with the function php

so i have this deletefile function and i want it to go back to tyhe home page after 3 seconds automaticly
public function deleteFile($id)
{
try {
$query = "SELECT naam, bestand_path FROM bestanden ";
$query .= "WHERE id='$id'";
$result = $this->datahandler->readsData($query);
$results = $result->fetchAll();
foreach ($results as $row) {
$filename = $row['naam'];
}
$file = getcwd() . "/uploads/" . $filename;
//echo "Absolute Path To Directory is: ";
//echo $delfile;
***if (unlink($file)) {
echo $filename . ' was deleted successfully!';
header('Location: ' . SERVER_URL . '/Home/');***
} else {
echo 'There was a error deleting ' . $filename;
}
$query = "DELETE FROM bestanden ";
$query .= "WHERE id=$id";
$result = $this->datahandler->deleteData($query);
} catch (PDOException $e) {
echo "Fout opgetreden";
}
}
its about the one with the stars around it.
thank you

Trouble displaying images from MySQL database

My problem is thatmy code will only display one image from my database. I change the id to a different row, the name and everything else comes up fine but the image wont load. Even if I upload a new image this still happens? Please help!
<?php
session_start();
$user = $_SESSION['username'];
if(!empty($_SESSION['loggedin'])) {
$id = $_GET['id'];
$conn = new PDO ("mysql:host=localhost;dbname=project", "root",
"pass");
$stmt = $conn->prepare("SELECT * FROM images where id = :id");
try {
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($row = $stmt->fetch())
{
if($row == false)
{
echo "Sorry nothing here!";
}
else {
echo "$row[title]";
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['image'] ) . '" />';
echo "$row[username]";
echo "$row[description]";
echo "$row[category]";
}
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
What could be causing this? The images are stored as long blobs, their file types vary between jpg, jpeg, png and gif.
I have also tried the following which still works the same as above:
$image = $row['image'];
echo '<img src="data:image/jpeg;base64,'. base64_encode($image) .'" />';

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

How to upload ONLY images in database

I want to upload ONLY pictures , in the database using php.
What I tried is,
<?php
if (isset($_POST['Upload'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("iis", $con);
$image = $_FILES["product_image"]["name"];
$imageType = mysql_real_escape_string($_FILES["product_image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
if (!file_exists("product_images")) {
mkdir("product_images");
}
if ($_FILES["product_image"]["error"] > 0) {
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/" . $_FILES["product_image"]["name"]);
}
}
$UserName = $_SESSION['id'];
$product_image = ("product_images/" . $_FILES["product_image"]["name"]);
mysql_query("INSERT INTO `feedbackzxc` VALUES ('', '$UserName', '$product_image')");
echo "Image Uploaded!";
} else {
echo "Only images are allowed";
}
?>
But when I upload a file other than images it doesn't show the error message. How can I make it show error message if a file other than an image is uploaded?
Your else block where the message Only images are allowed is shown must be located after the if block that check this: substr($imageType,0,5) == "image"
if(substr($imageType,0,5) == "image"){
if(!file_exists("product_images"))
{
mkdir("product_images");
}
if($_FILES["product_image"]["error"] > 0)
{
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/".
$_FILES["product_image"]["name"]);
}
}
else
{
echo "Only images are allowed";
}

Display a default image if not exist in the database does not work as expected

I'm trying to show an default image, if an image are not stored in database. Then only show the image stored in database. How can I solve this proble? Thanks
conecta.php
<? ini_set('error_reporting',E_ALL);
ini_set('display_errors','on');
$oConni=new mysqli('localhost','****','****','****');
$oConni->set_charset('utf8');
?>
images.php
<?php
require('conecta.php');
$stmt=$oConni->prepare("SELECT IMAGEN_IMAGENES FROM IMAGENES WHERE ID_PRODUCTOS_OFERTADOS=?");
$stmt->bind_param('i',$_GET['idPrdOfr']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($foto);
while ($stmt->fetch()) {
header('Content-Type: image/jpeg');
echo $foto;
}
?>
search.php
function pintaImagen($id_prod_ofertados){
$pintaImg=null;
require ('conecta.php');
$xSQL="SELECT IMAGEN_IMAGENES FROM IMAGENES WHERE ID_PRODUCTOS_OFERTADOS=?";
$stmt = $oConni->prepare($xSQL) or die($oConni->error);
$stmt->bind_param('i',$id_prod_ofertados);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($imagen);
while ($stmt->fetch()) {
if (isset( $imagen )){
$pintaImg.="<img class='img' src='images.php?idPrdOfr=" . $id_prod_ofertados . "' />";
}
else{
$pintaImg.="<img class='img' src='images/none.png' />";
//$pintaImg;
}
return $pintaImg;
}
}
Probably it needs to be this way:
if ($stmt->fetch() && isset( $imagen )) {
$pintaImg.="<img class='img' src='images.php?idPrdOfr=" . $id_prod_ofertados . "' />";
} else {
$pintaImg.="<img class='img' src='images/none.png' />";
//$pintaImg;
}
return $pintaImg;
instead of the while loop in search.php.

Categories