I scan a directory with PHP which includes only folders:
$folders = scandir('gallery');
Now i want to check if a string in javascript a folder in this directory.
if(theString == allTheFolders){
alert('yay');
}
Now $folders is an array with strings in it. To get all the strings i use a foreach loop and ignore the '.' & '..' directory's. But how can i get all these folders in the if loop?
Hope you understand my question!
Echo out your array as JSON, right into your JavaScript.
echo 'var folders = ', json_encode($folders);
Then you can loop through or do whatever you need directly in JavaScript.
Edit: Now that you have posted your actual question... Do this in your JavaScript:
var wantedFolder = 'something';
var wantedFolderFound = false;
for (folderIndex in folders) {
if (folders[folderIndex] === wantedFolder) {
wantedFolderFound = true;
}
}
if (wantedFolderFound) {
alert('Folder found!');
} else {
alert('Folder not found.');
}
As an alternative, I would probably use Array.indexOf(). It isn't available in all browsers, but that problem is easily remedied. See the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
Related
I'm a newbie...sorry...I'll admit that I've cobbled this script together from several sources, but I'm trying to learn. :-) Thanks for any help offered!!
$directory = new \RecursiveDirectoryIterator(__DIR__, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
if ($current->getFilename() === '.') {
return FALSE;
}
if ($current->isDir()) {
return $current->getFilename() !== 'css';
}
else {
// Only consume files of interest.
return strpos($current->getFilename(), 'story.html') === 0;
}
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
$files[] = $info->getPathname();
}
?>
Then down in my HTML is where I run into problems, in the 2nd echo statement...
<?php
echo '<ul>';
foreach ($files as $item){
echo '<li>http://<domain.com/directory/subdirectory/story.html></li>';
echo '</ul>';
};
?>
The purpose of my script is to "crawl" a directory looking for a specific file name in sub-directories. Then, when it finds this file, to create a human-readable, clickable URL from the server path. Up to now, my HTML gets one of these two server paths as my list item:
http://thedomain.com/var/www/vhosts/thedomain.com/httpdocs/directory/subdirectory/story.html
or
file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html
...depending on where I'm running my .php page.
I feel like I need to "strip away" part of these paths... to get down to /subdirectory/story.html ... If I could do that, then I think I can add the rest into my echo statements. Everything I've found for stripping strings has been from the trailing end of the path, not the leading end. (dirname($item)) takes away the filename, and (basename($item)) takes away the subdirectory and the filename ... the bits I want!!
Try this function
function strip($url){
$info = parse_url($url);
$slash = (explode('/',$info['path']));
$sub = $slash[count($slash)-2];
$file = basename($url)==$sub ? "" : basename($url);
return "/".$sub."/".$file;
}
calling it by
echo strip('file:///C:/Bitnami/wampstack-5.5.30-0/apache2/htdocs/directory/subdirectory/story.html');
will result in
/subdirectory/story.html
I'm in the process of creating an experiment for a psychology researcher, there are various tasks involved which the participant has to complete. I have been asked to randomise the order of the folders, but keep the order of files inside the directories the same.
I have looked at using glob() but I think I'm implementing it wrong.
My directory looks like this:
Clock
>>Task 1/Files.>>Task 2/Files.>>Task 3/Files.
At the moment I have this:
<?php
function random_folders($dir = 'Clock')
{
$folder = glob($dir. '/Task.*');
$folderRand = array_rand($folder);
return $folder[$folderRand];
}
echo random_folders();
?>
I've tried googling and using stackoverflow to search for a solution but I can't seem to find one, any help will be greatly appreciated.
Edit
I should mention that I'm using HTML5, JavaScript, PHP and MySQL to create the website, if that's relevant.
Thanks.
Your glob() is a little off. You don't want the . before the *. Then use shuffle() to shuffle them:
function random_folders($dir = 'Clock')
{
$folder = glob($dir. '/Task*');
shuffle($folder);
// Returns the randomized array of folders
return $folder;
}
$random_folders = random_folders();
// List them and their contents:
foreach ($random_folders as $rf) {
echo "Folder: $rf\n";
// List files in ascending order
$files = scandir($rf, SCANDIR_SORT_ASCENDING);
foreach ($files as $f) {
if ($file !== "." && $file !== "..") {
echo $file . "\n";
}
}
I am trying to make an HTML5 slideshow system that implements PHP. My idea begins with making a system that detects the images in a folder, and puts them in an array, which the jquery will then be able to access for implementation in the slideshow. Firstly I have a php file that will detect the names of every file in the folder, and output them as plain text.
How, instead of outputting as plain text, can i make the PHP transfer the file names to a numerical array, which can be used with the jquery that will then accompany it?
I intend to use jquery to access the numerical array that is then made. How is this done? Unless it is not possible to do, and so how else can it be done?
The goal is to be able to put files in a folder, and for the scripting to dynamically recognize the presence of files, and incorporate them in a slideshow. This slideshow will then be output to a screen display which will be used in a waiting area, showcasing our school with a slideshow of images about the school.
Here is the code that I have so far:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
echo "filename: " . $file . "<br />";
}
closedir($dir);
?>
At this point I do not know how to make PHP "talk" with Javascript. I hope that there is some simple method for this, what I think I'm going for is AJAX, but I have no idea how this works.
The answer here is to use JSON, a subset of Javascript supported by many languages that allows you to (amongst many other things) very easily pass structured data into Javascript from external sources. PHP has a function json_encode() which allows you convert PHP data structures - usually arrays or objects - into a format the Javascript can easily read. jQuery also has built-in support for JSON.
<?php
// An array of the image file names
$images = array();
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$images[] = $file;
}
closedir($dir);
echo json_encode($images);
?>
Now, in jQuery you can do this:
$.getJSON('http://url/of/your/script.php', function(images) {
// In here the variable "images" is an array identical to the one you constructed with PHP
});
Yes you can use ajax to fetch the image filenames as an array by changing you php code like follows
<?php
//Open images directory
$dir = opendir("images");
$images = array();
//List files in images directory
while (($file = readdir($dir)) !== false)
{
//echo "filename: " . $file . "<br />";
$images[] = $files;
}
closedir($dir);
echo json_encode($images);
?>
then use $.getJSON o fetch that list
$.getJSON('path_to_above_php_file', function(images) {
//all your files are in images array, you can loop through it to find individual files
});
You could have an array with all your pictures then convert this array to JSON.
There are a few ways to do this, a quick and easy way is to do:
your php:
$dir = opendir("images");
$store = array();
while (($file = readdir($dir)) !== false)
{
$store[] = $file;
}
closedir($dir);
Now you have an array of all files (i might add that you may want to validate the file is an image!). I like to just dump them into JS as a json string as it saves me messing around. so:
echo "<script> var allimages = jQuery.parseJSON('".addslashes(json_encode($store))."'); </script>";
Now if you console.log() the allimages variable you will see you have all your images within that so you can use "$.each" or similar if you wish.
Rather than simply storing the name of the images, why not write the images themselves to your document? So something like:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$files[] = YOUR_URL_PATH.$file;
}
closedir($dir);
?>
...
<div id="slideshow">
<?php
foreach($files as $img)
echo '<img class="slide" src="'.$img.'" />';
?>
</div>
...
<script type="text/javascript">
$(document).ready(function()
{
alert($(".slide").length+" slides detected");
});
</script>
That way, instead of relying on PHP to define your jQuery, you're using PHP to define the elements jQuery needs in order to function properly.
UPDATE:
If your PHP and Javascript exist on the same page, and you still want to be able to set a Javascript array using PHP, then I think this is what you're looking for:
<?php
//Open images directory
$dir = opendir("images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
$files[] = YOUR_URL_PATH.$file;
}
closedir($dir);
?>
...
<script type="text/javascript">
$(document).ready(function()
{
var fileArr = [<?php echo implode(',',$files); ?>];
});
</script>
This requires that your Javascript resides on the same page as your PHP that defines the file array. If your Javascript is intended to be referenced externally, then your best bet is to use JSON array as mentioned by many of the other answers here.
I would say JSON suits your situation well. Just create PHP file that prints (echo) the JSON object containing the list of your files. You can use json_encode() to create the JSON object. On your browser side you can make an AJAX request (or simply use jQuery.getJSON()) and set the data type to JSON and you should be good to go:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
Here you can read about using JSON in PHP.
SPL library has function to handler directories
From PHP site:
Usage example:
To see all the files:
<?php
$ite=new RecursiveDirectoryIterator($_POST['path']);
$files = array();
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
array_push($files, $filename);
}
echo json_encode($files);
?>
Now with jquery.post() you can retrieve the list of files in folder.
I need to get all the folders and files from a folder recursively in alphabetical order (folders first, files after)
Is there an implemented PHP function which caters for this?
I have this function:
function dir_tree($dir) {
$path = '';
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..' && $dircont[$i] !== '.svn') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
I have sorted the array and printed it like so:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
What I need is to know when a new sub directory is found, so I can add some spaces to print it in a directory like structure instead of just a list.
Any help?
Many thanks
Look at the RecursiveDirectoryIterator.
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure though if it returns the files in alphabetical order.
Edit:
As you say it does not, I think the only way is to sort them yourself.
I would loop through each directory and put directories and files in a seperate arrays, and then sort them, and then recurse in the directories.
I found a link which helped me a lot in what I was trying to achieve:
http://snippets.dzone.com/posts/show/1917
This might help someone else, it creates a list with folders first, files after. When you click on a subfolder, it submits and another page with the folders and files in the partent folder is generated.
The following code loads all .php files found in the specified folder (defined separately). Is there a way to put this into an array to simplify the code?
Only a couple of variables change but essentially the code repeats several times.
// The General Files
$the_general = opendir(FRAMEWORK_GENERAL);
while (($the_general_files = readdir($the_general)) !== false) {
if(strpos($the_general_files,'.php')) {
include_once(FRAMEWORK_GENERAL . $the_general_files);
}
}
closedir($the_general);
// The Plugin Files
$the_plugins = opendir(FRAMEWORK_PLUGINS);
while (($the_plugins_files = readdir($the_plugins)) !== false) {
if(strpos($the_plugins_files,'.php')) {
include_once(FRAMEWORK_PLUGINS . $the_plugins_files);
}
}
closedir($the_plugins);
There are several more sections which call different folders.
Any help is greatly appreciated.
Cheers,
James
I nicer way to do this would to use glob(). And make it into a function.
function includeAllInDirectory($directory)
{
if (!is_dir($directory)) {
return false;
}
// Make sure to add a trailing slash
$directory = rtrim($directory, '/\\') . '/';
foreach (glob("{$directory}*.php") as $filename) {
require_once($directory . $filename);
}
return true;
}
This is fairly simple. See arrays and foreach.
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS, );
foreach ($dirs as $dir) {
$d = opendir($dir);
while (($file = readdir($d)) !== false) {
if(strpos($file,'.php')) {
include_once($dir . $file);
}
}
closedir($d);
}
A better idea might be lazy loading via __autoload or spl_autoload_register, including all the .php files in a directory might seem like a good idea now, but not when your codebase gets bigger.
Your code should be layed out in an easy to understand heirarchy, rather than putting them all in one directory so they can be included easily. Also, if you dont need all of the code in the files in every request you are wasting resources.
Check http://php.net/manual/en/language.oop5.autoload.php for an easy example.
This can be done pretty tightly:
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS);
foreach($dirs as $dir) {
if (!is_dir($dir)) { continue; }
foreach (glob("$dir/*.php") as $filename) {
include($filename);
}
}
Put that in a function where $dirs comes in as a param and use freely.