PHP Image help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjohnson
Forum Newbie
Posts: 3
Joined: Wed Oct 01, 2008 12:30 pm

PHP Image help

Post by cjohnson »

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi guys,

I really need some help. I am storing images in my MySQL database (I hate to do it, but I do not have write access to this folder to upload an image). I can load the image in the database and download it again, but it won't display. If I try to display in the page, it is garbage or the red x.

Here is my upload form:

Code: Select all

<?php # upload.php
 
//This file is the site's file upload page.
 
ob_start();
session_start();
require_once ('header.php');
 
if (isset($_POST['filesubmitted']) && isset($_FILES['userfile']) && isset($_SESSION['userid'])) {
    $userid = $_SESSION['userid'];
    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];
    $fp = fopen($tmpName, 'r');
    $image = fread($fp, filesize($tmpName));
    if(!get_magic_quotes_gpc()) {$image = addslashes($image);}
    fclose($fp);
    if(!get_magic_quotes_gpc()) {$fileName = addslashes($fileName);}
    global $dbc;
    require_once (MYSQL);
    $s = "INSERT INTO files (userid, image, name, type, size) VALUES ('$userid', '$image', '$fileName', '$fileType', '$fileSize')";
    $t = mysqli_query ($dbc, $s) or trigger_error("Query: $s\n<br />MySQL Error: " . mysqli_error($dbc));
    if (mysqli_affected_rows($dbc) == 1) {
        echo '<script>alert("File Submitted")</script>';
    } else {
        echo '<script>alert("File Not Submitted")</script>';
    }
}
 
echo '
<fieldset><legend><span style="color:blue">Form Upload
</span></legend>
<center><p>In this section, you may upload scanned images of the required forms for this position.</p>
 
<form method="post" enctype="multipart/form-data">
<b>Select file to upload:</b><br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" name="userfile" style="width:50%;" /><br />
<input type="submit" name="submit" value="Upload" style="width:50%;" />
<input type="hidden" name="filesubmitted" value="TRUE" />
</form>
</center>
</fieldset>
';
 
?>
 
<?php require_once ('footer.php'); ?>
and here is my view form:

Code: Select all

<?php # view.php
 
//This file is the site's file upload page.
 
ob_start();
session_start();
require_once ('header.php');
 
if (isset($_POST['viewfilesubmitted'])) {
    $fileid = $_POST['fileid'];
    global $dbc;
    require_once (MYSQL);
    $s = "SELECT * FROM files WHERE fileid='$fileid'";
    $t = mysqli_query ($dbc, $s) or trigger_error("Query: $s\n<br />MySQL Error: " . mysqli_error($dbc));
    if (mysqli_affected_rows($dbc) == 1) {
        $u = mysqli_fetch_array ($t, MYSQLI_ASSOC);
        $size = $u['size'];
        $type = $u['type'];
        $name = $u['name'];
        $image = $u['image'];
        header("Content-length: $size");
        header("Content-type: $type");
        header("Content-Disposition: attachment; filename=$name");
        echo $image;
        exit;
    } else {
        echo 'Error:  File could not be retrieved.';
    }
}
 
?>
 
<?php require_once ('footer.php'); ?>
Any help would really be appreciated!

Thanks,
Chris


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

When you display an image in an HTML page do you open the image file in a text editor, copy the contents of it, and paste it into the middle of your HTML?

No, didn't think so.

So why are you trying to do that with your PHP?

You need to write a script that recreates the image, and only the image, with no other data at all, and then call that script from your HTML using something like <img src="myimage.php">. You can pass $_GET vars like any other script. Just make sure there is nothing except the headers and the image data being sent from the image script.

(Which is, in a round about way, to say remove the line require_once ('header.php'); ... :) ... you might need to remove the Content-Disposition header too. I think that forces it to be downloaded instead of displayed.)
cjohnson
Forum Newbie
Posts: 3
Joined: Wed Oct 01, 2008 12:30 pm

Re: PHP Image help

Post by cjohnson »

Everything is working now. onion2k, you rock!

I have worked with php and mysql creating several sites, but never used a BLOB, so I just wasn't getting it. Read your post, and had one of those Homer Simpson d'oh moments.

Anyway, thanks for the help and the quick reply.

Chris
User avatar
panic!
Forum Regular
Posts: 516
Joined: Mon Jul 31, 2006 7:59 am
Location: Brighton, UK

Re: PHP Image help

Post by panic! »

Why was my post deleted?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

panic! wrote:Why was my post deleted?
Are you sure it was? There's nothing in the topic log.
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

:banghead:

I have the same problem - and onion, you explanation doesn't help me. Please, save!
Instead of image - abrakadbra :-)

