Jump to content

Recommended Posts

I have a script that allows users to upload an image into my database. Is there a way to pull that image from the database and display it as the image and not just as the filename? Or would the image have to be downloaded first into a folder?

Are you saving an image in your database (aka a BLOB) or are you saving the path to the image in your database?

 

If you are saving the path to the image, is the image inside your webroot?  If it is, you can simply use an img HTML tag.  If it is outside of the webroot, you can use readfile() + header() to display the image.

There is a readfile example on php.net:

 

http://us2.php.net/manual/en/function.readfile.php

 

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

When it saves the image to the database, it saves the filename into the database, but I also have a download script that allows me to download the image. Here is my upload insert and input files:

 

input:

<?php

session_start();

?>

<html>
<head>
<title>Sailor Moon RPG - Character Creation Form - Upload Image</title>
<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>
</head>
<body>
<!-- HEADER -->
<h1 class="logo">Sailor Moon RPG</h1>
<!-- /HEADER -->
<?php include("topnav.php"); ?>
<div id="main">
<?php include("includes/log.php"); ?>
<?php include("mainnav.php"); ?>
<h1>Character Creation - Upload Image</h1>
<h2>Please upload an image of your character.</h2>
<form method="post" enctype="multipart/form-data" action="upload.php">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</div>
<?php include("bottomnav.php"); ?><!-- FOOTER -->
<!-- FOOTER -->
<div id="footer_wrapper">
<div id="footer">
<p>Sailor Moon and all characters
are<br /> 
trademarks of Naoko Takeuchi.</p>
<p>Copyright © 2009 Liz Kula. All rights reserved.<br />
A product of <a href="#" target="_blank">Web Designs By Liz</a> systems.</p>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/digital/index.php" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/digital/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</div>
<!-- /FOOTER -->
</body>
</html>
[/code

insert
[code]
<?php

session_start();

if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$identity = $_SESSION['identity'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}

//connect to server and select database
$conn = mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("smrpg", $conn) or die(mysql_error());

$query = "INSERT INTO upload (identity, name, size, type, content ) ".
"VALUES ('$identity', '$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed');

$display_block = "<br>File $fileName uploaded<br>";
}
?>

<html>
<head>
<title>Sailor Moon RPG - Character Creation - Upload Image</title>
<style type="text/css" media="screen">
/*<![CDATA[*/
@import url(global.css); 
/*]]>*/
</style>
</head>
<body>
<!-- HEADER -->
<h1 class="logo">Sailor Moon RPG</h1>
<!-- /HEADER -->
<?php include("topnav.php"); ?>
<div id="main">
<?php include("includes/log.php"); ?>
<?php include("mainnav.php"); ?>
<h1>Character Creation - Upload Image</h1>
<?php echo $display_block; ?>
</div>
<?php include("bottomnav.php"); ?><!-- FOOTER -->
<!-- FOOTER -->
<div id="footer_wrapper">
<div id="footer">
<p>Sailor Moon and all characters
are<br /> 
trademarks of Naoko Takeuchi.</p>
<p>Copyright © 2009 Liz Kula. All rights reserved.<br />
A product of <a href="#" target="_blank">Web Designs By Liz</a> systems.</p>
<div id="foot-nav">
<ul>
<li><a href="http://validator.w3.org/check?uri=http://webdesignsbyliz.com/digital/index.php" target="_blank"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a></li>
<li><a href="http://jigsaw.w3.org/css-validator/validator?uri=http://webdesignsbyliz.com/digital/global.css" target="_blank"><img class="c2" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /></a></li>
</ul>
</div>
</div>
</div>
<!-- /FOOTER -->
</body>
</html>

 

Here is the download file:

 

<?php
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database

//connect and select database
$conn = mysql_connect("localhost", "root", "")
   or die(mysql_error());
mysql_select_db("smrpg",$conn) or die(mysql_error());

$id    = $_GET['id'];
$query = "SELECT name, type, size, content " .
         "FROM upload WHERE id = '$id'";

$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) =                                  mysql_fetch_array($result);

header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content;

//close database connection
exit;
}

?>

 

Can you explain how I'd get it to display?

The download file works based off of what file you click o download off of the display page:

 

<html>
<head>
<title>Download File From MySQL</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php
//connect and select database
$conn = mysql_connect("localhost", "root", "")
   or die(mysql_error());
mysql_select_db("smrpg",$conn) or die(mysql_error());

$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0) 
{
    echo "Database is empty <br>";
}
else
{
    while(list($id, $name) = mysql_fetch_row($result))
    {
?>
<a href="download.php?id=<?php echo $id; ?>"><?php echo $name; ?></a> <br>
<?php
    }
}
?>
</body>
</html>

 

But I want to display the image on another page (profile.php) based on the identity field in the upload table.

Yeah, sorry, the example I showed of readfile() forces the download instead of displaying the image.

 

What you need to do is create a file, called image.php or something.  Use it like this:

 

<img src="image.php?<?php echo $upload['id'] ?>" />

 

And image.php should look something like this:

