php file not opening on my new laptop - php

I have this form that pops up in a modal window like so:
<?php
error_reporting(0);
require("../codebase/grid_connector.php");
include '../site_globals/dbc.php';
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
//Get All Submission ID's for this popup
$datum = array();
$result = mysql_query("SELECT submission_id FROM submissions WHERE submissions.category='$array' AND submissions.manufacturer_id='$array1'");
while ($rowd = mysql_fetch_array($result, MYSQL_ASSOC)) {
$datum[] = $rowd['submission_id'];
}
$datalist = implode($datum, ' , ');
$datalist = filter($datalist);
// Use Submission ID's to Get All Image ID's for this popup
$datum9 = array();
$datasql = mysql_query("SELECT DISTINCT image_id FROM imagsub WHERE submission_id IN ($datalist)");
while ($row23 = mysql_fetch_array($datasql, MYSQL_ASSOC)) {
$datum9[] = $row23['image_id'];
}
$datalist2 = implode($datum9, ' , ');
$datalist2 = filter($datalist2);
//Select filenames from images table that matches $datalist2 results
$sql = "SELECT * FROM images WHERE image_id IN ($datalist2)";
$resultz = mysql_query($sql);
?>
<html>
<head>
<title>Supplychex Vendor Dashboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body onLoad="doInitGrid();" marginwidth="0"; topmargin="0">
<div style="width:100%; height:120px; background-image:url(../images/header.png)">
<div style="float:left; width:30%; text-align:center">
<form action="../php/pop_category_viewimages.php" method="post" name="MyForm" target="_blank" id="MyForm">
<fieldset>
<legend>Attachments</legend>
<SELECT id="dropdown" name="dropdown" style="width:250px">
<?php
while ( $rowg = mysql_fetch_array($resultz, MYSQL_ASSOC) ){
echo '<OPTION value="'.$rowg['image_id'].'">'.$rowg['filename'].'</OPTION>'."\r\n";
}
?>
</SELECT></br></br>
<INPUT type="SUBMIT" name="SUBMIT" value="View">
</fieldset>
</form>
</div>
</body>
</html>
I have this action for this form set to this file:
<?php
define("DB_HOST", ""); // set database host
define("DB_USER", ""); // set database user
define("DB_PASS", ""); // set database password
define("DB_NAME", ""); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$id = $_POST['dropdown'];
$query = sprintf('select * from images where image_id = %d', $id);
$result = mysql_query($query);
$image = mysql_fetch_array($result);
header('Content-type: ' . $image['mime_type']);
header('Content-length: ' . $image['file_size']);
echo $image['file_data'];
?>
I currently have a gif file and pdf file in the dropdown. Both gif and pdf work great on my desktop in all browsers. A new tab opens and displays either one. I just picked up a new laptop and eventhough Im using firefox 9 in both places when I run this on my laptop instead of simply displaying the pdf in a new tab the browser tries to download the pop_category_viewimages.php file. In IE on my laptop a new tab opens up blank. In chrome on my laptop the pdf opens up just fine. The gif opens fine in all browsers in all locations. Im totally thrown by this and hoping there is something I can adjust in my code to have the pdf open correctly in all browsers.

It means you do not have a PDF reader installed. Chrome is the only browser (AFAIK) that has a PDF renderer built-in. Other browsers delegate this task to third party software like Adobe's Acrobat Reader, which provide plugins that allow PDFs to be rendered directly in the browser. Lacking such available plugins, the only thing the browser knows what to do is to offer the file for download.

Set the content-disposition header to inline (to ask the browser to show it) or attachment (to ask the browser to download it to disk):
header('Content-Disposition: inline"');
Or
header('Content-Disposition: attachment; filename="downloaded.pdf"');

php file is server dependent, you may need to either configure your IIS, or install wamp or xamp to get the functionality your looking for.

Related

PHPExcel file could be corrupted or unsafe

