PHP - Randomly grab a file from folder and echo - php

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.

Related

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

How to move/copy a file that has a wildcard in the name in PHP?

I am trying to copy a file that I download it. The file name is test1234.txt, but I want to access it using a wildcard like this: test*.txt and after that to move it to another folder (because I don't know how the file name looks like, but I know that the beginning is test and the rest is changing every time I download a new one). I tried some codes:
$myFile = 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNewFile = 'C:/Users/Carl/Downloads/'. date("y-m-d").'/text.xml';
if(preg_match("([0-9]+)", $myFile)) {
echo 'ok';
copy($myFile, $myNewFile);
}
I am getting an error because of * in $myFile. Any help is very appreciated.
$myFile= 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNyFile = 'C:/Users/Carl/Downloads/'.date("y-m-d").'/test.txt';
foreach (glob($myFile) as $fileName) {
copy($fileName, $myNyFile);
}
For complete response, if you want to only move *.txt in NewFolder.
$myFiles = 'C:/Users/Carl/Downloads/*.txt';
$myFolderDest = 'C:/Users/Carl/NewFolder/';
foreach (glob($myFiles) as $file) {
copy($file, $myFolderDest . basename($file));
}

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']];
?>

Get file name + path of images in folder - PHP

My script is pointing to a folder that stores images.
I would like to retrieve the file name and path name of the images so that my images get loaded when called (see html/php code below).
I have tried the following but i am getting an error:
Failed to open stream: Permission denied
On this line of code $page = file_get_contents($fileinfo->getPathname());
PHP
public function action_mybook($page = '') {
FB::log($this->request->param('id1'));
$this->template->content = View :: factory('mybook/default');
// give me a list of all files in folder images/mybook_images
$dir = new DirectoryIterator('images/mybook/');
$this->template->content->pages = array('.$dir.');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$pages[] = $fileinfo->getFilename();
$page = file_get_contents($fileinfo->getPathname());
}
}
}
HTML/PHP
<div id="book">
<!-- Next button -->
<div ignore="1" class="next-button"></div>
<!-- Previous button -->
<div ignore="1" class="previous-button"></div>
<?php
foreach ($pages as $page) {
echo '<div><img src="'.$page.'" /></div>';
}
?>
</div>
If I comment out the line $page = file_get_contents($fileinfo->getPathname()); and get no errors and the div for the image is created, but it says 'failed to load given url'
Loading the image manually using echo '<img src="myimage.png">' it displays the image
Possible problem
Your directory separator.
I try executate your code and get the same code. Whhy? Because the /. In windows is \. The return URL is invalid:
images/mybook\arrows.png
The correctly is:
images\mybook\arrows.png
or images/mybook/arrows.png (linux... in windows works too)
So, you need to use DIRECTORY_SEPARATOR constant of PHP, this solve your problem. See below:
UPDATE
I just add the $page to end of the URL in DirectoryIterator.
public function action_mybook($page = '') {
FB::log($this->request->param('id1'));
$this->template->content = View :: factory('mybook/default');
$dir = new DirectoryIterator('images' . DIRECTORY_SEPARATOR . 'mybook' . DIRECTORY_SEPARATOR . $page);
$this->template->content->pages = array('.$dir.');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
$pages[] = $fileinfo->getPathname();
}
}
}
I hope this help.
And sorry for my english.
Change permissions on files in directory on 777, and try again
Try to comment this line:
$page = file_get_contents($fileinfo->getPathname());
i have no any idea, that you need to read image file to variable.
Check your full image path, try this:
$pages[] = 'images/mybook/'.$fileinfo->getFilename();
or
$pages[] = '/images/mybook/'.$fileinfo->getFilename();
relate to your project path.
Try to give the permission to your image, you can give the permission using chmod :
chmod($fileinfo->getPathname(),0777);//add this line in your code
$page = file_get_contents($fileinfo->getPathname());
Note: $fileinfo->getPathname() should return the image path.

Glob() filesearch, question

a little question. I have this code, which is works perfect for files, but If am trying search on a directory name, the result is blank. How I can fix that?
<?php
function listdirs($dir,$search)
{
static $alldirs = array();
$dirs = glob($dir."*");
foreach ($dirs as $d){
if(is_file($d)){
$filename = pathinfo($d);
if(eregi($search,$filename['filename'])){
print "". $d . "<br/>";
}
}else{
listdirs($d."/",$search);
}
}
}
$path = "somedir/";
$search= "test";
listdirs($path,$search);
?>
somedir/test/
result: blank (I want: /somedir/test/)
somedir/test/test.txt
result: OK
I want to search also in the directory names, how I can do that?
If you want to search for a directory, you're going to have to change the if(is_file($d)) block. Right now, you're having it simply call listdirs again when it encounters a directory... but this also means you'll never see a print with a link to said directory.
I suggest doing something like this in the foreach instead:
$filename = basename($d);
if(eregi($search,$filename)){
print "". $d . "<br/>";
}
if(is_dir($d)){
listdirs($d."/",$search);
}
Your script is working fine. I think the webserver user does not have permissions to the given directory.

Categories