printing a UL from an array of images - php

I am trying to print a UL list of images ending with _th.jpg returned from a specific folder. All i get back is array()
<?php
require '../../config.php';
$conn = new PDO(DB_DSN, DB_USER, DB_PASS);
$id = (int)$_GET['id'];
$q = $conn->query("SELECT * FROM cms_page WHERE id=$id");
$project = $q->fetch(PDO::FETCH_ASSOC);
$q->closeCursor();
$imagesDir = 'public/images/portfolio/'.$project['slug'].'/';
$images = glob($imagesDir . '*_th.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo $imagesDir ;
print_r($images);
?>
<h1><?=htmlspecialchars($project['title'])?></h1>
<?php
if ($images < 1) {
echo '<div id="slider">';
echo '<ul>';
foreach($images as $key => $value) {
echo '<li><img src="public/images/portfolio/'.$project['title'].'/'.$value.'.jpg" width="160" height="96" /></li>';
}
echo '</ul>';
echo '</div>';
} else {
echo 'There are currently no images to display for tihis project.';
}
?>
Anyone got any ideas?

First of all : are you sure you are reading from the right directory ?
What I mean, is : does 'public/images/portfolio/'.$project['slug'].'/' really exist, and is accessible from your script, using this relative path, in this PHP script ?
(You can test that with is_dir, for instance)
As a precaution, when working with files and directories, I like using absolute paths, so I always know to which directory exactly I'm accessing.
For instance, something like this :
$imagesDir = '/var/www/public/images/portfolio/'.$project['slug'].'/';
If you do not know the absolute path to your directories, you can use dirname(__FILE__), to get the absolute path to the current PHP file -- and then, starting from that file, use a relative path ; for instance :
$imagesDir = dirname(__FILE__) . '/public/images/portfolio/'.$project['slug'].'/';
This way, you don't have to care about the current working directory : your path will always be the same, as it's not relative.
If that doesn't work, then first of all, make sure you are accessing the right directory.

<h1><?=htmlspecialchars($project['title'])?></h1>
Is <? a valid PHP opening tag?
Since your last block of PHP code isn't apparently executed (since it would either print an empty ul or the text from the else block) I suspect the PHP doesn't get parsed correctly.

Related

Get image from PHP displaying using an img src

The code I have should output a jpg from a list of files in a directory however it is not. I have trawled this site and tried different methods but not helped. I am a relative beginner at php so looking for any help at all.
I have tried using img src in the php code but I am trying to get the image to display within a Wordpress post so I cannot echo the img src within the script. I have tried file_get_contents and read file as well but it may be my lack of knowledge holding me back.
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);
define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );
If(LOCALHOST){
define('PATH_IMAGES', 'this_path');
}else{
define('PATH_IMAGES', '../../../Images/');
}
$arrnum = $GLOBALS[imagenum] - 1;
$dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
$images = scandir($dirname);
rsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
header('Content-type: image/jpeg');
file_get_contents('$dirname$images[$arrnum]');
}
}
?>
Have you tried readfile(...); should read and output the file. In your example you are not outputting the image data
http://php.net/manual/en/function.readfile.php

Calling external php function in <img>

I've created an external php file (sort.php) that sorts the files in a folder on the server by time modified, and returns the most recent file.
<?php
function scanDir ($dir){
$fileTimeArray = array();
// Scan directory and get each file date
foreach (scandir($dir) as $fileTime){
$fileTimeArray[$fileTime] = filemtime($dir . '/' . $fileTime);
}
//Sort file times
var $latestFile = arsort($fileTimeArray);
return($latestFile[0]);
}
?>
I'm attempting to call this function inside of , in another php file, and set the src:
<img <?php echo 'src="'.scanDir("issues/preview").'"';?>/>
I've included sort.php at the top of the page in question.
The image src reads "(unknown)". What am I missing or doing wrong or both?
Thank you!
I would write
<?php $x = scanDir("issues/preview"); ?>
<img src="<?php echo $x; ?>"/>

PHP - Randomly grab a file from folder and echo