When I generate an Excel report using PHPExcel I get this error:
"The file format and extension of 'test.xls' don't match. The file
could be corrupted or unsafe. Unless you trust its source, don't open
it. Do you want to open it anyway?"
This is my set up -- PHP 5.4/PHPExcel 1.7.9/Windows 7
When I click 'OK' to open the unsafe excel file anyway it either is empty or gibberish.
HTML Code: it allows the the user to select a report from the drop down then they select the button if they either want to preview the report, generate an excel file, or create a PDF file. But in this case I'm working on getting the excel files to generate.
<!DOCTYPE html">
<html>
<head>
<meta charset=utf-8" />
<title>Generate Reports</title>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<!--Display the Criteria screen only if Title Org Codes Report (rpt3) is selected-->
<script type="text/javascript">
function showForm() {
var selopt = document.getElementById("selReport").value;
if (selopt === "rpt3") {
document.getElementById("criteria").style.display = "block";
}
else {
document.getElementById("criteria").style.display = "none";
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="reports" class="center">
<h3> Generate Reports: </h3>
<!--Display the list of reports-->
<form id="frm1" name="frm1" method="post" action="Reports.php">
<!-- Excel, PDF, View buttons -->
<input type="submit" value="Preview Report" id="view" name="view">
<input type="submit" value="Export to Excel" id="excel" name="excel">
<input type="submit" value="Publish as PDF" id="pdf" name="pdf">
<br><br><br>
Select a Report:
<select id="selReport" name="selReport" onclick="showForm();">
<option></option>
<option value="rpt1">Units/Ranges Summary</option>
<option value="rpt2">Divisions Table</option>
<option value="rpt3">Title Codes</option>
</select>
<!--Creates the criteria drop down menu-->
<div id="criteria" style="display:none">
<br><br><h3>Selection Criteria for Reports:</h3>
Title File Status:
<select name="selCriteria" id="selCriteria" onchange="showForm();">
<option></option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="all">All</option>
</select>
</div> <!--end criteria -->
</form> <!-- end frm1 -->
</div> <!-- end #reports -->
</div> <!-- end #content -->
</div> <!-- end #wrapper -->
</body>
</html>
Here is the PHP file: where the PHPExcel code is executed. I built if else statements to indicate which report the user selected and run only that report.
<?php
//Get the user selection and put into variables
$varRpt = $_POST['selReport'];
$varCrit = $_POST['selCriteria'];
// require the PHPExcel classes
require 'PHPExcel/Classes/PHPExcel.php';
// PHPExcel_Writer_Excel2007
require 'PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';
//-------------------------------
// Connect to the MySQL database
//-------------------------------
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "*******";
$dbname = "test";
mysql_connect($dbhost,$dbuser,$dbpass)or die ("Could not connect to mysql because ".mysql_error());
mysql_select_db($dbname)or die("Unable to select database" .mysql_error());
//-------------------------------------
// Figure out which report to generate
//-------------------------------------
if ($varRpt == "rpt1")
{
$query = "SELECT a.div_id, a.unit_id, b.unit_beg, b.unit_end, a.title_org, c.long_desc, c.short_desc FROM depunits a LEFT OUTER JOIN unitRanges b ON ( a.unit_id )= ( b.unit_id ) LEFT OUTER JOIN orgcodes c ON ( a.title_org )= ( c.l1l5_id ) ORDER BY a.div_id, a.unit_id" ;
//Column headings
$headings = array('Div_id','Unit Id','Unit Begin','Unit End','Title Org','Long Desc','Short Desc');
// Sheet name
$title = "Summary Report Units/Ranges";
// Name of the saved excel file
$filename = "Rpt1_" . date('Ymd') . ".xls";
}
else
if ($varRpt == "rpt2")
{
$query = "SELECT alldiv_id, div_id, L1l2_id, L2_id, L1l3_id, L2l3_id, Exec_beg, Exec_end, Csa_id, Area_id, Area_Desc, Short_Desc, Long_Desc FROM divisions WHERE avail_ind='Y' AND active_ind='Y' ORDER BY alldiv_id ";
// Column Labels
$headings = array('All','Div','L1L2','L2','L1L3','L2L3','Exec Begin','Exec End','CSA','Area Id','Area Desc','Short Desc','Long Desc');
// Report Title
$title = "Divisions Table";
// name of the saved excel file
$filename = "Rpt2_" . date('Ymd') . ".xls";
} // end $varRpt == "rpt2"
else
if ($varRpt == "rpt3")
{
//Column heading
$headings = array('Title Code','Short Title','Long Title','Status');
// Report title
$title = "Title Codes";
// Name of the saved file
$filename = "Rpt3_" . date('Ymd') . ".xls";
if ($varCrit == "active")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 WHERE UPPER(TRIM(status))= 'A' ORDER BY L2l5";
}
else
if ($varCrit == "inactive")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 WHERE UPPER(TRIM(status))= 'I' ORDER BY L2l5";
}
else
if ($varCrit == "all")
{
$query = "SELECT L2l5, Stitl, Ltitl, Status FROM Tl2l5 ORDER BY L2l5";
}
}
//-----------------------------------------
// Insert data into Excel Report template
//-----------------------------------------
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Sheet name
$objPHPExcel->getActiveSheet()->setTitle('sheet1');
// Set the default font type (Arial) and the size (10)
$objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);
// Set the column headings to row 3 and data to start on row 4
$rowHeadStart = 3;
$rowDataStart = 4;
//Merge Cells for the report titles
$objPHPExcel->getActiveSheet()->mergeCells("A1:T1"); // Report Title
$objPHPExcel->getActiveSheet()->mergeCells("A2:T2"); // Date
//Set Cell Text
$objPHPExcel->getActiveSheet()->setCellValue("A1", $title);
$objPHPExcel->getActiveSheet()->setCellValue('A2', date("m/d/Y"));
//Make Report title bold
$objPHPExcel->getActiveSheet()->getStyle("A1:T1")->applyFromArray(array("font" => array( "bold" => true)));
//Make the date italicized
$objPHPExcel->getActiveSheet()->getStyle("A2:T2")->applyFromArray(array("font" => array( "italic" => true)));
//Make Column headers bold
$objPHPExcel->getActiveSheet()->getStyle("A3:T3")->applyFromArray(array("font" => array( "bold" => true)));
//---------------------------------------------
// Loop through to display the column headings
//---------------------------------------------
$col = 'A';
foreach($headings as $heading)
{
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowHeadStart,$heading);
$col++;
} // end $headings as $heading
//-------------------------------------------------
// Loop through the result set to display the data
//-------------------------------------------------
while ($row = mysql_fetch_row($result))
{
$col = 'A';
foreach($row as $cell)
{
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowDataStart,$cell);
$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
$col++;
} // end $row as $cell
$rowDataStart++;
//-----------------------
// Page/Cell Formatting
//-----------------------
//Set font size for the main report title
$objPHPExcel->getActiveSheet()->getStyle("A1")->getFont()->setSize(16);
$objPHPExcel->setActiveSheetIndex(0);
// Left align the entire document
$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
// Set the page orientation to landscape
$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
} //end $row = mysql_fetch_row($result)
// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="0teste.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit();
?>
A week ago the reports were able to generate using the code above but recently for some reason it's giving me the error that the file could be corrupted or unsafe. My PHPExcel class files are in my project folder so the paths are able to be referenced. I'm unsure how to fix this error.
If anybody could shine some light on this issue I would really appreciate it.
Thank you.
please use
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
instead of
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
I tried and it works.
Thank u

