im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.
Related
I am facing an issue to get images from database. I went through so many articles of stack and other websites also, but none have the solution I am looking for. How can I get images stored in the database on the page?
Here is the code, kindly check it and let me know what mistake I made. All help is really appreciated.
<?php
// I have database name databaseimage
// I have a table named store
// I have 3 columns into the table store
// id (int primary key ai), name (varchar), and image (longblob)
// prevent accesing the page directly
if($_SERVER['REQUEST_METHOD'] !='POST') {
echo "you can not acces this page directly";
die();
}
else {
print_r($_FILES);
// file properties
$file = $_FILES['image']['tmp_name'];
echo "<br>$file";
if(!isset($file)){
echo "please select an image";
die();
} else {
//actual image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])) ;
// image name
$image_name = addslashes($_FILES['image']['name']);
echo "<br> image name is = $image_name";
//geting image size to check whether it is actually an image or not
$image_size = getimagesize($_FILES['image']['tmp_name']);
echo "<br>";
print_r($image_size);
if($image_size==FALSE) {
echo "plese select an images only";
die();
}
else {
#code to put an image into the database
// connect to database
try {
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<br>connection succesfull";
// make a query
$extr = $con->prepare("INSERT INTO store (name, image)
VALUES (:na , :im)" );
//$a=1;
//$extr->bindParam(':i', $a);
$extr->bindParam(':na', $image_name);
$extr->bindParam(':im', $image, PDO::PARAM_LOB);
if ( $extr->execute()==true) {
echo "<br>image uploaded succesfully";
# insert is working. I can insert images into database
# but really facing problem while displaying those images
# below is the code I tried
# CODE for to show uploaded files
# to show images which is uploaded
$show = $con->prepare("SELECT * FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_BOUND) ) {
# SHOW IMAGES
//echo "<img src = '$row[image]' alt='image' >";
echo '<img src= "data:image/png;base64,'.base64_encode($row['image']).'"
height="100" width="100" />';
}
} else {
echo "<br>image not uploaded";
}
}
catch(Exception $e)
{
echo "<br> Connection failed: " . $e->getMessage();
}
}
}
// disconnect the connection
$con = null;
}
?>
Step 1: create a php script with filename getimage.php with the
following code:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$sql = "SELECT image FROM store WHERE id=$id";
$stmt=$con->query($sql);
$res=$stmt->fetch(PDO::FETCH_ASSOC);
$con=null;
header("Content-type: image/pn")g;
echo $res['image'];
?>
Step 2: In your current php page (below the comment "# below is the code i tried") try the following code:
$show = $con->prepare("SELECT id FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_NUM) ) {
# SHOW IMAGES
echo '<img src="getimage.php?id="'.$row[0].'"
height="100" width="100" />';
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
It was working fine just a while ago I was getting JSON response, which was an array of JSON objects now it shows a blank page ,I have no idea why! Can anyone identify what's the problem here?
here is the php code:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="tourist"; // Database name
// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
if($con){
mysqli_set_charset($con ,'utf8');
$qry = "SELECT * FROM places";
$query=mysqli_query($con ,$qry);
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}
$return_arr = array();
$row_array = array();
$num_rows = mysqli_num_rows($query);
if ($num_rows > 0) {
while ($r = mysqli_fetch_array($query)) {
$row_array['place_id'] = $r['place_id'];
$row_array['place_name'] = $r['place_name'];
//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//$row_array['image'] = "http://localhost/tourist/". $r['db_image']; //.'" alt=\"\" /"';
$row_array['image'] = "tourist/".$r['db_image'];
$row_array['des'] = $r['description'];
header('Content-Type: application/json');
array_push($return_arr,$row_array);
}
return json_encode($return_arr);
} else {
$return_arr['place_name'] = 'ERRO - Place inexistente';
}
header('Content-Type: application/json');
echo json_encode($return_arr);
return json_encode($return_arr);
mysqli_close($con);
} else {
$return_arr['place_name'] = 'ERRO - failure';
echo json_encode($return_arr);
return json_encode($return_arr);
}
?>
There are a few error in here
First you are mixing database access API's you cannot use mysql_ and mysqli_ calls. as you are connecting with mysqli_ stick with that
Secondly you do not use a return unless you are in a function. Used as you have it is killing the script the first one it comes across in the normal flow of the code, and of course NOT sending the data back to your browser.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="tourist"; // Database name
// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");
if($con){
mysqli_set_charset($con ,'utf8');
$qry = "SELECT * FROM places";
$query=mysqli_query($con ,$qry);
if (!$query) {
//$message = 'Invalid query: ' . mysql_error() . "\n";
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $qry;
die($message);
}
$return_arr = array();
$row_array = array();
$num_rows = mysqli_num_rows($query);
if ($num_rows > 0) {
while ($r = mysqli_fetch_array($query)) {
$row_array['place_id'] = $r['place_id'];
$row_array['place_name'] = $r['place_name'];
//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//$row_array['image'] = "http://localhost/tourist/". $r['db_image']; //.'" alt=\"\" /"';
$row_array['image'] = "tourist/".$r['db_image'];
$row_array['des'] = $r['description'];
header('Content-Type: application/json');
array_push($return_arr,$row_array);
}
// This will be terminating the script
//return json_encode($return_arr);
} else {
$return_arr['place_name'] = 'ERRO - Place inexistente';
}
header('Content-Type: application/json');
echo json_encode($return_arr);
// not needed
//return json_encode($return_arr);
mysqli_close($con);
} else {
$return_arr['place_name'] = 'ERRO - failure';
echo json_encode($return_arr);
// Not needed
//return json_encode($return_arr);
}
?>
I have an issue rendering stored images from phpmyadmin database.
I have two files, first one is image.php ,which is suppose to retrieve the images from database :
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("hostname","username","password");
if(!$conn)
{
echo mysql_error();
}
$db = mysqli_select_db("imagestore");
if(!$db)
{
echo mysql_error();
}
$ano = $_GET['ano'];
$q = "SELECT aphoto,aphototype FROM animaldata where ano='$ano'";
$r = mysqli_query("$q",$conn);
if($r)
{
$row = mysqli_fetch_array($r);
$type = "Content-type: ".$row['aphototype'];
header($type);
readfile($ano);
echo mysql_real_escape_string.$row['aphoto'];
}
else
{
echo mysql_error();
}
?>
and show.php , which is suppose to show the retrieved image :
<?php
//show information
ini_set('display_errors',1);
error_reporting(E_ALL);
include "connect.php";
$q = "SELECT * FROM animaldata";
$r = mysqli_query($conn,$q);
if($r)
{
while($row=mysqli_fetch_array($r))
{
//header("Content-type: text/html");
echo "</br>";
echo $row['aname'];
echo "</br>";
echo $row['adetails'];
echo "</br>";
//$type = "Content-type: ".$row['aphototype'];
//header($type);
echo "<img src=image.php?ano=".$row['ano']." width=300 height=100/>";
}
}
else
{
echo mysql_error();
}
?>
When I try show.php i get this result:
I would be very grateful for any help, because i tried many different codes but i could not find the solution and still getting the same result.
Thank you.
You should get rid of the readfileline as it is not needed and also the mysqli_real_escape_string from the line below. Otherwise this looks like it could work, but without knowing how you stored the images I can't know for sure. For example, if you stored them base64 encoded then you'd need to echo the the base64 decoded string.
I have PHP code for downloading pdf files from mysql database.
The code is working fine in firefox mozilla and google chrome but not in IE 10, it show garbage in the screen.
I have debugged the code with some headers utilities to examine the headers request, it appear the headers is not sending back to the user agent (IE browser) it just blank.
<?php
ob_start();
$company =$_GET['company'];
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if($id <= 0)
{
die('The ID is invalid!');
}
else
{
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno())
{
die("MySQL connection failed: ". mysqli_connect_error());
}
$query = "SELECT mime, name, size, data FROM $company WHERE id = $id";
$result = $dbLink->query($query);
if($result)
{
if($result->num_rows == 1) {
$row = mysqli_fetch_assoc($result);
$size = $row['size'];
$filename = $row['name'];
$data = $row['data'];
$mime = $row['mime'];
ini_get('zlib.output_compression');
ini_set('zlib.output_compression', 'Off');
header('Content-Type: application/pdf');
while (#ob_end_clean());
header('Content-Disposition: attachment; filename='.($filename));
header('Content-Length:'.($size));
echo $data;
exit();
}
else
{
echo 'Error! No image exists with that ID.';
}
mysqli_free_result($result);
}
else
{
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
}
}
else
{
echo 'Error! No ID was passed.';
}
?>
My php script is posting bad urls that ajax send to it. When I try to filter the url and cancel the insert into mysql, it doesn't work. What I want to do is verify the $link variable if it a link. If not, don't post data to mysql. Can i know what I did wrong and how to fix it? Thank you :)
Here is my code
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$link = $_POST['new'];
$name = $_POST['name'];
$size = $_POST['size'];
$cat = $_POST['cat'];
// PHP 5.3.5-1ubuntu7.2
$link = mysql_real_escape_string($link);
$name = mysql_real_escape_string($name);
$size = mysql_real_escape_string($size);
$cat = mysql_real_escape_string($cat);
if (filter_var($link, FILTER_VALIDATE_URL)) {} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
try this one:
if(filter_var($link, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) === false){
echo "URL is NOT valid";
mysql_close($con);
exit();
}
Your are right xxxhxtxtp://example.com will pass as valid url.
Try it with preg_match instead.
if (!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $link)) {
echo "URL is NOT valid";
mysql_close($con);
exit();
}
With this regex you need to have http(s) scheme. So you can search for another regex if that don't work for you.
Is this what you're trying to do? Perhaps you need a regex solution.
if (filter_var($link, FILTER_VALIDATE_URL)) {
$check = mysql_query("SELECT link FROM links WHERE link = '{$link}';");
if (mysql_num_rows($check) == 0) {
// insert
$sql="INSERT INTO links (link, name, size, category) VALUES ('$link','$name','$size','$cat')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added. Redirecting!";
mysql_close($con);
}
} else {
echo "URL is NOT valid";
mysql_close($con);
exit();
}