I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content.
I'd like to randomly grab a file from this folder and echo it into a div. Here is what I have:
<?php
function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
<div class="my-div">
<?php echo random_update(); ?>
</div><!--end my-div-->
I am getting 500 errors? Also, my intention is to only echo 1 file at a time. Will the provided code accomplish that?
Php does not recognize the syntax you used. You have to bypass it like this:
<?php
function random_update($dir = NULL)
{
if ($dir === NULL) {
$dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
}
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Also, you might want to enable error dumping in your development environment so you know what went wrong next time.
Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code:
<?php echo random_update(); ?>
for this one:
<?php echo file_get_contents (random_update()); ?>
because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div.
You can't use any expression as "default" function's argument value.

CodeIgniter doesn't see images (using file_exists)

I'm learning CodeIgniter. I have a directory img with images (path /img/). I am trying to access it through CI view and check if exists with this code:
$av = '../../../img/content/users/'.$userID.'.jpg';
if(file_exists($av)) {
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works. What should I do?
CI always runs on index.php, so paths are always relative from there.
Assuming index.php and /img are at the same level in the root, try this:
$av = 'img/content/users/'.$userID.'.jpg';
if(is_file($av)) { // or better yet, make sure it's really an image
$avatar = $av;
} else {
$avatar = 'img/content/users/none.jpg';
}
Funny thing is, echoing <img src="'.$av.'"> works
It's because the browser is looking in a different place than the server. I'd recommend not using ../../relative/paths but using functions like base_url() and img(). When there are additional segments in the URL, relative paths break.
URLs and file paths are not the same. From the current URL ../../../img/content/users may and likely is something completely different than the file path on the hard disk where the view file is located.
Use following steps
1) Create a custom config file name site_config.php in config file (/application/config/) and paste following code
<?php
$config['base_url'] = "http://".$_SERVER['SERVER_NAME'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
if(!defined('DOCUMENT_ROOT')) define('DOCUMENT_ROOT',str_replace('system/application/config','',substr(__FILE__, 0, strrpos(__FILE__, '/'))));
$config['base_path'] = constant("DOCUMENT_ROOT");
?>
2) Edit autoload.php to autoload site_config.php (/application/config/autoload.php)
$autoload['config'] = array('site_config');
3) Then using following code to view image
$image_path = $this->config->item('base_path').'folder_name/'.$userID.'.jpg';
if(file_exists($image_path)) {
$avatar = $this->config->item('base_url').'folder_name/'.$userID.'.jpg';
} else {
$avatar = $this->config->item('base_url').'default_folder_name/profile.jpg';
}
echo '<img src="'.$avatar.'" />';
I think it will help you
Try this:
$av = './img/content/users/'.$userID.'.jpg';

Get list of all image files in a directory

I am trying to generate some HTML code to list some images for a slide show.
I arrived at the following idea:
function galGetTopPhotos()
{
//path to directory to scan
$directory = SITE_ROOT_PATH."/gallery/best/";
//get all files
$images = glob($directory . "*.*");
//print each file name
$ret = "";
$ret .= '<div id="myslides">';
foreach($images as $image)
{
$ret .= '<img src="'.$image.'" />';
}
$ret .= '</div>';
return $ret;
}
The problem is that it only works when I use root path for $directory...if I use URL it will not work. And it causes the images to not load. Here is what this code generates:
<div id="myslides">
<img src="D:/xampp/htdocs/mrasti/gallery/best/1.jpg" />
<img src="D:/xampp/htdocs/mrasti/gallery/best/10.jpg" />
</div>
So the question is, how to get the list of files so it generates img sources in http://127.0.0.1/.... format?
What I mean if I use the code like this it returns no file!
$directory ="http://127.0.0.1/mrasti/gallery/best/";
This looks like a job for PHP function basename. This takes a file path and returns only the final element of the path - in this case the actual name of the jpeg image.
You could amend your code so that it looks something like this:
$urlPath = "http://127.0.0.1/mrasti/gallery/best/";
...
...
foreach($images as $image)
{
$relative_path = $urlPath.basename($image);
$ret .= '<img src="'.$relative_path.'" />';
}
The above takes the path and appends the filename "example.jpg" to your image directory url
glob does only work for local files and not on remote files. Have a look here:
http://php.net/manual/en/function.glob.php
For remote files have a look here:
http://www.php.net/manual/en/features.remote-files.php
But i do not think that you need remote files. It seems like you want to go through a local directory and display this images.
Try something like this
...
$ret .= '<img src="http://127.0.0.1/my/path/'.basename($image).'" />';
...
You need to have some functionality to translate the file path on disk to the correct URI so that your browser can understand it.
In your specific case as outlined and with the exact data given in your question, the following could work:
foreach($images as $image)
{
$src = '/mrasti/gallery/best/'.substr($image, strlen($directory));
$ret .= '<img src="'.$src.'" />';
}

Categories