<?php
$id = $_GET["id"];

$filename = // hit the database to get the path to the image

header("Content-type: image/jpeg");
readfile($filename);
exit;

Where I am displaying the image is already within a php tag...

 

$display_block .= "
	<tr>
	<td width=24% valign=top><strong>Character Name:</strong></td>
	<td width=55% valign=top>$name</td>
	<td align=center valign=top rowspan=18><img src=\"image.php?<?php echo $upload['id'] ?>\" /> height=\"500\" width=\"200\"></td>
	</tr>
	<tr>
	<td><strong>Element Of Influence:</strong></td>
	<td>$element_of_influence</td>
	</tr>
	<tr>
	<td><strong>Age:</strong></td>
	<td>$age</td>
	</tr>
	<tr>
	<td><strong>Date Of Birth:</strong></td>
	<td>$getMonth $birth_date, $birth_year</td>
	</tr>
	<tr>
	<td><strong>Height:</strong></td>
	<td>$height_feet feet $height_inches inches</td>
	</tr>
	<tr>
	<td><strong>Blood Type:</strong></td>
	<td>$blood_type</td>
	</tr>
	<tr>
	<td><strong>Hobbies:</strong></td>
	<td>$hobbies</td>
	</tr><tr>
	<td><strong>Favorite Color:</strong></td>
	<td>$favorite_color</td>
	</tr>
	<tr>
	<td><strong>Favorite Gemstone:</strong></td>
	<td>$favorite_gemstone</td>
	</tr>
	<tr>
	<td><strong>Favorite Food:</strong></td>
	<td>$favorite_food</td>
	</tr>
	<tr>
	<td><strong>Least Favorite Food:</strong></td>
	<td>$least_favorite_food</td>
	</tr>
	<tr>
	<td><strong>Favorite School Subject:</strong></td>
	<td>$favorite_school_subject</td>
	</tr>
	<tr>
	<td><strong>Least Favorite School Subject:</strong></td>
	<td>$least_favorite_school_subject</td>
	</tr>
	<tr>
	<td><strong>Strengths:</strong></td>
	<td>$strengths</td>
	</tr>
	<tr>
	<td><strong>Weaknesses:</strong></td>
	<td>$weaknesses</td>
	</tr>
	<tr>
	<td><strong>Goal:</strong></td>
	<td>$goal...</td>
	</tr>
	<tr>
	<td><strong>Mission:</strong></td>
	<td>$mission.</td>
	</tr>
	<td><strong>Character Biography:</strong></td>
	<td>$biography</td>
	</tr>
	<tr>
	<td> </td>
	<td> </td>
	<td valign=left>Created By: $username<br>
	Created On: [$character_create_time]</td>
	</tr>";
	}

	//close up the table
	$display_block .= "</table>";
}

 

How would I do it in this instance?

 

On your example for the upload.php file, where is says $file = //hit the database to get the path to the image, how do I get the path? I don't understand this part. Do I not need to have an SQL statement selecting the fields needed to be accessed by the variable? Like:

 

$get_file = "select * from upload where identity = $identity";

$get_file_res = mysql_query($get_file, $conn) or die(mysql_error());

 

I'm sorry. I might be making this more confusing than it needs to be. :-(

I have this for my image_upload page (the code you suggested):

 

<?php

//connect to server and select database
$conn = mysql_connect("localhost", "root", "")
or die(mysql_error());
mysql_select_db("smrpg", $conn) or die(mysql_error());

//verify the identity exists
$verify_identity = "select identity from upload where
identity = $_GET[identity]";
$verify_identity_res = mysql_query($verify_identity, $conn)
or die(mysql_error());

if (mysql_num_rows($verify_identity_res) < 1) {
//an image for this character does not exist
$display_block = "<p><em>You have not uploaded an image for your character.
Please <a href=\"file_upload.php\">upload</a> one</em></p>";
} else {

//get the image
$get_image = "select * from upload where identity = $_GET[identity]";
$get_image_res = mysql_query($get_image, $conn) or die(mysql_error());

while ($image_info = mysql_fetch_array($get_image_res)) {
	$image_id = $image_info['id'];
	$identity = $image_info['identity'];
	$name = $image_info['name'];
}
}	

$id = $_GET["id"];

//$filename = // hit the database to get the path to the image

header("Content-type: image/jpeg");
readfile($name);
exit;
?>

 

Is this right so far? Want to make sure I've written it right.

Here are a few lines of code from where I intend to display the image:

 

<?php
//add to display
	$display_block .= "
	<tr>
	<td width=24% valign=top><strong>Character Name:</strong></td>
	<td width=55% valign=top>$name</td>
	<td align=center valign=top rowspan=18><img src=\"image.gif\" height=\"500\" width=\"200\"></td>
	</tr>
	<tr>
	<td><strong>Element Of Influence:</strong></td>
	<td>$element_of_influence</td>
	</tr>";
?>

 

It is within php tags already. How can I implement your code into this?

 

<img src="image.php?<?php echo $upload['id'] ?>" />

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.