content - is MEDIUMBLOB
also - error - headers already sent........ 3 months i re-writing in!!! HELP ME!!!

<html>
<head>
<title>List of Cars</title>
</head>
<body>

<br /><br />
<h3>These cars are currenly for sale:</h3>
<blockquote>
<?php
$dbcnx = @mysql_connect('localhost', 'xxx', ''xxx');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}

if (!@mysql_select_db('ddd')) {
exit('<p>Unable to locate the cars ' .
'database at this time.</p>');
}

$result = @mysql_query('SELECT brand, model, year, colour, driveside, doors, engine, fuel,
transmis, mileage, datereg, location, price, description,
name, type, size, content FROM cars');

// Display the car parameters in a paragraph
while ($row = mysql_fetch_array($result))
{
$name = $row['name'];
$type = $row['type'];
$content = $row['content'];

header("content-disposition: inline; name=$name");
header("content-type: $type");
header('content-lenght:' . strlen($content));

echo '<p><b>Make/Manufacturer:</b> ' . $row['brand'] . '</p>';
echo '<p><b>Model:</b> ' . $row['model'] . '</p>';
echo '<b>Year:</b> ' . $row['year'] . '<br />';
echo '<b>Driver Side:</b> ' . $row['driveside'] . '<br />';
echo '<b>Colour:</b> ' . $row['colour'] . '<br />';
echo '<b>Engine:</b> ' . $row['engine'] . '<br />';
echo '<b>Fuel:</b> ' . $row['fuel'] . '<br />';
echo '<b>Trasmission:</b> ' . $row['transmis'] . '<br />';
echo '<b>Mileage:</b> ' . $row['mileage'] . '<br />';
echo '<b>Doors:</b> ' . $row['doors'] . '<br />';
echo '<b>Registration Date:</b> ' . $row['datereg'] . '<br />';
echo '<b>Location:</b> ' . $row['location'] . '<br />';
echo '<b>Price:</b> ' . $row['price'] . '<br />';
echo '<b>Additional Details:</b> ' . $row['description'] . '<br /><br /><br />';
echo $content;
}
?>
</blockquote>
</body>
</html>
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

Actually you have exactly the same problem, and the fix is the same too. Don't output image data in the middle of HTML. Put an image tag in (eg <img src="image.php?id=1">) and write a script that only outputs the headers and image data.
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

Thanks, onion, can you please fix the code itself - I am completely stupid - :banghead: the main script - the one shows everything but image and the one you suggest to link with an image. I m open to suggestions and don't mind to pay some reasonable price - so long I am struggling with it... :crazy:
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

Can anyone write(fix) the code - for outputting the description from MySQL and also the code for outputting the image? Should it be stored in the same table or in different ones?
PLEASE HELP! I really need to do it and stuck for so long! :crazy:
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

:cry:
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

You need to remove all the code you've got that's trying to dump the image data into the middle of your HTML and replace it with an HTML image tag (eg <img src="image.php?image_id=1">) then write a script that only outputs the image data for that id. When you've at least done the HTML stuff post your code again.

Please don't bump this topic again if you don't have anything new to add.
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

hello, sorry if was too annoying. thank you for your advice - but it still doesn't work. still can't see image...
here all my code - any help will be handy - there is no problem with seeing text and i can see image stored in MySql via phpMyAdmin.

table
---------
CREATE TABLE cars (
carid INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
brand VARCHAR(55) NOT NULL,
model VARCHAR(55) NOT NULL,
year INT(11) NOT NULL,
colour VARCHAR(55) NOT NULL,
description TEXT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL
);

upload page
------------
//Connect to database

$dbcnx = @mysql_connect('localhost', 'xxx', 'yyy');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}

if (!@mysql_select_db('aaa')) {
exit('<p>Unable to locate the cars ' .
'database at this time.</p>');
}

// If user pressed submit
if (isset($_POST['brand'])):

$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$colour = $_POST['colour'];
$description= $_POST['description'];

$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

// Open file for reading ('rb')
$fp = fopen($tmpName, 'rb');

// Read the entire file into memory using PHP's
// filesize function to get the file size.
$content = fread($fp, filesize($tmpName));

// Prepare for database insert by adding backslashes
// before special characters.
$content = addslashes($content);

// Create the SQL query.

$sql = "INSERT INTO cars SET
brand='$brand',
model='$model',
year='$year',
colour='$colour',
description='$description',
name='$fileName',
size='$fileSize',
type='$fileType',
content='$content'";

if (@mysql_query($sql))

{
echo '<p><b>New car added</b></p>';
echo '<p><a href="cars.php"><b>Go to Cars listing</b></a></p>';

} else {
echo '<p>Error adding new car: ' .
mysql_error() . '</p>';
}

?>

<?php else:
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Add New Car</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<br />
<p><b><a href="<?php echo $_SERVER['PHP_SELF']; ?>?logout=1">Log out</a></b></p>
<br />


<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p><b>Enter the new car:</b></p>
<b>Brand: </b><input type="text" name="brand" /><br /><br />
<b>Model: </b><input type="text" name="model" /><br /><br />
<b>Year: </b><input type="text" name="year" /><br /><br />
<b>Colour: </b><input type="text" name="colour" /><br /><br />
<b>Driver Side: </b><input type="text" name="driveside" /><br /><br />
<b>Doors: </b><input type="text" name="doors" /><br /><br />
<b>Description: </b><textarea name="description" rows="15" cols="45"></textarea><br /><br />

<input type="hidden" name="MAX_FILE_SIZE" value="20000000" />
<b>Upload Image:</b><input name="userfile" type="file" id="userfile" />
<br /><br />
<input type="submit" name="upload" id="upload" value="SUBMIT" />
<input type="reset" value="CLEAR" />
</form>

<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>"><b>Add another car</b></a></p>
<p><a href="cars.php"><b>Return to cars list</b></a></p>
<p><b><a href="<?php echo $_SERVER['PHP_SELF']; ?>?logout=1">Log out</a></b></p>

<?php
endif;
include_once 'footer.html';
?>
</body>
</html>
----------------------------------
display cars (cars.php)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>List of Cars</title>
</head>
<body>

<br />
<?php
include_once 'header.html';
?>

<br /><br />
<h3>These cars are currenly for sale:</h3>
<blockquote>

<?php
$dbcnx = @mysql_connect('localhost', 'xxx', 'yyy');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}