How to convert dynamic php file which accepts data from database to pdf?

I am working on WordPress website. And on front-end I am giving the functionality to create a resume online & on submitting the form he will get a option to download & print the resume in PDF format. Till now everything is working fine If I am passing a simple html file to convert into PDF. But I want to create a PDF out of the fields of resume inserted in the database. If I am passing the plain html file for conversion it works fine.
But what if I want to create a dynamic PDF file of the PHP file.
Here is my tried code:
I have used html2pdf conversion library for this.
This is a file from which the call to test.php goes.
require("html2pdf/html2fpdf.php");
$htmlFile = "test.php";
$buffer = file_get_contents($htmlFile);
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
And the test.php file is:
<html>
<body>
<?php
$username = "";
$password = "";
$hostname = "";
$dbname = "";
// Create connection
$con = mysqli_connect($hostname, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo $result = mysqli_query($con,"SELECT * FROM wp_resume ORDER BY id DESC LIMIT 1");
echo "hioooooo";
while($row = mysqli_fetch_array($result))
{
?>
<div>
<label>First Name</label><script type="text/php"><?php echo $row['firstName']; ?></script><br>
<label>Last Name</label><script type="text/php"><?php echo $row['lastName']; ?></script><br>
</div>
<?php
}
?>
</body>
</html>
Now after submitting the form I am getting a PDF file which contains only this data:
First Name
Last Name
And I want all the details of the entry inserted. Clearly this ignores the code inside the <?php ?> tags. So even if I used var_dump(), I didn't get anything.
SO please help me out in this guys. How can I pass the PHP data to PDF file.
Hey I got the solution for this. And the correct code is:
require("html2pdf/html2fpdf.php");
$html = '<h2>Resume</h2>';
$query = "SELECT * FROM wp_resume order by id desc limit 1";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$html .= '<div>
<label>First Name</label> '. $row['firstName'].'<br>
<label>Last Name</label> '. $row['lastName']. '<br>
</div>';
}
$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($html);
$pdf->Output('test.pdf', 'F');
I hope this will help somebody....
file_get_contents returns the content of a file, without it being parsed as PHP...
Replace
$buffer = file_get_contents($htmlFile);
With
ob_start();
include($htmlFile);
$buffer = ob_end_clean();
What we are doing: opening an output buffer (this prevents the echo from going to the client as they appear) then we include the PHP file so it gets parsed and all. Remember all the echo's are in the output buffer, so grab it with ob_end_clean() and use the generated HTML to make a PDF.

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

