PHP Array Blocklist - php

I've created this code to cycle through the folders in the current directory and echo out a link to the folder, it all works fine. How would I go about using the $blacklist array as an array to hold the directory names of directories I dont want to show?
$blacklist = array('dropdown');
$results = array();
$dir = opendir("./");
while($file = readdir($dir)) {
if($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($dir);
foreach($results as $file) {
if($blocked != true) {
$fileUrl = $file;
$fileExplodedName = explode("_", $file);
$fileName = "";
$fileNameCount = count($fileExplodedName);
echo "<a href='".$fileUrl."'>";
$i = 1;
foreach($fileExplodedName as $name) {
$fileName .= $name." ";
}
echo trim($fileName);
echo "</a><br/>";
}
}

array_diff is the best tool for this job -- it's the shortest to write, very clear to read, and I would expect also the fastest.
$filesToShow = array_diff($results, $blacklist);
foreach($filesToShow as $file) {
// display the file
}

Use in_array for this.
$blocked = in_array($file, $blacklist);
Note that this is rather expensive. The runtime complexity of in_array is O(n) so don't make a large blacklist. This is actually faster, but with more "clumsy" code:
$blacklist = array('dropdown' => true);
/* ... */
$blocked = isset($blacklist[$file]);
The runtime complexity of the block check is then reduced to O(1) since the array (hashmap) is constant time on key lookup.

Related

Sorting files in an array by the ocurrences of a word in it, php

I'm making a search bar that searches files in a directory that have the word searched, then I want it to be added to an array by order of which one has more times the word asked to the one with less.
I'm working on PHP this is my code:
<?php
if(isset($_POST['busqueda'])){
$variable = utf8_encode($_POST['busqueda']);
}
$Array1 = array();
foreach(glob("*.txt") as $filename) {
$contents = file_get_contents($filename);
if (strpos($contents, $variable)){
$Array1[] = $filename;
}
}
I don't know how to do it exactly, I think that I should use substr_count(file_get_contents($Array1[$position1])) or something like that but I'm unsure how to make the sorting system, can someone help me!
print_r($Array1);
for($var1=0; $var1<sizeof($Array1); $var1++){
echo "times on the file: ".$Array1[$var1]."<br>";
echo substr_count(file_get_contents($Array1[$var1]));
}
?>
You can use the substr_count itself. Then you need to use arsort to sort the array.
$Array1 = array();
foreach (glob("*.txt") as $filename) {
$contents = file_get_contents($filename);
if ( ($count = substr_count($contents, $variable)) ) {
$Array1[$filename] = $count;
}
}
arsort($Array1) ;
print_r($Array1);
foreach ($Array1 as $file => $count) {
echo "times on the file($file): $count <br>";
}
Bash (available on at least Linux and Mac operating systems) makes it extremely easy to accomplish your task, because you can call commands through PHP's exec function, assuming it is not disabled by an administrator. If you're on Windows, then this will probably not work, but most people are using Linux for a production environment, so I thought this answer would be worthy of posting.
The following function is taken from CodeIgniter's file helper and only serves to fetch an array of filenames from a specified directory. If you don't need a function like this because you are getting your filenames from somewhere else, just note that this function can include the full file path for each file, and that's why I used it.
function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE)
{
static $_filedata = array();
if ($fp = #opendir($source_dir))
{
// reset the array and make sure $source_dir has a trailing slash on the initial call
if ($_recursion === FALSE)
{
$_filedata = array();
$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}
while (FALSE !== ($file = readdir($fp)))
{
if (#is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
{
get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);
}
elseif (strncmp($file, '.', 1) !== 0)
{
$_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;
}
}
return $_filedata;
}
else
{
return FALSE;
}
}
Now that I can fetch an array of filenames easily, I'd do this:
/**
* Here you can see that I am searching
* all of the files in the script-library
* directory for the word "the"
*/
$searchWord = 'the';
$directory = '/var/www/htdocs/script-library';
$filenames = get_filenames(
$directory,
TRUE
);
foreach( $filenames as $file )
{
$counts[$file] = exec("tr ' ' '\n' < " . $file . " | grep " . $searchWord . " | wc -l");
}
arsort( $counts );
echo '<pre>';
print_r( $counts );
echo '</pre>';
For a good explaination of how that works, see this: https://unix.stackexchange.com/questions/2244/how-do-i-count-the-number-of-occurrences-of-a-word-in-a-text-file-with-the-comma
I tested this code locally and it works great.

Learning PHP. Have recursive directory loop issue

So, I'm familiar with Javascript, HTML, and Python. I have never learned PHP, and at the moment, I'm banging my head against my desk trying to figure out what (to me) seems to be such a simple thing.
I have a folder, with other folders, that contain images.
At the moment, I'm literally just trying to get a list of the folders as links. I get kind of there, but then my output is always reversed! Folder01, Folder02 comes out as Folder02, Folder01. I can't fricken' sort my output. I've been searching constantly trying to figure this out but nothing is working for me.
<?php
function listAlbums(){
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo $entry . "<br/>";
}
}
closedir($handle);
}
}
?>
This outputs: Folder02, Folder01. I need it the other way around. I've tried asort, array_reverse, etc. but I must not be using them properly. This is killing me. I never had to even thin about this in Python, or Javascript, unless I actually wanted to have an ascending list...
Try one of these, one is recursive, one is not:
// Recursive
function listAlbums($path = './photos/')
{
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object) {
ob_start();
echo rtrim($object,".");
$data = ob_get_contents();
ob_end_clean();
$arr[] = $data;
}
return array_unique($arr);
}
// Non-recursive
function getAlbums($path = './photos/')
{
$objects = dir($path);
while (false !== ($entry = $objects->read())) {
if($entry !== '.' && $entry !== '..')
$arr[] = $path.$entry;
}
$objects->close();
return $arr;
}
// I would use __DIR__, but not necessary
$arr = listAlbums();
$arr2 = getAlbums();
// Reverse arrays by key
krsort($arr);
krsort($arr2);
// Show arrays
print_r($arr);
print_r($arr2);
I try your code and make simple changes and I am able to do what you want to get.
Here is my code ( copy of your code + Modify ) :
function listAlbums() {
$files = array();
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
//echo $entry . "<br/>";
$files[] = $entry;
}
}
closedir($handle);
}
// Sort your folder in ascending order
sort($files);
// Sort your folder in descending order [ code commented ]
//rsort($files);
// Check your photos folder has folder or not
if( !empty( $files ) ) {
// Show Your Folders
foreach ($files as $key => $folderName ) {
echo $folderName . "<br/>";
}
} else {
echo 'You have no folder yet in photos directory';
}
}
My Changes:
First store your all folders in the photos directory in an array variable
Secondly sort this array whatever order you want.
Finally show your folders (And your work will be solved)
You can know more about this from sort-and-display-directory-list-alphabetically-using-opendir-in-php
Thanks
Ok, this is the best result i've gotten all night. This does 99% of what I need. But I still can't figure out this damn sort issue. This code will go through a list of directories, and create lightbox galleries out of the images in each folder. However, the first image is always the last one in the array, and I can't figure out how the heck to get it to sort normally! Check line 16 to see where I talking about.
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
foreach (new DirectoryIterator($folderItem) as $fileInfo) {
if($fileInfo->isDot()) continue;
$files = $folderItem."/".$fileInfo->getFilename();
if ($count == 0){ //This is where my issues start. This file ends up being the last one in the list. I need it to be the first.
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
?>
Whew! Ok, I got everything working. DirectoryIterator was pissing me off with its random print order. So I fell back to just glob and scandir. Those seem to print out a list "logically". To summarize, this bit of php will grab folders of images and turn each folder into its own lightbox gallery. Each gallery shows up as a hyperlink that triggers the lightbox gallery. I'm pretty happy with it!
So here's my final code:
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
$scanDir = scandir($folderItem);
foreach($scanDir as $file){
if ($file === '.' || $file === '..') continue;
$filePath = $folderItem."/".$file;
if ($count == 0){
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
Special thanks to Rasclatt for bearing with me through all of this and offering up a lot of hand-holding and help. I really appreciate it!

How to get list of files as array, where key is the same as value?

I could use some help with this. I have to get list of files from one directory, and return them as array, but key needs to be the same as value, so output would be looking like this:
array(
'file1.png' => 'file1.png',
'file2.png' => 'file2.png',
'file3.png' => 'file3.png'
)
I found this code:
function images($directory) {
// create an array to hold directory list
$results = array();
// create a handler for the directory
$handler = opendir($directory);
// open directory and walk through the filenames
while ($file = readdir($handler)) {
// if file isn't this directory or its parent, add it to the results
if ($file != "." && $file != "..")
{
$results[] = $file;
}
}
// tidy up: close the handler
closedir($handler);
// done!
return $results;
}
It's working fine, but it returns regular array.
Can someone help me with this?
Also small note at the end, I need to list only image files (png,gif,jpeg).
Change your following line
$results[] = $file;
To
$results[$file] = $file;
To limit file extension do as below
$ext = pathinfo($file, PATHINFO_EXTENSION);
$allowed_files = array('png','gif');
if(in_array($ext,$allowed_files)){
$results[$file] = $file;
}
Something like this should to the work
$image_array = [];
foreach ($images as $image_key => $image_name) {
if ($image_key == $image_name) {
$image_array[] = $image_name;
}
return $image_array;
}
Why not using glob and array_combine ?
function images($directory) {
$files = glob("{$directory}/*.png");
return array_combine($files, $files);
}
glob() get files on your directory according to a standard pattern ( such as *.png )
array_combine() creates an associative array using an array of keys and an array of values
now do this on my script
$scan=scandir("your image directory");
$c=count($scan);
echo "<h3>found $c image.</h3>";
for($i=0; $i<=$c; $i++):
if(substr($scan[$i],-3)!=='png') continue;
echo "<img onClick=\"javascript:select('$scan[$i]');\" src='yourdirectory/$scan[$i]' />";
endfor;
this code only list png images from your directory.

PHP scandir results: sort by folder-file, then alphabetically

PHP manual for scandir: By default, the sorted order is alphabetical in ascending order.
I'm building a file browser (in Windows), so I want the addresses to be returned sorted by folder/file, then alphabetically in those subsets.
Example: Right now, I scan and output
Aardvark.txt
BarDir
BazDir
Dante.pdf
FooDir
and I want
BarDir
BazDir
FooDir
Aardvark.txt
Dante.pdf
Other than a usort and is_dir() solution (which I can figure out myself), is there a quick and efficient way to do this?
The ninja who wrote this comment is on the right track - is that the best way?
Does this give you what you want?
function readDir($path) {
// Make sure we have a trailing slash and asterix
$path = rtrim($path, '/') . '/*';
$dirs = glob($path, GLOB_ONLYDIR);
$files = glob($path);
return array_unique(array_merge($dirs, $files));
}
$path = '/path/to/dir/';
readDir($path);
Note that you can't glob('*.*') for files because it picks up folders named like.this.
Please try this. A simple function to sort the PHP scandir results by files and folders (directories):
function sort_dir_files($dir)
{
$sortedData = array();
foreach(scandir($dir) as $file)
{
if(is_file($dir.'/'.$file))
array_push($sortedData, $file);
else
array_unshift($sortedData, $file);
}
return $sortedData;
}
I'm late to the party but I like to offer my solution with readdir() rather than with glob(). What I was missing from the solution is a recursive version of your solution. But with readdir it's faster than with glob.
So with glob it would look like this:
function myglobdir($path, $level = 0) {
$dirs = glob($path.'/*', GLOB_ONLYDIR);
$files = glob($path.'/*');
$all2 = array_unique(array_merge($dirs, $files));
$filter = array($path.'/Thumbs.db');
$all = array_diff($all2,$filter);
foreach ($all as $target){
echo "$target<br />";
if(is_dir("$target")){
myglobdir($target, ($level+1));
}
}
}
And this one is with readdir but has basically the same output:
function myreaddir($target, $level = 0){
$ignore = array("cgi-bin", ".", "..", "Thumbs.db");
$dirs = array();
$files = array();
if(is_dir($target)){
if($dir = opendir($target)){
while (($file = readdir($dir)) !== false){
if(!in_array($file, $ignore)){
if(is_dir("$target/$file")){
array_push($dirs, "$target/$file");
}
else{
array_push($files, "$target/$file");
}
}
}
//Sort
sort($dirs);
sort($files);
$all = array_unique(array_merge($dirs, $files));
foreach ($all as $value){
echo "$value<br />";
if(is_dir($value)){
myreaddir($value, ($level+1));
}
}
}
closedir($dir);
}
}
I hope someone might find this useful.

dynamic formation of array with incremental depth in PHP

I want to use a function to recursively scan a folder, and assign the contents of each scan to an array.
It's simple enough to recurse through each successive index in the array using either next() or foreach - but how to dynamically add a layer of depth to the array (without hard coding it into the function) is giving me problems. Here's some pseudo:
function myScanner($start){
static $files = array();
$files = scandir($start);
//do some filtering here to omit unwanted types
$next = next($files);
//recurse scan
//PROBLEM: how to increment position in array to store results
//$next_position = $files[][][].... ad infinitum
//myScanner($start.DIRECTORY_SEPARATOR.$next);
}
any ideas?
Try something like this:
// $array is a pointer to your array
// $start is a directory to start the scan
function myScanner($start, &$array){
// opening $start directory handle
$handle = opendir($start);
// now we try to read the directory contents
while (false !== ($file = readdir($handle))) {
// filtering . and .. "folders"
if ($file != "." && $file != "..") {
// a variable to test if this file is a directory
$dirtest = $start . DIRECTORY_SEPARATOR . $file;
// check it
if (is_dir($dirtest)) {
// if it is the directory then run the function again
// DIRECTORY_SEPARATOR here to not mix files and directories with the same name
myScanner($dirtest, $array[$file . DIRECTORY_SEPARATOR]);
} else {
// else we just add this file to an array
$array[$file] = '';
}
}
}
// closing directory handle
closedir($handle);
}
// test it
$mytree = array();
myScanner('/var/www', $mytree);
print "<pre>";
print_r($mytree);
print "</pre>";
Try to use this function (and edit it for your demands):
function getDirTree($dir,$p=true) {
$d = dir($dir);$x=array();
while (false !== ($r = $d->read())) {
if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
$x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
}
}
foreach ($x as $key => $value) {
if (is_dir($dir.$key."/")) {
$x[$key] = getDirTree($dir.$key."/",$p);
}
}
ksort($x);
return $x;
}
It returns sorted array of directories.

Categories