how to get images to print in loop - php

This is probably a very simple solution but I am new to PHP I have been searching google to find out how to get it to work to no avail. Here is my problem I want to be able to use the glob function along with extract(pathinfo) to find all images in a folder and print them into an html page. I can only get one image to print to the screen I figured it would print them in order it finds the files. Here is my code:
<?php
$images = glob('*.{png,jpg,jpeg}', GLOB_BRACE);
foreach($images as $img) {
extract(pathinfo($img));
$thumb_name = "$filename.$extension";
//$thumb_name = $info['filename'] . '.' . $info['extension'];
echo $thumb_name . "\n";
}
?>
And finally the html file:
<?php include 'index.php' ?>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<?php echo "<img src=\"$thumb_name\" title=\"bar\" alt=\"foo\" />"; ?>
<?php echo "<img src=\"$thumb_name\" title=\"bar\" alt=\"foo\" />"; ?>
</body>
</html>

not actual working code, but just for u to get an idea
Put the echo img inside the for loop
$images = glob('*.{png,jpg,jpeg}', GLOB_BRACE);
foreach($images as $img){
extract(pathinfo($img))
$thumb_name = "$filename.$extension";
echo '<img src=\'.$thumb_name\.' title=\bar\ alt=\foo\ />';
}

Related

Images are displaying vertically rather horizontally

Update: After looking at my HTML code in browser I figure out I need to only run the SQL code inside php just once in foreach loop and the images will be displayed horizontally. I was wondering how do I make that sql code run only once in that loop?
When I write the below code inside foreach ($ffs as $ff) {
Code:
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
So when this code is inside that foreach loop the images displays in vertical and I want my images to be displayed in horizontal (one next to other). But, if I remove that code from foreach and put it outside foreach code the image are displayed horizontally and works fine. I have tried CSS to display the image horizontally, but it only works if I remove that code from foreach. For some reason the above code (In foreach) somehow forcing the images to display in vertical, so no matter what I do it displays in vertical (the images).
I can't put my code outside foreach. I know I can use foreach to loop through my SQL code and it works fine, but the thing is I want it to work like first load images then first row only from sql, then 2nd image and 2nd row from sql and for that to make it work the only way is to put inside foreach my sql code, so it loads one at a time or else if I put it outside foreach It will load all the data of sql at once (1 row to 9 let's say) then all the images which makes no sense. I am storing my images in my hosting website files.
My question is how do I force my images to display horizontally one next to other?
My code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
require "testing.php";
?>
<html>
<head>
<link rel="stylesheet" href="userprofilestyl.css">
</head>
<body>
<hr>
<?php
global $username;
//username to get data of specific user
$username = $_SESSION['name'];
//to get image by username
$image = "images/$username";
global $increaseForText;
$increaseForText = 0;
function listFolderFiles($dir, $username, $increaseForText)
{
//getting images
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1) {
return;
}
$column_count = 0;
$sql = "select username_for_info, _name, _desc
from info_desc where username_for_info = '$username'";
try {
require "testing.php";
$stmt = $conn->prepare($sql);
$stmt->execute();
$Data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div class="image-container">';
foreach ($ffs as $ff) {
//select data from database
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/", $string));
$sav;
$sav = '<li>' . $ff;
global $sa;
$sa = "$ff";
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff, $username, $increaseForText);
}
//printing image
if (is_file($saving)) {
echo '<img src="' . $saving . ' " width="100" height="100" alt="Random image" />';
}
//printing text
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
$increaseForText++;
}
} catch (PDOException $e) {
echo '{error":{"text":' . $e->getMessage() . '}}';
}
echo '</div>';
}
listFolderFiles($image, $username, $increaseForText);
?>
</body>
</html>
Add this to your css file:
.image-container{
display:inline-flex;
flex-flow:row;
}
This will change the flow of every element inside the div with the class "image-container" from vertically to horizontally
Foreach has nothing to do with making the images display vertically, there should be something wrong with the HTML or CSS. Make sure your tags are closed, such as your p and li tags.
There are alot of ways to make the images display horizontally, it would easier if you can send a jsfiddle or a code snippet.
But try this on .image-container:
display: flex !important;
flex-flow: row;

How to Display Remote Image?

