Loading images from a directory into an array with php - php

So I've killed an entire day trying to do something that would take someone who actually knows how to write php less than 2mins. Frustrating, but I learn by doing and trying to figure things out.
I'll feel like a failure for not getting this, but 8hrs and counting (yeah I know lame) is enough.
Can somebody tell me what's wrong with this equation...
$dir = '../folder';
$images_array = glob($dir.'*.jpg');
$values['options'] = array( '<img src="$images_array"/>');
It's probably obvious, but all I need is for the images in mysite.com/folder to be loaded into the $values['options'] array.
If I simply state the path to a single image in then the image is displayed (obviously because it's not reliant on anything else.)
Thanks.
#hellcode
Sorry about the mess in the 'comment' below your response. Unfortunately I couldn't get this to work? Maybe I need to provide more context.
The images in the folder are going to be used as checkbox items in a form. This was my original code (not working):
add_filter('frm_setup_new_fields_vars', 'frm_set_checked', 20, 2);
function frm_set_checked($values, $field){
if($field->id == 187){
$dir = '../folder';
$images_array = glob($dir.'*.jpg');
$values['options'] = array( '<img src="$images_array"/>');
$values['use_key'] = true;
}
return $values;
}
I added your code like so:
add_filter('frm_setup_new_fields_vars', 'frm_set_checked', 20, 2);
function frm_set_checked($values, $field){
if($field->id == 187){
$dir = '../folder';
$images_array = glob($dir.'*.jpg');
$values['options'] = array();
foreach($images_array as $image) {
$values['options'][] = '<img src="'.$image.'"/>';
}
$values['use_key'] = true;
}
return $values;
}
But it didn't pull the files in unfortunately :(

Try:
$dir = '../folder';
$images_array = glob($dir.'*.jpg');
$values['options'] = array();
foreach($images_array as $image) {
$values['options'][] = '<img src="'.$image.'"/>';
}

Well, one problem may be that the glob() function uses the current directory, which can be anything, unless you use the chdir() function.
One thing that is definitely a problem is that you are using glob()'s return value, $images_array, as a string. Because it is an array that will not work.
Here is something that should work.
// Allowed image formats (also known as a "whitelist")
$allowedFormats = ['jpg', 'jpeg', 'gif', 'png'];
// Array for holding any found images
$foundImages = [];
// Get the real path from the relative path
$path = realpath('../folder');
if ($path === false) {
die('The path does not exist!');
}
// Open a folder handle
$folder = dir($path);
// Read what is in the folder
while (($item = $folder->read()) !== false) {
// .. is the parent folder, . is the current folder
if ($item === '..' or $item === '.') {
continue;
}
// Find the last dot in the filename
// If it was not found then not image file
$lastDot = strrpos($item, '.');
if ($lastDot === false) {
continue;
}
// Get the filetype and make sure it is
// an allowed format
$filetype = substr($item, $lastDot);
if ( ! in_array($filetype, $allowedFormats)) {
continue;
}
// Okay, looks like an image!
$foundImages[] = $item;
}
// Close the folder handle
$folder->close();

Related

How to calculate entire directory size with FTP access using PHP

I have a number of different hosting accounts set up for clients and need to calculate the amount of storage space being used on each account, which would update regularly.
I have a database set up to record each clients storage usage.
I attempted this first using a PHP file on each account, run by a Cron Job. If run manually by myself, it would output the correct filesize and update the correct size to the database, although when run from the Cron Job, it would output 0.
I then attempted to run this file from a Cron Job from the main account but figured this wouldn't actually work as my hosting would block files from another server and I would end up with the same result as before.
I am now playing around with FTP access to each account from a Cron Job from the main account which looks something like below, the only problem is I don't know how to calculate directory size rather than single file sizes using FTP access, and don't know how to reiterate this way? Hoping somebody might be able to help here before I end up going around in circles?
I will also add the previous first attempt too.
$ftp_conn = ftp_connect($ftp_host, 21, 420) or die("Could not connect to server");
$ftp_login = ftp_login($ftp_conn, $ftp_username, 'mypassword');
$total_size = 0;
$contents = ftp_nlist($ftp_conn, ".");
// output $contents
foreach($contents as $folder){
while($search == true){
if($folder == '..' || $folder == '.'){
} else {
$file = $folder;
$res = ftp_size($ftp_conn, $file);
if ($res != -1) {
$total_size = $total_size + $res;
} else {
$total_size = $total_size;
}
}
}
}
ftp_close($ftp_conn);
This doesn't work as it doesn't calculate folder sizes and I don't know how to open the reiterate using this method?
This second script did work but would only work if opened manually, and return 0 if run by the cron job.
class Directory_Calculator {
function calculate_whole_directory($directory)
{
if ($handle = opendir($directory))
{
$size = 0;
$folders = 0;
$files = 0;
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
if(is_dir($directory.$file))
{
$array = $this->calculate_whole_directory($directory.$file.'/');
$size += $array['size'];
$files += $array['files'];
$folders += $array['folders'];
}
else
{
$size += filesize($directory.$file);
$files++;
}
}
}
closedir($handle);
}
$folders++;
return array('size' => $size, 'files' => $files, 'folders' => $folders);
}
}
/* Path to Directory - IMPORTANT: with '/' at the end */
$directory = '../public_html/';
// return an array with: size, total files & folders
$array = $directory_size->size($directory);
$size_of_site = $array['size'];
echo $size_of_site;
Please bare in mind that I am currently testing and none of the MySQLi or PHP scripts are secure yet.
If your server supports MLSD command and you have PHP 7.2 or newer, you can use ftp_mlsd function:
function calculate_whole_directory($ftp_conn, $directory)
{
$files = ftp_mlsd($ftp_conn, $directory) or die("Cannot list $directory");
$result = 0;
foreach ($files as $file)
{
if (($file["type"] == "cdir") || ($file["type"] == "pdir"))
{
$size = 0;
}
else if ($file["type"] == "dir")
{
$size = calculate_whole_directory($ftp_conn, $directory."/".$file["name"]);
}
else
{
$size = intval($file["size"]);
}
$result += $size;
}
return $result;
}
If you do not have PHP 7.2, you can try to implement the MLSD command on your own. For a start, see user comment of the ftp_rawlist command:
https://www.php.net/manual/en/function.ftp-rawlist.php#101071
If you cannot use MLSD, you will particularly have problems telling if an entry is a file or folder. While you can use the ftp_size trick, as you do, calling ftp_size for each entry can take ages.
But if you need to work against one specific FTP server only, you can use ftp_rawlist to retrieve a file listing in a platform-specific format and parse that.
The following code assumes a common *nix format.
function calculate_whole_directory($ftp_conn, $directory)
{
$lines = ftp_rawlist($ftp_conn, $directory) or die("Cannot list $directory");
$result = 0;
foreach ($lines as $line)
{
$tokens = preg_split("/\s+/", $line, 9);
$name = $tokens[8];
if ($tokens[0][0] === 'd')
{
$size = calculate_whole_directory($ftp_conn, "$directory/$name");
}
else
{
$size = intval($tokens[4]);
}
$result += $size;
}
return $result;
}
Based on PHP FTP recursive directory listing.
Regarding cron: I'd guess that the cron does not start your script with a correct working directory, so you calculate a size of a non-existing directory.
Use an absolute path here:
$directory = '../public_html/';
Though you better add some error checking so that you can see yourself what goes wrong.