if (!@mysql_select_db('aaa')) {
exit('<p>Unable to locate the cars ' .
'database at this time.</p>');
}

$result = @mysql_query('SELECT brand, model, year, colour, description
FROM cars');
if (!$result) {
exit('<p>Error showing cars: ' . mysql_error() . '</p>');
}


// Display the car parameters in a paragraph
while ($row = mysql_fetch_array($result)) {
echo '<p><b>Make/Manufacturer:</b> ' . $row['brand'] . '</p>';
echo '<p><b>Model:</b> ' . $row['model'] . '</p>';
echo '<b>Year:</b> ' . $row['year'] . '<br />';
echo '<b>Driver Side:</b> ' . $row['driveside'] . '<br />';
echo '<b>Colour:</b> ' . $row['colour'] . '<br />';
echo '<b>Additional Details:</b> ' . $row['description'] . '<br /><br /><br />';
echo '<img src="image.php">' . '<br /><br /><br />';
}
?>

</blockquote>
</body>
</html>

----------------
And following your advice - image.php - script that should display image from d/b....
--------------------
<?php

$dbcnx = @mysql_connect('localhost', 'sugarcu_timcar7', 'alexandra01');
if (!$dbcnx) {
exit('<p>Unable to connect to the ' .
'database server at this time.</p>');
}

if (!@mysql_select_db('sugarcu_timocars')) {
exit('<p>Unable to locate the cars ' .
'database at this time.</p>');
}
$id=$_Get['carid']

$sql = "SELECT name, type, size, content FROM cars where id= '$carid'";

$result=@mysql_query($sql);

if (!result) {
exit ('Databas error: ' . mysql_error());
}

$file=mysql_fetch_array($result);
if (!$file){
exit('No image available');
}

$name = $row['name'];
$type = $row['type'];
$content = $row['content'];

header("content-disposition: inline; name=$name");
header("content-type: $type");
header('content-lenght:' . strlen($content));

echo $content;

?>
--------------------------
Can you solve it? Please. And thank you for responding.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

Your image link is just image.php, yet in the image.php script you're trying to use $_Get['carid']. If you don't pass 'carid' to image.php you won't be able to use it. Every script is completely separate. You won't be able to access any variables that were set in the script that generates the HTML from image.php unless you pass it via $_GET.

Also, please use tags when you post code ... it's a lot easier to read if you do.
BattyNatty
Forum Newbie
Posts: 6
Joined: Fri Oct 03, 2008 8:45 am

Re: PHP Image help

Post by BattyNatty »

Thank you.
As I understand to pass 'carid' to image.php I need another header something like
header( "Location: carslastt.php?carid=$carid”);

I tried to put it after other headers in image.php - didn't help.

How would you recommend to pass it and whereexactly in image.php it should go?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: PHP Image help

Post by onion2k »

How would you pass the information from cars.php to image.php if image.php was just another PHP script rather than an image?

You'd have a link in cars.php that went to image.php?carid=$cardid wouldn't you?

So how do you think you'd do that in this case?
Post Reply