I have the next code:
<?php
$path = 'imgsFor';
$files_array = scandir($path);
for ($x=0; $x<=4; $x++)
{
echo '<img src="imgsFor/$files_array[$x]" <br>';
}
?>
In order to display all images in the folder imgsFor.
For some reason, I see the just boxes and not the actual images.
What can be the reason?
The best way for me is to use glob function:
foreach (glob($path) as $filename) {
echo '<img src="' . $path . '/' . $filename . '"/><br/>';
}
You messed up some things. Your correct script would be
<?php
$path = 'imgsFor/';
$files_array = scandir($path);
foreach($files_array as $f) {
if(is_dir($path . $f) === false)
continue;
echo '<img src="' , $path , $f , '"><br>';
}
/* EOF */
The reason is that your URL is invalid. Your variable wont echo out if you use single quotes. You also forgot to end the tag. Try this:
echo "<img src='http://yourwebsite.com/imgsFor/{$files_array[$x]}'/><br/>";
Please check you directory path and use is_dir which returns false when the file doesn't exist. you can try like this
$path = 'imgsFor';
$scan = scandir($path);
foreach($scan as $file)
{
if (!is_dir($path))
{
echo $file.'\n';
}
}
Related
I have a PHP script that scans a specified Movie directory then displays it styled on a webpage using for loop and php. The code is below. I tried using glob but once I have all the images in an array how do I compare them to the array with all of the movies then if the image and the movie folder match to display the image with the correct name?
<?php
// set dir to the directiry you want to index
$dir = 'Movies/';
// scanning the directory you set
$scan = scandir($dir);
// I have this value at 11 because the first movie shows up
// in the 11th file in the array
$file = 11;
// This then removes the first useless files from our array
$scanned = array_slice($scan, $file);
// gets the amount of files
$FileNum = count($scanned);
// display all images and fanart
$images = glob('*.jpg');
// for loop that goes through the array
for ($i = 0; $i <= $FileNum; $i++) {
// gives the class for styling
echo '<li class="image">';
this is problem bit
// check if there is fanart/images in the folders
if (file_exists($dir . $scanned[$i] . $images)) {
// if there is images display them styled
echo '<img id="box1" src="' . $dir . $scanned[$i] . '*.jpg' . '" width="280" height="150" />';
} else {
// if not then display default image
echo '<img id="box1" src="http://placehold.it/280x150" width="280" height="150" />';
}
// make the box clickable to where the folder is located
echo '<a href="'. $dir . $scanned[$i] .'">';
// display the name of the movie and some JS
echo '<span class="text-content"><span>' . $scanned[$i] .'<br><br><i class="fa fa-4x fa-play-circle-o"></i><br><br><i class="fa fa-chevron-down" onclick="openNav()" aria-hidden="true"></i></span></span> </a>';
}
The file structure is as follows
`MOVIES---
\--random movies
\--mp4 and .jpg files`
To clarify my question is - Is there a way to check if a file exists, and if it does then put it in an array? I've tried using glob but that can't check if the file exists.
Well there is an * in your echo i don't think it needs to be there.
And if your movie directory gets updated, or the images. Then your script does not work anymore. Because of the hard slicing (11th file).
Maybe this will work for you:
<?php
// movies
$dir = "movies/";
$files = scandir($dir);
$movies = array();
$images = array();
foreach ($files as $file) {
// check for the mime type:
$mime = mime_content_type($dir . $file);
$type = substr($mime, 0,5);
$filename = pathinfo($dir . $file, PATHINFO_FILENAME);
if ($type == "video") $movies[] = $file;
if ($type == "image") $images[] = $filename;
}
foreach ($movies as $movie) {
$placeholder = true;
foreach($images as $image) {
if (strpos($movie, $image) !== false) {
$placeholder = false;
continue;
}
}
if ($placeholder) {
echo $movie . " - placeholder<br>";
} else {
echo $movie . " - image<br>";
}
}
It works with the mime-type.
<?php
$dir_path = "./folder/";
if(is_dir($dir_path))
{
$files = opendir($dir_path);
{
if($files)
{
while (($file_name = readdir($files)) !== FALSE)
{
if ($file_name != '.' && $file_name != '..'){
echo "".$file_name."<br>";
#echo "<img src=".$file_name.">";
}
}
}
}
}
?>
Returns an array of files and directories from the directory . ... I wanted to easely access data in a certain directory using foreach. I came up with the following:
but it is not download
it say like this
Object not found!
In these cases first you need get files of directory like following:
$dir = './FILE_FOLDER_NAME';
$files = scandir($dir);
unset($files[0]);
unset($files[1]);
Why we used unset, these code remove . and .. from $files variable and you have just file names.
Now you can show files with this approach:
foreach($files as $key => $value):
$path_info = pathinfo($value); //RETURN FILE EXTENTION
?>
<a href="DIRECTORY_PATH<?php echo $value; ?>" target="_blank"><?php echo $value; ?>
<?php
endforeach;
If you want to delete a file can add new button to your foreach like this:
<button href="PHPSAMPLEFILE.PHP?file=<?php echo base64_encode ($value); ?>"><?php echo 'DELETE'; ?></button>
and in your PHP file:
$file = base64_decode($_GET['file']);
$path = './DIRECTORY_PATH/'.$file;
unlink($path);
Iam writting here for the first time. I wrote some php code which read files from folder and makes list of links to each file. Problem is that, its generates two more links at the begining of the list, which arent links to files, only dots. Does anyone have some idea to help me about this? This is the code:
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
}
echo '</div>';
?>
You always have to check for the . and .. directories and ignore them. They exist in every folder.
They are what are used when you do cd .. and ls . for example in a command window
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
if ( $file == '.' || $file == '..' ) {
continue;
}
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
echo '</div>';
?>
I tried sort, Ksort, multiSort, nothing is working and I'm not sure why.I can use print_r and see that it is an array but it won't sort just keeps giving errors. I think it is because the values are floats but I may be wrong.
Here's a page with the array shown using print_r function:
http://forcedchange.testdomain.pw/gallery/
Here is my code:
<?php
$uploads = wp_upload_dir(); //Path to my gallery uploads folder
if ($dir = opendir($uploads['basedir'].'/gallery-2')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
$images = ksort($images); /* not working */
// echo '<pre>';
// echo print_r($images);
// echo '</pre>';
foreach($images as $image) {
echo '<figure><img src="';
echo $uploads['baseurl'].'/gallery-2/'. $image;
echo '" alt="" /></li>';
echo '<figcaption>';
echo '<p>' . erq_shortcode() . '</p>';
echo '</figcaption>';
echo '</figure>';
}
?>
Try using natsort($images) (don't know which result you want). It should sort the array like:
1.png
2.png
...
9.png
10.png
...
20.png
Assigning won't work because the sort-funcs return a bool... the sorting is done direct inside the given array.
$images=glob("/path/*.{jpg,png,gif}");
ksort($images);
foreach($images as $image)
{
...
... do something with basename($image);
...
}
I have the following code that reads the content of a folder
PHP Code:
<?
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
//This function gets the file names of all images in the current directory
//and ouputs them as a JavaScript array
function returnimages($dirname="./images") {
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";' . "\n";
$curimage++;
}
}
closedir($handle);
}
sort($files);
return($files);
}
echo 'var galleryarray=new Array();' . "\n"; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
which spits out this the following code:
var galleryarray = new Array();
galleryarray[0] = "image1.jpg";
galleryarray[1] = "image5.jpg";
galleryarray[2] = "image2.jpg";
galleryarray[3] = "image4.jpg";
galleryarray[4] = "image8.jpg";
galleryarray[5] = "image7.jpg";
galleryarray[6] = "image0.jpg";
galleryarray[7] = "image3.jpg";
galleryarray[8] = "image6.jpg";
Now in my html file I want to echo something like
<img src="images/image0.jpg" />
<img src="images/image1.jpg"/>
...
...
How can I do that?
foreach($galleryarray as $img) {
echo "<img src='images/$img' />";
}
maybe this help u
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
if($handle = opendir("./images")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ ?>
<img src="/images/<?php echo $file; ?>">
<?php
}
}
}
assuming that you want to sort image name by value and then show the images. you first need to sort values by using function "asort"
asort($galleryarray);
foreach ($galleryarray as $key => $val) {
echo "<img src='images/{$val}'/>"
}
if you want to print and array
1) print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
2) use var_dump($array) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Try changing the echo line in the function to this:
echo '<img src="images/' . $file . '" />' ;
Hope this will help :)
OR
Outside the function, use it like this:
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
Also, you have to include this line inside the if condition in the while loop:
$files[] = $file; //insert the file into the array. This array is what we are going to return from the function
Update
I have tested this code and it's working:
//PHP SCRIPT: getimages.php
header('content-type: application/x-javascript');
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)"; // http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression/
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files); // http://php.net/manual/en/function.sort.php
natcasesort($files); // case insensitive "natural order" algorithm :: http://php.net/manual/en/function.natcasesort.php
return($files);
}
$images = returnimages(); //will get the array containing the images
foreach($images as $img)
{
echo '<img src="images/' . $img . '" />';
}
In my images folder, I have put 5 files for testing. And upon running it, it would give the following:
<img src="images/a.jpg" />
<img src="images/ba.jpg" />
<img src="images/ca.jpg" />
<img src="images/Copy (3) of a.jpg" />
<img src="images/Copy (4) of a.jpg" />