Iterating through results MongoDB & GridFS (PHP) - php

I am using GridFS and I have currently got it to display a single image using findOne, although I would like it to iterate through all the results in the grid and echo them all to screen, here is the code I am using:
<?php
try {
// open connection to MongoDB server
$conn = new Mongo;
// access database
$db = $conn->database;
// get GridFS files collection
$grid = $db->getGridFS();
// retrieve file from collection
header('Content-type: image/png');
$file = $grid->findOne(array('_id' => new MongoId('4fb437dbee3c471b1f000001')));
// send headers and file data
echo $file->getBytes();
exit;
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
Thanks

In general, if you're displaying images on a web page, you want to have a bunch of tags like <img src="someUrl" /> and then have each someUrl handle getting a single image.

Use "find" vs "findOne", which will return a result set you can loop through with a foreach, like:
$files = $grid->find({});
foreach($files as $file) { echo $file->someData; }

You set the header to image/png so the browser expects only one image.
What you could do is change that to a text/html document and embed the images using the data URI scheme (see http://en.wikipedia.org/wiki/Data_URI_scheme ) and then output the images in a series of images tags.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My images</title>
<head>
<body>
<?php
/* ... db connection/init code ... */
$files = $grid->find({});
foreach($files as $file) {
$encodedData = base64_encode($file->getBytes());
echo "<img src=\"data:image/png;base64,{$encodedData}\">";
echo "<br>";
}
?>
</body>
</html>
Note that you probably want to detect if the mime type of the image and change accordingly and set alt, width and height attributes using the file's metadata.
Hope this helps.

Related

PHP-How to re display images on website from fetched URL IMGS

So I'm a bit stuck, and I've been given various solutions, none of which work. Any hotshot PHP folks out there? Here's the deal, I'm trying to get an image to display on my website, from another website, that has a randomly generated IMG. Though I'm actually trying to do this off a personal art site of mine, this example will serve perfectly.
http://commons.wikimedia.org/wiki/Special:Random/File
A random image page with an image on it pops up with that link. Now, I'd like to display THAT random image, or whatever image comes up, on another site. The two possible solutions I have encountered is gathering an array of URL LINKS from a given link. And then re displaying that array as images on another site, like a: < a href="https
The code I get back from what I'm talking about looks like this:
Array
(
[0] => https ://kfjhiakwhefkiujahefawef/awoefjoiwejfowe.jpg
[1] => https ://oawiejfoiaewjfoajfeaweoif/awoeifjao;iwejfoawiefj.png
)
Instead of the print out however, I'd like the actual images displayed, well specifically array [0], but one thing at a time. The code that's actually doing this is:
<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/
*/
$url = 'http://commons.wikimedia.org/wiki/Special:Random/File';
// Fetch page
$string = FetchPage($url);
// Regex that extracts the images (full tag)
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $string, $out, PREG_PATTERN_ORDER);
$img_tag_array = $out[0];
echo "<pre>"; print_r($img_tag_array); echo "</pre>";
// Regex for SRC Value
$image_regex_src_url = '/<img[^>]*'.
'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER);
$images_url_array = $out[1];
echo "<pre>"; print_r($images_url_array); echo "</pre>";
// Fetch Page Function
function FetchPage($path)
{
$file = fopen($path, "r");
if (!$file)
{
exit("The was a connection error!");
}
$data = '';
while (!feof($file))
{
// Extract the data from the file / url
$data .= fgets($file, 1024);
}
return $data;
}
for($i=0; $i<count($arr1); $i++) {
echo '<img src="'.$arr1[$i].'">';
}
?>
Solution two,
Use a file_get_contents command. Which is this:
<?php
$html =
file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$image_src = $xpath->query('//div[contains(#class,"fullImageLink")]/a/img')
[0]->getAttribute('src') ;
echo "<img src='$image_src'><br>";
?>
However, there's unfortunately an error message I get: Fatal error: Cannot use object of type DOMNodeList as array in /home/wilsons888/public_html/wiki.php on line 11. Or, if I remove a "}" at the end, I just get a blank page.
I have been told that the above code will work, but with openssl extension included. Problem is, I have no idea how to do this. (I'm very new to PHP). Anyone know how to plug it in, so to speak? Thank you so much! I feel like I'm close, just missing the last element.
I was able to load the random image, and "print it" as an image directly (so you can embed the php file directly on the IMG tag) using this code:
<?php
$html = file_get_contents("http://commons.wikimedia.org/wiki/Special:Random/File");
$dom = new DOMDocument();
$dom->loadHTML($html);
$remoteImage = $dom->getElementById("file")->firstChild->attributes[0]->textContent;
header("Content-type: image/png");
header('Content-Length: ' . filesize($remoteImage));
echo file_get_contents($remoteImage);
?>
Get a new file called showImage.php and put this code in it:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<img src="test.php">
</body>
</html>
Next, go to your browser and get the showImage.php path, and will show a random image fromt he site you asked...

Try/Catch seems to work with $_POST but not with session variables, PHP

I'm working on a php tutorial where a thumbnail generation page allows me to select from a dropdown list of photos in a directory on my server and upon hitting the submit button, a thumbnail of given size is created using a custom thumbnail class (the thumbnail overwrites the original image, which is fine for what I'm doing now). It's basic stuff and works as expected.
The page code:
<?php
$folder = '../images/';
use ClassFiles\Image\Thumbnail;
if (isset($_POST['create'])) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($_POST['pix']);
$thumb->setDestination('../images/');
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
?>
<form method="post" action="">
<p>
<select name="pix" id="pix">
<option value="">Select an image</option>
<?php
$files = new FilesystemIterator('../images/');
$images = new RegexIterator($files, '/\.(?:jpg|png|gif)$/i');
foreach ($images as $image) {
$filename = $image->getFilename();
?>
<option value="<?= $folder . $filename; ?>"><?= $filename; ?></option>
<?php } ?>
</select>
</p>
<p>
<input type="submit" name="create" value="Create Thumbnail">
</p>
</form>
</body>
</html>
The custom thumbnail class is lengthy and for the sake of brevity I'm not posting it here unless requested, as it works fine.
So here's the problem:
I decided to take the image path and image filename information from an upload page I've been working on and store them in session variables that could be taken to the thumbnail generation page. The code in the thumbnail generation page was modified as shown:
<?php
require_once('includes/session_admin.php');
$folder = $_SESSION['image_path'];
use ClassFiles\Image\Thumbnail;
$getSize = getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']);
$imagePath = $_SESSION['image_path'];
$imageFilename = $_SESSION['image_filename'];
if ($getSize[0] > 400) {
require_once('ClassFiles/Image/Thumbnail.php');
try {
$thumb = new Thumbnail($imageFilename);
$thumb->setDestination($imagePath);
$thumb->setMaxSize(400);
$thumb->create();
$messages = $thumb->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
} else {
echo "Image is " . $getSize[0] . "px wide and is OK!";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Thumb</title>
</head>
<body>
<?php
if (isset($messages) && !empty($messages)) {
echo '<ul>';
foreach ($messages as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
// this was just to test that the session variables were correct
echo $_SESSION['image_path'] . $_SESSION['image_filename'];
echo '<br>';
print_r(getimagesize($_SESSION['image_path'] . $_SESSION['image_filename']));
?>
<!--
Removed the form...
-->
</body>
</html>
Now, instead of the conditional statement checking to see if $_POST was submitted, the code (I thought) would automatically check to see if the image, given the full path and filename, is wider than 400px, and if so, resize the image using the custom thumbnail class.
But, this throws errors from the thumbnail class, the same class that works just fine with the original thumbnail generation page code from the tutorial.
This works in the original tutorial code:
$thumb = new Thumbnail($_POST['pix']);
but not when modified to take a session variable instead:
$thumb = new Thumbnail($imageFilename);
I've looked and looked for any suggestion that $_POST was required here, I checked that the session variables were passing along the proper information, and they are. But making the switch from $_POST to using a session variable prevents this from working.
As you'll see, I'm still learning php and this is one of those hurdles that has held me up all day. Perhaps the answer is glaringly obvious, but I'm certainly at a standstill.
All input is appreciated, thanks!
Try this before set the object of your class
$_POST['pix']=$_SESSION['image_filename'];
So you set the POST variable manually and use it a The thumbnail class suppose it

PHP link to include header

I have php reading a text file that contains all the names of images in a directory, it then strips the file extension and displays the file name without the .jpg extension as a link to let the user click on then name, what I am looking for is a easy way to have the link that is clicked be transferred to a variable or find a easier solution so the link once it is clicks opens a page that contains the default header and the image they selected without making hundreds of HTML files for each image in the directory.
my code is below I am a newbie at PHP so forgive my lack of knowledge.
thank you in advance. also I would like a apple device to read this so I want to say away from java script.
<html>
<head>
<title>Pictures</title>
</head>
<body>
<p>
<?php
// create an array to set page-level variables
$page = array();
$page['title'] = ' PHP';
/* once the file is imported, the variables set above will become available to it */
// include the page header
include('header.php');
?>
<center>
<?php
// loads page links
$x="0";
// readfile
// set file to read
$file = '\filelist.txt' or die('Could not open file!');
// read file into array
$data = file($file) or die('Could not read file!');
// loop through array and print each line
foreach ($data as $line) {
$page[$x]=$line;
$x++;
}
$x--;
for ($i = 0; $i <= $x; $i++)
{
$str=strlen($page[$i]);
$str=bcsub($str,6);
$strr=substr($page[$i],0,$str);
$link[$i]= "<a href=".$page[$i]."jpg>".$strr."</a>";
echo "<td>".$link[$i]."<br/";
}
?>
</P></center>
<?php
// include the page footer
include('/footer.php');
?>
</body>
</html>
add the filename to the url that you want to use as a landing page, and catch it using $_GET to build the link.
<a href='landingpage.php?file=<?php echo $filename; ?>'><?php echo $filename; ?></a>
Then for the image link on the landing page
<img src='path/to/file/<?php echo $_GET['file'] ?>.jpg' />

Saving XML_Query2XML output to file?

I have a short script that utilizes the XML_Query2XML PEAR package. It pulls data from a SQL database and outputs to the browser. The XML that appears in the browser is exactly what I want to be saved to a file, but any attempts to use ob_get_contents or any of the other methods I'm familiar with result in a blank output file. The code is as follows:
<?php
set_include_path('/Library/WebServer/Documents/PEAR/');
include 'XML/Query2XML.php';
include 'MDB2.php';
try {
// initialize Query2XML object
$q2x = XML_Query2XML::factory(MDB2::factory('mysql://root:pass#site.com/site'));
$sql = "SELECT * FROM Products";
$xml = $q2x->getFlatXML($sql);
header('Content-Type: text/xml');
$xml->formatOutput = true;
echo $xml->saveXML();
} catch (Exception $e) {
echo $e->getMessage();
}
?>
I'm wondering what the general procedure is for saving files with this plugin and output type (XML). Any help is greatly appreciated.
The $xml variable is a DOMDocument object, which means you can use its methods to save it into a file, e.g. save:
$xml->save('foo.xml');

Tool for exporting html as pdf

I have a html document which marks up a report. I have a button on this page "Export as pdf". However I am not sure how to export html into a pdf..Are there any tools out there that anyone recommends for such a task..
EDIT: In more detail:
I have the following php:
<?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();
$sectionTwo = array();
$sectionThree = array();
$sectionFour = array();
$sectionFive = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$section = $row['sectionId'];
switch($section){
case '1':
$sectionOne[] = $row;
break;
case '2':
$sectionTwo[] = $row;
break;
case '3':
$sectionThree[] = $row;
break;
case '4':
$sectionFour[] = $row;
break;
case '5':
$sectionFive[] = $row;
break;
default:
break;
}
}
}else{
//error - sql failed
}
}
?>
<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(){
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
Export as PDF
</div>
<h3>Biological Information</h3>
<?php
$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++;
}
?>
<h3>Fatigue and Recovery</h3>
<?php
foreach($sectionTwo as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Illness and Injury</h3>
<?php
foreach($sectionThree as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>Training Sessions</h3>
<?php
foreach($sectionFour as &$value){
echo($value['question'].' : '.$value['answer']);
echo("<br/>");
}
?>
<h3>General Feedback</h3>
<?php
if(count($sectionFive)>0){
foreach($sectionFive as &$value){
echo($value['question'].' : '.$value['answer']);
}
}else{
echo("User didn't leave any feedback");
}
echo("<br/>");
?>
</body>
</html>
<?php
}
?>
This displays the following:
So if I'm using fpdf, what is the best way to export the following as a pdf? Should I write a fpdf function in the same php file or is it best to write a separate php file which creates and displays the pdf (which means I would have to post all relevant data to this file)...
Use FPDF library for php
check here
The first and the main base for this file conversion is FPDF library. FPDF is a pure PHP class to generate PDF files on the fly. Let us start the PDF generation with a simple Hello world display.
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
To generate a pdf file, first we need to include library file fpdf.php. Then we need to create an FPDF object using the default constructor FPDF(). This constructor can be passed three values namely page orientation (portrait or landscape), measure unit, and page size (A4, A5, etc.,). By default pages are in A4 portrait and the measure unit is millimeter. It could have been specified explicitly with:
$pdf=new FPDF('P','mm','A4');
It is possible to use landscape (L), other page formats (such as Letter and Legal) and measure units (pt, cm, in).
Then we have added a page to our pdf document with AddPage(). The origin is at the upper-left corner and the current position is by default placed at 1 cm from the borders; the margins can be changed with the function SetMargins().
To print a text, we need to first select a font with SetFont(). Let us select Arial bold 16:
$pdf->SetFont('Arial','B',16);
We use Cell() function to output a text. A cell is a rectangular area, possibly framed, which contains some text. It is output at the current position. We specify its dimensions, its text (centered or aligned), if borders should be drawn, and where the current position moves after it (to the right, below or to the beginning of the next line). To add a frame, we would do this:
$pdf->Cell(40,10,'Hello World !',1);
Finally, the document is closed and sent to the browser with Output(). We could have saved it in a file by passing the desired file name.
I've found this software quite useful: http://code.google.com/p/wkhtmltopdf/
It is true that you'll have to exec() it from your code, but it works very good and uses webkit as the backend engine (allowing javascript also, and many other features to customize the pdf creation), saving a lot of code.
Hope it helps, we're using it here and it works like a charm.
EDIT: try the static binaries. untar and ready to go :)
You may also use an online tool Pdfcrowd API
Its easy to integrate and provides much in its free edition. You may check
PDFCrowd Official Site
require 'pdfcrowd.php';
// create an API client instance
$client = new Pdfcrowd("username", "apikey");
// convert a web page and store the generated PDF into a variable
$pdf = $client->convertURI('http://www.google.com/');
//You can also convert raw HTML code, just use the convertHtml() method instead of convertURI()
$pdf = $client->convertHtml("<body>My HTML Layout</body>");
//Or use convertFile() to convert a local HTML file
$pdf = $client->convertFile("/path/to/MyLayout.html");
// set HTTP response headers
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"google_com.pdf\"");
// send the generated PDF
echo $pdf;
Another much easier way is with HTML2FPDF.
HTML2FPDF is a PHP Class library that uses the FPDF class library to convert HTML files to PDF files. This library consist of three classes namely PDF, HTML2FPDF and FPDF (modified FPDF class). The class PDF extends the class HTML2FPDF that extends the class FPDF.
Now let us see, how to convert a sample html page into a PDF file using HTML2FPDF Library. The html page contains a table that lists a few nations with their corresponding national flags. Below is the code for the conversion.
<?
require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();
$fp = fopen("sample.html","r");
$strContent = fread($fp, filesize("sample.html"));
fclose($fp);
$pdf->WriteHTML($strContent);
$pdf->Output("sample.pdf");
echo "PDF file is generated successfully!";
?>
First, we need to include the html2fpdf.php file that contains the HTML2FPDF class and an object is created using the constructor HTML2FPDF(). Then a new page is added to the pdf document using the function AddPage(). The html contents are read from the sample.html file using file functions. Then the html contents are written in to the pdf format using WriteHTML() function. To view the html file, click here and to view the generated pdf, click here. The above sample code with the sample html file and images and the html2fpdf class libraries can be downloaded here.
The HTML2FPDF class library will be working best with the XHTML 1.0. Also the class does not support all the features available with HTML. To know the supported HTML tags and other features, Please refer http://html2fpdf.sourceforge.net.
I recommend you to use this since it's much easier and friendly.

Categories