How to serve multiple images which reside above the www root within a single page?

I am hoping to offer users a user submitted image gallery. I have written a upload script which saves the file above the www root. I know I can serve the file by specifying the page header and then using readfile, however I am planning to throw the images within a table to be displayed with other information and dont think the header/readfile is the best solution. I am thinking maybe symlinks but I am not sure.
What is the best method to achieve this?
You'll need a script like getimage.php which sends the image headers and echo's out its contents. Then in your HTML, you just utilize it as the <img src=''> in your HTML. The only purpose of getimage.php is to retrieve and output the image. It remains separate from whatever PHP you use to generate the HTML sent to the browser.
Additionally, you can check if the user has a valid session and permission to view the image in getimage.php and if not, send a some kind of access-denied image instead.
The contents of getimage.php are small and simple:
// Check user permissions if necessary...
// Retrieve your image from $_GET['imgId'] however appropriate to your file structure
// Whatever is necessary to determine the image file path from the imgId parameter.
// Output the image.
$img = file_get_contents("/path/to/image.jpg");
header("Content-type: image/jpeg");
echo($img);
exit();
In your HTML:
<!-- as many as you need -->
<img src='getimage.php?imgId=12345' />
<img src='getimage.php?imgId=23456' />
<img src='getimage.php?imgId=34567' />
It then becomes the browser's job to call getimage.php?imgId=12345 as the path to the image. The browser has no idea it is calling a PHP script, rather than an image in a web accessible directory.
If the script is running on a Unix server, you might try to create a symlink in your web root that links to the directory outside of your web root.
ln -s /webroot/pictures /outside-of-webroot/uploads
If you're using an Apache server you could also have a look at mod_alias.
I've heard that there are a few issues when using mod_alias and configuring it through .htaccess. Unfortunately I don't have any experience with mod_alias whatsoever.
Something that always has worked well for me is to have users upload their images directly into my mysql db. The PHP will encode into base64 and store into a blob. Then you do something similar to what michael said to retrieve and display the image. I've included some code from a project I was working on in 2008. I wouldn't copy it exactly if it's a method you're interested in using since it's old code.
This is the PHP to upload and store into a DB. Obviously replace your info and connect to your own DB.
<?php
include("auth.php");
// uploadimg.php
// By Tyler Biscoe
// 09 Mar 2008
// Test file for image uploads
include("connect.php");
include("include/header.php");
$max_file_size = 786432;
$max_kb = $max_file_size/1024;
if($_POST["imgsubmit"])
{
if($_FILES["file"]["size"] > $max_file_size)
{
$error = "Error: File size must be under ". $max_kb . " kb.";
}
if (!($_FILES["file"]["type"] == "image/gif") && !($_FILES["file"]["type"] == "image/jpeg") && !($_FILES["file"]["type"] == "image/pjpeg"))
{
$error .= "Error: Invalid file type. Use gif or jpg files only.";
}
if(!$error)
{
echo "<div id='alertBox'> Image has been successfully uploaded! </div>";
$handle = fopen($_FILES["file"]["tmp_name"],'r');
$file_content = fread($handle,$_FILES["file"]["size"]);
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
$id = $_POST["userid"];
echo $_FILES["file"]["tmp_name"];
$default_exist_sql = "SELECT * FROM members WHERE id='".$id."'";
$default_result = mysql_query($default_exist_sql);
$results = mysql_fetch_array($default_result);
if(!$results["default_image"])
{
$insert_sql = "UPDATE members SET default_image = '$encoded' WHERE id='". $id ."'";
mysql_query($insert_sql);
}
$sql = "INSERT INTO images (userid, sixfourdata) VALUES ('$id','$encoded')";
mysql_query($sql);
}
else
{
echo "<div id='alertBox'>". $error . "</div>";
}
}
?>
<br />
<font class="heading"> Upload images </font>
<br /><br />
<form enctype = "multipart/form-data" action = "<?php $_SERVER['PHP_SELF']; ?>" method = "post" name = "uploadImage">
<input type = "hidden" name="userid" value = "<?php echo $_GET["userid"]; ?>" >
<input id="stextBox" type="file" name="file" size="35"><br />
<input type="submit" name="imgsubmit" value="Upload">
</form>
<?php include("include/footer.php"); ?>
This next one displays the file:
<?php
// image.php
// By Tyler Biscoe
// 09 Mar 2008
// File used to display pictures
include("connect.php");
$imgid = $_GET["id"];
$result = mysql_query("SELECT * FROM images WHERE imgid=" . $imgid . "");
$image = mysql_fetch_array($result);
echo base64_decode($image["sixfourdata"]);
echo $image["sixfourdata"];
?>
Then:
<img src="image.php?id=your_img_id">

image loaded from database does not show

guys.
I tried to load image stored in mysql blob field with php, but the image does not show correctly. In firebug, I got these infos: get-image.php Dimensions0 × 0File size5.35KBMIME typeimage/jpeg
Here is my code
HTML
<html>
<head>
<title>Demo of Database Image in a page</title>
</head>
<body>
Here is your picture:<br>
img src=get-image.php?id=1 width=400 height=300><br>
</body>
</html>
PHP
<?php
include "db.php";
$conn = OpenDbConnection();
$key = $_GET["id"];
$tkey = "" . $key . "";
$strsql = "SELECT * FROM `images` WHERE `image_id` = " . $tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
if (!($row = mysql_fetch_array($rs))) {
die("File not exists.");
}
header("Content-type: image/jpeg");
echo $row["content"];
mysql_free_result($rs);
mysql_close($conn);
?>
Please someone tell me what is wrong with my code?
Please try this code.
Instead of
echo $row["content"];
Use this code
?>
<img scr="<?php echo $row["content"];?>" />
<?php
Thanks,
Kanji
Maybe it's because of blog type. Whenever you upload an image which exceed the limit of blob, then image not displayed correctly. Try to change type from blob to long blob.

Categories