php - Get the last modified dir

A little stuck on this and hoping for some help. I'm trying to get the last modified dir from a path in a string. I know there is a function called "is_dir" and I've done some research but can't seem to get anything to work.
I don't have any code i'm sorry.
<?php
$path = '../../images/';
// echo out the last modified dir from inside the "images" folder
?>
For example: The path variable above has 5 sub folders inside the "images" dir currently right now. I want to echo out "sub5" - which is the last modified folder.
You can use scandir() instead of is_dir() function to do it.
Here is an example.
function GetFilesAndFolder($Directory) {
/*Which file want to be escaped, Just add to this array*/
$EscapedFiles = [
'.',
'..'
];
$FilesAndFolders = [];
/*Scan Files and Directory*/
$FilesAndDirectoryList = scandir($Directory);
foreach ($FilesAndDirectoryList as $SingleFile) {
if (in_array($SingleFile, $EscapedFiles)){
continue;
}
/*Store the Files with Modification Time to an Array*/
$FilesAndFolders[$SingleFile] = filemtime($Directory . '/' . $SingleFile);
}
/*Sort the result as your needs*/
arsort($FilesAndFolders);
$FilesAndFolders = array_keys($FilesAndFolders);
return ($FilesAndFolders) ? $FilesAndFolders : false;
}
$data = GetFilesAndFolder('../../images/');
var_dump($data);
From above example the last modified Files or Folders will show as Ascending order.
You can also separate your files and folder by checking is_dir() function and store the result in 2 different arrays like $FilesArray=[] and $FolderArray=[].
Details about filemtime() scandir() arsort()
Here's one way you can accomplish this:
<?php
// Get an array of all files in the current directory.
// Edit to use whatever location you need
$dir = scandir(__DIR__);
$newest_file = null;
$mdate = null;
// Loop over files in directory and if it is a subdirectory and
// its modified time is greater than $mdate, set that as the current
// file.
foreach ($dir as $file) {
// Skip current directory and parent directory
if ($file == '.' || $file == '..') {
continue;
}
if (is_dir(__DIR__.'/'.$file)) {
if (filemtime(__DIR__.'/'.$file) > $mdate) {
$newest_file = __DIR__.'/'.$file;
$mdate = filemtime(__DIR__.'/'.$file);
}
}
}
echo $newest_file;
This will work too just like the other answers. Thanks everyone for the help!
<?php
// get the last created/modified directory
$path = "images/";
$latest_ctime = 0;
$latest_dir = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if(is_dir($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_dir = $entry;
}
} //end loop
echo $latest_dir;
?>

