Calling external php function in <img> - php

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; ?>"/>

Related

Yii2: Error Not allowed to load local resource

Im trying to display images from backend of my app
<?php foreach ($img as $key=>$row): ?>
<div class="products_inside_wrapper intro_wrapper">
<div class="classes_inside_item bordered_wht_border">
<?php
foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
{
?>
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
<?php
}
?>
</div>
</div>
<?php endforeach; ?>
Tried with above code to display all images, but getting error Not allowed to load local resource when I open Google Chrome Inspect Element
i think you are using a local url instead of using this
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
try using it like
<?= Html::img(Yii::getAlias('#web').'/images/'.$value_img]);?>
As stig-js answered you can't load local saved image directly, If you're really interested into loading resources from a local path, you can open image as a binary file with fopen and echo the content of it with a proper header to output. In general way, you can add a method to your model like this:
public function getImage($imageName)
{
$imagePath = '#backend/web' . '/' . $imageName;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $imagePath);
finfo_close($fileInfo);
$fp = fopen($imagePath, 'r');
header("Content-Type: " . $contentType);
header("Content-Length: " . filesize($imagePath));
ob_end_clean();
fpassthru($fp);
}
P.S: Also you can use combination of this answer with showing image as base64 on HTML. See How to display Base64 images in HTML?
Images must be accesible by an url, like
yoursite.com/backend/imagedir/IMG'
If yoursite.com/backend points to your backend/web folder.
Backend alias points to your local path, so you need a custom alias to reach image folders.
Yii2 aliases: http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html

Exchanging variables between two pages PHP

I am aware that this kind of question has already been asked before, but I have a slightly different case.
foreach($dir as $file)
{
$file = '<li>'.basename($file).'</li>';
echo $file;
}
This is my script to display files in a folder and link to them. The way it is now, I use the $_GET['file'] on the other page to receive the information on the other page. The other page is supposed to display a photo/video with the file that has been linked, however I don't know how to use the $_POST or $_SESSION in this case, since it's a loop and I don't want the information about the file be in the link.
Also, I don't want any forms. I want to click the link with the name of the file and the other website to already have the information about the file and display the video or image.
Use like this by storing the media path in session and use the corresponding index to pass.
First file:
<?php
$i = 1;
session_start();
$dir = array('1.jpg', '2.jpg', '3.jpg');
echo '<ul>';
foreach($dir as $file)
{ //echo $i.'---'.$file."<br />";
echo '<li>'.$file.'</li>';
$_SESSION['media_'.$i] = $file;
$i++;
}
echo '</ul>';
?>
test.php
<?php
session_start();
echo $_SESSION['media_'.$_GET['file']];
?>

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.

Listing the html contents of a directory error

So basically, I'm using PHP to read the contents of a directory (one that only contains html files) and then to create a list of links.
<?php
$dir="../zpress/pages/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
?>
<p><a href="<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
It works perfectly on the pages where it lists them, but when i open the link it goes to www.mywebsite.com/zpress/g.html, whereas it's supposed to go to www.mywebsite.com/zpress/pages/g.html
Suggestions?
You'd need to output the correct path as well in your <a> area. The user's browser has absolutely NO way to tell that you're listing the contents of some OTHER area of the site, and will build urls based on the address of the current page. So you need to have:
<p><a href="../zpress/pages/<?php echo $filename; ?>"><?php echo $filename;
^^^^^^^^^^^^^^^^
Prefix the output so it goes to the right directory:
<p><?php echo $filename; ?></p>

printing a UL from an array of images

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.

Categories