I need to have a working remote IMG display using PHP, let's say like this:
<img src='$src' />
And I need to fetch the remote URL based on $id, where
<?php
$id = "brown_fox";
$url = "http://exampl.com/$id";
get_remote_img($url) {
// some code to get image which SRC is dynamic:
<img id="pic" src="sjf5d85v258d.jpg" />
$src="sjf5d85v258d.jpg";
return $src
}
?>
I hope I explained it understandably.
If I understand you correctly then you can do something like this:
<?php
...
get_remote_img($url) { ...
$src = get_remote_img($url);
// Concatenating the result to the elements src attribute:
echo '<img src='.$src.' />';
?>
What you're looking for is something like this:
<?php
$id = "brown_fox";
$url = "http://exampl.com/" . $id;
...
function get_remote_img($url) {
// some code to get image which SRC is dynamic:
$src="sjf5d85v258d.jpg";
echo "<img id=\"pic\" src=" . "\"" . $src . "\"" . "/>";
return $src;
}
?>
Also, if you want to send and receive query parameters in the URI dynamically through a form, you can take a look at GET Request in PHP.

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

How to View multiple images which retrieve with explode from a single row of table

I am using this below code to retrieve image name and explode and to display. but the problem is the output. in out put view one extra blank image is displaying at the end in this below 75 id it consist of only 2 image name but it displaying 2 image with one blank image. Any help to solve this problem will be appreciate.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
?>
<!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>
<div>
<?php
$sql1=mysql_query("Select * from multiimg WHERE id=75");
$result=mysql_fetch_array($sql1);
/*$images = explode(",",$result['image']);
if(sizeof($images) > 0 ){
foreach($images as $image){
echo '<img src="photo/'.$image.'" height="50" width="50">' ;
echo "<br />";
}
}*/
$temp = explode(',',$result['image'] );
foreach($temp as $image){
$images[]="photo/".trim( str_replace( array('[',']') ,"" ,$image ) );
}
//now your array of images cotaines to full source to each image
foreach($images as $image){
echo "<img src='{$image}' height='100' width='200' />";
}
?>
</div>
</body>
</html>
There are three things you can do to get around this. One is to trim/remove the comma at the end of your image inputs in your table and the others are:
EDIT Add a trim() first:
// (I don't think you have to escape the comma, but I do anyway)
$result['image'] = trim($result['image'],'\,');
// Explode array
$temp = explode(',',$result['image'] );
// use array_filter() to remove empty key/values
// I had this filtering $images, but probably best to
// filter the original exploded array $temp
$temp = array_filter($temp);
foreach($temp as $image){
$images[]="photo/".trim( str_replace( array('[',']') ,"" ,$image ) );
}
foreach($images as $image){
// Use an if here...you could use a root directory if defined previously.
// Use whatever you like to check if the file exists
if(is_file(ROOTDIR.$image))
echo "<img src='{$image}' height='100' width='200' />";
}
This is a guess but try adding a trim statement before explode
like
$images = trim($result['image'], "'");
$temp = explode(',', $images);
First print and see how many images you are getting from the database. if they are correct as you need then do this or use trim to remove blank before this:
$temp = explode(',',$result['image'] );
foreach($temp as $image)
{
$images="photo/".$image;
echo "<img src='$images' height='100' width='200' />";
}
Try this, i sure whatever you want that you will getting from this below code. and one more thing if you get blank image than please check whether that images is exist in your folder from wherever you are trying to get..
<?php
$sql1=mysql_query("Select * from multiimg WHERE id=75");
$result=mysql_fetch_array($sql1);
$images=$result['image'];
$remove_last_comma=substr($images,0,-1);
$temp = explode(',',$remove_last_comma);
for($i=0;$i<count($temp);$i++)
{
echo '<img src="photo/'.trim($temp[$i]).'" height="50" width="50">';
echo "<br />";
echo "<br />";
}
?>

Php showing pictures using array

I'm trying to show images from some directory using foreach.. But the problem is it's showing results in array, so if i want to print out first image I have to use $imag['0']..
Is there any way that I can bypass this number in this brackets?
Here's my code...
<?php
$domena = $_SERVER['HTTP_HOST'];
$galerija = $_POST['naziv'];
$galerija = mysql_real_escape_string($galerija);
define('IMAGEPATH', 'galleries/'.$galerija.'/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
?>
<img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $imag['0']; ?>">
If you only need the first filename, then you could avoid the loop and directly access the first element of the array and use it afterwards:
$files = glob(IMAGEPATH.'*');
$filename = array_shift(array_values($files));
$image = basename($filename);
And to display it, you could use sprintf():
echo sprintf('<img src="http://%s/galerija/galleries/%s/%s"/>',
$domena, $galerija, $image);
Well you could first not create the array in the foreach statement and instead just print the img:
echo '<img src="', $domena ,'/galerija/galleries/', $galerija ,'/', $filename,'">';
Or you could iterate the array.
foreach($imag as $img): ?>
<img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $img ?>">
<?php endforeach; ?>

Categories