Is there an efficient one-liner to grab the first file in a directory?

I want to grab the first file in a directory, without touching/grabbing all the other files. The filename is unknown.
One very short way could be this, using glob:
$file = array_slice(glob('/directory/*.jpg'), 0, 1);
But if there are a lot of files in that directory, there will be some overhead.
Other ways are answers to this question - but all involve a loop and are also longer then the glob example:
PHP: How can I grab a single file from a directory without scanning entire directory?
Is there a very short and efficient way to solve this?
Probably not totally efficient, but if you only want the FIRST jpg that appears, then
$dh = opendir('directory/');
while($filename = readdir($dh)) {
if (substr($filename, -4) == '.jpg')) {
break;
}
}
Well this is not totally a one-liner, but it is a way to go I believe:
$result = null;
foreach(new FilesystemIterator('directory/') as $file)
{
if($file->isFile() && $file->getExtension() == 'jpg') {
$result = $file->getPathname();
break;
}
}
but why don't you wrap it in a function and use it like get_first_file('directory/') ? It will be a nice and short!
This function will get the first filename of any type.
function get_first_filename ($dir) {
$d = dir($dir);
while ($f = $d->read()){
if (is_file($dir . '/' . $f)) {
$d->close();
return $f;
}
}
}

Iterate through a folder?

I'm looking for the best way to iterate through a folder and put all the file names inside it into an array and in another one the count of the files.
I have found glob() as a good solution, but also a lot of alternatives for it on php.net. I'm not sure which I should use, so I'm asking here. If you're wondering for what I want to use it, it's to get all the .sql files inside a backup folder and display them as <li>thesqlfile.sql</li> and have a count of all of them too.
So I thought of having two arrays, one with their names, and one with the count of all of them. So in this case which method would be best fit to iterate ?
Method I:
<?php
$files = array();
foreach (glob("backup/*.txt") as $filename) {
$files[]= $filename;
}
$count = sizeof($files);
?>
Method II:
function getfoldercontents($dir, $file_display = array(), $exclusions = array()) {
if(!file_exists($dir)){
return FALSE;
}
$dir_contents = scandir($dir);
$contents = array();
foreach ($dir_contents as $file){
$file_parts = explode('.', $file);
$file_type = strtolower(end($file_parts));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) && !in_array($file, $exclusions)) {
$contents[] = $dir. '/'. $file;
}
}
return $contents;
}
Since glob() already returns an array, you don't need to iterate over it to append to an array at all. Your first method is a little over-complicated. This accomplishes the same thing:
// Just assign the array output of glob() to a variable
$files = glob("backup/*.txt");
$num_files = count($files);
I would say the second is probably better in terms of file-control (through $file_display and $file_exclude), but maybe you should add a check to ensure the current file is not a directory named something.typeyouwishtodisplay

PHP, reading a folder - listing all items with checkboxes and delete them?

i wonder if theres a tutorial out there or you could give me a quick and simple approach how i could do the following task.
i have a folder on my server. i want to build a kind of cms where i can easily delete files from a folder. i know how to upload them, i already found a tutorial.
i think of simply running through all files, creating a list of them with a checkbox in front, selecting the checkbox and pressing a DELETE button.
is this a rather difficult task to get done? do you maybe kno any tutorial or something.
thank you very much!
Start with
List all files
<?php
// file_array() by Jamon Holmgren. Exclude files by putting them in the $exclude
// string separated by pipes. Returns an array with filenames as strings.
function file_array($path, $exclude = ".|..", $recursive = false) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
if($recursive) $result[] = file_array($path, $exclude, true);
} else {
$result[] = $filename;
}
}
}
return $result;
}
?>
then create hyperlinks to the above files to a delete function like;
unlink('filename.jpg');

Categories