How can I foreach all files in a dictionary? - php

I am working on a method of saving CPU by loading all my resources into ram before starting the my game server, rather then loading it into RAM on the fly.
So I save all my packet data in a dictionary. The files have random names. How can I foreach every file in the dictionary? I need something like this:
$path = //path to dictionary
foreach(//get dictionary files as $packet){
$filename = //getfile name
if(!isset($this->chunkCache[$filename])){
$this->chunkCache[$filename] = $packet;
}
}
Is this possible?

Check this out : readdir()
This bit of code should list all entries in a certain directory:
$path = //path to dictionary
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}

Related

PHP: Fastest way to get huge number of directories including subdirectories into db

How to get all directories including subdirectories separately and save in database in PHP? I am using MySQL and PHP 5.4 and nginx.
Right now I have the following function which uses readdir and does what I want just fine.
protected function getSubDirsRecursively($dir)
{
$result = array();
$dir = rtrim($dir, '\\/');
if (is_dir($dir)) {
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
$currentPath = $dir . DIRECTORY_SEPARATOR . $file;
if ($file !== '.' && $file !== '..' && is_dir($currentPath)) {
$result[] = $currentPath;
$result = array_merge($result, $this->getSubDirsRecursively($currentPath));
}
}
closedir($dh);
}
return $result;
}
However, the problem is when user has huge number of directories (e.g. 1m) and PHP execution time limit which he cannot change due to shared hosting.
Is it possible to do this with ajax requests and collect directories in portions?

List files with php

I'd like to know how to listing files with php?
What I try to do is it was sailing along this list of files in order that when it chooses one of them (.html) it me appears in the iframe that I have in my (index.php). Can someone help me?
use the below code:
$path = 'path to the directory';
$files = scandir($path);
I hope this helps you.
You can use readdir link to readdir
Look at this exemple:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}

How can I fetch pictures from a directory into an array?

I am looking for a php function to grab images from a directory and load them into an array so that I can output them automatically
For example instead of creating such an array on my own:
$pics = array('../photos/t.png','../photos/t1.png','../photos/t2.png','../photos/t3.png','../photos/t4.png');
It would be much easier if I had a function that fetches all the (.jpg, .png, .jpeg, .bmp) extension files and load them into an array
Your ideas will be very helpful.
You could try something like this:
<?php
$directory = "/var/site/images";
$images = array();
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$image = realpath("{$directory}/{$entry}");
array_push($images, $image);
}
}
closedir($handle);
}
?>
This will loop through all the files in your images directory and store their path off to the images array. You could even use a substring function to identify images as you loop through (if you have other filetypes in your images folder) and only add the allowed file types to the array.
This is not all my code, some was borrowed from the PHP manual on readdir().

Read and delete a text file in php

I am making a simple php script which just read a text file from server and delete it after showing on web.Script works well but it reads another file and delete another. It should delete the same file it reads. Any help please. Here is my code:
<?php
$mystr = '';
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$info = pathinfo($entry);
if ($info["extension"] == "txt") {
$mystr = $entry;
}
}
}
closedir($handle);
}
if (empty($mystr)) {
}else{
$contents = file_get_contents($mystr);
echo $contents;
unlink($mystr);
}
?>
Update
I dont know the file name, So in a loop I get the file name. I want to read any .txt file in the folder. This I read file one by one and at the same time delete it.
Your script is just this :
foreach(glob('/path/to/dir/*.txt') as $file)
{
readfile($file);
unlink($file);
}
See readfile() and glob() manual pages.

is_dir does not recognize folders

I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle

Categories