php sort folder by date created instead of name - php

Currently my script list all folders by their name.
Now I want to sort it by date they have created.
Index.php :
<?php
include("include.php");
include("header.php");
?>
<h1>Photo</h1>
<p class="breadcrumb">home > gallery</p>
<?php if(count($categories_array)<=0){?>
<p>There are no photo categories, create one or more categories before uploading photos</p>
<?php }
if(count($categories_array)>0){?>
<div>
<?php foreach($categories_array as $photo_category=>$photos_array){?>
<?php
$category_thumbnail = $gallery_url."/layout/pixel.gif";
if(file_exists('files/'.$photo_category.'/thumbnail.jpg')){
$category_thumbnail = $gallery_url.'/'.$photo_category.'/thumbnail.jpg';
}
$category_url = $gallery_url.'/'.$photo_category;
?>
<span class="category_thumbnail_span" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height+20;?>px;">
<a class="category_thumbnail_image" href="<?php echo $category_url;?>" style="width:<?php echo $settings_thumbnail_width;?>px; height:<?php echo $settings_thumbnail_height;?>px; background-image:url('<?php echo $gallery_url;?>/layout/lens_48x48.png');" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>">
<img src="<?php echo $category_thumbnail;?>" width="<?php echo $settings_thumbnail_width;?>" height="<?php echo $settings_thumbnail_height;?>" alt="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>" />
</a>
<a class="category_thumbnail_title" href="<?php echo $category_url;?>" title="<?php echo htmlentities(ucwords(str_replace('-', ' ', $photo_category)));?>">
<?php echo htmlentities(str_replace('-',' ', truncate_by_letters($photo_category, 16, '..')), ENT_QUOTES, "UTF-8");?> (<?php echo count($photos_array);?>)
</a>
</span>
<?php } ?>
</div>
include.php :
<?php
include("settings.php");
$page_load_start = microtime(true);
if (!isset($_SESSION)) {
session_start();
}
setlocale(LC_CTYPE, "en_US.UTF-8");
$gallery_domain = str_replace("www.", "", $_SERVER['HTTP_HOST']);
$gallery_url = dirname($_SERVER['SCRIPT_NAME']);
$gallery_url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $gallery_url);
error_reporting(E_ALL ^ E_NOTICE);
include("system_functions.php");
$is_admin = false;
if($_SESSION['session_admin'] == md5($_SESSION['session_secret'].$settings_secret)){
$is_admin = true;
}
$categories_array = array();
$timer_1 = microtime(true);
// loop over files directory and read the categories
$scandir_array = scandir('files');
foreach($scandir_array as $folder){
if(is_dir('files/'.$folder) and $folder!='.' and $folder!='..'){
// define this key in the array, it will be blank, store categories as keys
$categories_array[$folder] = array(filectime($folder));
// $total_photos_array[$folder] = 0;
$files_in_dir = scandir('files/'.$folder);
foreach($files_in_dir as $file){
if($file!='.' and $file!='..'){
// if file is not the category thumbnail (thumbnail.jpg) and not _thumb.jpg and not _small.jpg
if($file != "thumbnail.jpg" and substr($file, strlen($file)-10) != "_small.jpg" and substr($file, strlen($file)-10) != "_thumb.jpg"){
// $total_photos_array[$folder]++;
$base_file_name = substr($file, 0, strlen($file)-4);
// insert this file in the array of files
array_push($categories_array[$folder], $base_file_name);
//echo "<br>$base_file_name";
}
}
}
}
}
$timer_2 = microtime(true);
// !! if you use wrong sorting parameter it will convert the category string keys into integer
arsort($categories_array);
//ksort($categories_array);
?>
I tried with $base_file_name = filemtime($file); but does not seems to work.
Any help in this regards will be appreciated.
Thanks in advance.

You could write function, similar to this. It's not tested, so it proboly won't work right away.
$scandir_array = order_by_date(scandir('files'));
function order_by_date($files) {
$return = array();
foreach ($files as $file) {
$return[$file] = filemtime($file);
}
arsort($files);
$return = array_keys($files);
return $return;
}

SOLVED:
$categories_array = array ();
$temp_array = array ();
$timer_1 = microtime ( true );
$scandir_array = scandir ( 'files' );
foreach ( $scandir_array as $folder ) {
if (is_dir ( 'files/' . $folder ) and $folder != '.' and $folder != '..') {
$timestamp = filemtime ( 'files/' . $folder );
$temp_array[$timestamp] = $folder;
}
}
krsort ( $temp_array ); // sorts an array by key.
foreach ( $temp_array as $folder ) {
// define this key in the array, it will be blank, store categories as keys
$categories_array [$folder] = array ();
$files_in_dir = scandir ( 'files/' . $folder );
foreach ( $files_in_dir as $file ) {
if ($file != '.' and $file != '..') {
// if file is not the category thumbnail (thumbnail.jpg) and not _thumb.jpg and not _small.jpg
if ($file != "thumbnail.jpg" and substr ( $file, strlen ( $file ) - 10 ) != "_small.jpg" and substr ( $file, strlen ( $file ) - 10 ) != "_thumb.jpg") {
$base_file_name = substr ( $file, 0, strlen ( $file ) - 4 );
// insert this file in the array of files
array_push ( $categories_array [$folder], $base_file_name );
} // if
} // if
} // foreach
} // foreach

Related

Get list of multi layered folder structure in php [duplicate]

I'd like my script to scandir recursively,
$files = scandir('/dir');
foreach($files as $file){
if(is_dir($file)){
echo '<li><label class="tree-toggler nav-header"><i class="fa fa-folder-o"></i>'.$file.'</label>';
$subfiles = scandir($rooturl.'/'.$file);
foreach($subfiles as $subfile){
// and so on and on and on
}
echo '<li>';
} else {
echo $file.'<br />';
}
}
I'd like to loop this in a way that for each dir found by scandir, it runs another scandir on the folders that have been found within that dir,
So dir 'A' contains dir 1/2/3, it should now scandir(1), scandir(2), scandir(3)
and so on for each dir found.
How can I manage to implement this easily without copy pasting the code over and over in every foreach?
EDIT: Since the answers are nearly the very same as I already tried, I'll update the question a bit.
With this script I need to create a treeview list. With the current posted scripts the following get's echo'd happens:
/images/dir1/file1.png
/images/dir1/file2.png
/images/dir1/file3.png
/images/anotherfile.php
/data/uploads/avatar.jpg
/data/config.php
index.php
What I actually need is:
<li><label>images</label>
<ul>
<li><label>dir1</label>
<ul>
<li>file1.png</li>
<li>file2.png</li>
<li>file3.png</li>
</ul>
</li>
<li>anotherfile.php</li>
</ul>
</li>
<li><label>data</label>
<ul>
<li><label>uploads</label>
<ul>
<li>avatar.jpg</li>
</ul>
</li>
<li>config.php</li>
</ul>
</li>
<li>index.php</li>
And so on, Thank you for the already posted answers!
I know this is an old question but I wrote a version of this that was more functional. It doesn't use global state and uses pure functions to figure things out:
function scanAllDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanAllDir($filePath) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$result[] = $filename;
}
}
return $result;
}
You can scan directory recursively in this way the target is your top most directory:
function scanDir($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
scanDir( $file );
}
}
}
You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:
function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = #opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && #is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}
Pass your path to the function:
$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);
$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')
All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.
What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.
I hope this will help you and I wish you a merry Christmas.
function getFiles(string $directory, array $allFiles = []): array
{
$files = array_diff(scandir($directory), ['.', '..']);
foreach ($files as $file) {
$fullPath = $directory. DIRECTORY_SEPARATOR .$file;
if( is_dir($fullPath) )
$allFiles += getFiles($fullPath, $allFiles);
else
$allFiles[] = $file;
}
return $allFiles;
}
I know this is old but i wanted to show a slightly different version of the other answers. Uses array_diff to discard the "." and ".." folders. Also the + operator to combine 2 arrays ( i rarely see this used so it might be useful for someone )
Though the question is old. But my answer could help people who visit this question.
This recursively scans the directory and child directories and stores the output in a global variable.
global $file_info; // All the file paths will be pushed here
$file_info = array();
/**
*
* #function recursive_scan
* #description Recursively scans a folder and its child folders
* #param $path :: Path of the folder/file
*
* */
function recursive_scan($path){
global $file_info;
$path = rtrim($path, '/');
if(!is_dir($path)) $file_info[] = $path;
else {
$files = scandir($path);
foreach($files as $file) if($file != '.' && $file != '..') recursive_scan($path . '/' . $file);
}
}
recursive_scan('/var/www/html/wp-4.7.2/wp-content/plugins/site-backup');
print_r($file_info);
Create a scan function and call it recursively...
e.g:
<?php
function scandir_rec($root)
{
echo $root . PHP_EOL;
// When it's a file or not a valid dir name
// Print it out and stop recusion
if (is_file($root) || !is_dir($root)) {
return;
}
// starts the scan
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue; // skip . and ..
}
$path = $root . '/' . $dir;
scandir_rec($path); // <--- CALL THE FUNCTION ITSELF TO DO THE SAME THING WITH SUB DIRS OR FILES.
}
}
// run it when needed
scandir_rec('./rootDir');
You can do a lot variation of this function. Printing a 'li' tag instead of PHP_EOL for instance, to create a tree view.
[EDIT]
<?php
function scandir_rec($root)
{
// if root is a file
if (is_file($root)) {
echo '<li>' . basename($root) . '</li>';
return;
}
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . '/' . $dir;
if (is_file($path)) {
// if file, create list item tag, and done.
echo '<li>' . $dir . '</li>';
} else if (is_dir($path)) {
// if dir, create list item with sub ul tag
echo '<li>';
echo '<label>' . $dir . '</label>';
echo '<ul>';
scandir_rec($path); // <--- then recursion
echo '</ul>';
echo '</li>';
}
}
}
// init call
$rootDir = 'rootDir';
echo '<ul>';
scandir_rec($rootDir);
echo '</ul>';
Modern way:
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
$path = '/var/www/path/to/your/files/';
foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ) ) as $file ) {
// TODO: Uncomment to see additional information. Do your manipulations with the files here.
// var_dump( $file->getPathname() ); // Or simple way: echo $file;
// var_dump( $file->isFile() );
// var_dump( $file->isDir() );
// var_dump( $file->getFileInfo() );
// var_dump( $file->getExtension() );
// var_dump( $file->getDepth() );
}
function deepScan($dir = __DIR__){
static $allFiles = [];
$allFiles[$dir] = [];
$directories = array_values(array_diff(scandir($dir), ['.', '..']));
foreach($directories as $directory){
if(is_dir("$dir\\$directory")){
foreach(deepScan("$dir\\$directory") as $key => $value) $allFiles[$key] = $value;
}
else{
$allFiles[$dir][] = "$directory";
}
}
return $allFiles;
}

Display a multi image(array) name from database in codeigniter

My problem is how to display the array image from database. I called that array image because when I uploaded that image I'm using an array to do upload to database.
I'm using this code to insert the file name to database
public function multipost()
{
$filepath = $this->upload->get_multi_upload_data('file_name');
$filenames = '';
foreach($filepath as $a) {
$filenames .= $a['file_name'].",";
}
$filenames = rtrim($filenames,',');
$db_data = array(
'pic_id'=> NULL,
'ad_pic'=> $filenames,
);
$this->db->insert('technical_slide_img', $db_data);
}
That result to
As you can see the ad_pic column has the value of 1.jpg,2.jpg.
if I'm using like this
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode("/", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
to display that image. Is there any way to display that images? Or do I need to separate that 2 images into row?
replace
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode("/", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
with
<?php
foreach ($this->header_model->getalldata() as $row)
{
$image_arr = explode(",", $row->ad_pic);
foreach($image_arr as $image_name)
{
echo base_url().'images/'.$image_name .'<br />';
}
}
?>
As i see in your database table image is saved with comma , and you are exploding it with slash / . So i think you have to replace / with , in your explode function.
<?php foreach ($this->header_model->getalldata() as $row) {
$image_arr = explode(",", $row->image);
$image_name = end($image_arr);
echo base_url().'images/'.$image_name;
} ?>
<?php
$image_arr = explode(",", $data_user->image);
foreach($image_arr as $image_name)
{?>
<img style="width:5em;"src="<?php echo base_url().'uploads/'.$image_name?>" class="img-reponsive thumbnail">
<!-- echo base_url().'images/'.$image_name .'<br />'; -->
<?php }
?>

PHP scandir recursively

I'd like my script to scandir recursively,
$files = scandir('/dir');
foreach($files as $file){
if(is_dir($file)){
echo '<li><label class="tree-toggler nav-header"><i class="fa fa-folder-o"></i>'.$file.'</label>';
$subfiles = scandir($rooturl.'/'.$file);
foreach($subfiles as $subfile){
// and so on and on and on
}
echo '<li>';
} else {
echo $file.'<br />';
}
}
I'd like to loop this in a way that for each dir found by scandir, it runs another scandir on the folders that have been found within that dir,
So dir 'A' contains dir 1/2/3, it should now scandir(1), scandir(2), scandir(3)
and so on for each dir found.
How can I manage to implement this easily without copy pasting the code over and over in every foreach?
EDIT: Since the answers are nearly the very same as I already tried, I'll update the question a bit.
With this script I need to create a treeview list. With the current posted scripts the following get's echo'd happens:
/images/dir1/file1.png
/images/dir1/file2.png
/images/dir1/file3.png
/images/anotherfile.php
/data/uploads/avatar.jpg
/data/config.php
index.php
What I actually need is:
<li><label>images</label>
<ul>
<li><label>dir1</label>
<ul>
<li>file1.png</li>
<li>file2.png</li>
<li>file3.png</li>
</ul>
</li>
<li>anotherfile.php</li>
</ul>
</li>
<li><label>data</label>
<ul>
<li><label>uploads</label>
<ul>
<li>avatar.jpg</li>
</ul>
</li>
<li>config.php</li>
</ul>
</li>
<li>index.php</li>
And so on, Thank you for the already posted answers!
I know this is an old question but I wrote a version of this that was more functional. It doesn't use global state and uses pure functions to figure things out:
function scanAllDir($dir) {
$result = [];
foreach(scandir($dir) as $filename) {
if ($filename[0] === '.') continue;
$filePath = $dir . '/' . $filename;
if (is_dir($filePath)) {
foreach (scanAllDir($filePath) as $childFilename) {
$result[] = $filename . '/' . $childFilename;
}
} else {
$result[] = $filename;
}
}
return $result;
}
You can scan directory recursively in this way the target is your top most directory:
function scanDir($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
scanDir( $file );
}
}
}
You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:
function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = #opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && #is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}
Pass your path to the function:
$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);
$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')
All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.
What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.
I hope this will help you and I wish you a merry Christmas.
function getFiles(string $directory, array $allFiles = []): array
{
$files = array_diff(scandir($directory), ['.', '..']);
foreach ($files as $file) {
$fullPath = $directory. DIRECTORY_SEPARATOR .$file;
if( is_dir($fullPath) )
$allFiles += getFiles($fullPath, $allFiles);
else
$allFiles[] = $file;
}
return $allFiles;
}
I know this is old but i wanted to show a slightly different version of the other answers. Uses array_diff to discard the "." and ".." folders. Also the + operator to combine 2 arrays ( i rarely see this used so it might be useful for someone )
Though the question is old. But my answer could help people who visit this question.
This recursively scans the directory and child directories and stores the output in a global variable.
global $file_info; // All the file paths will be pushed here
$file_info = array();
/**
*
* #function recursive_scan
* #description Recursively scans a folder and its child folders
* #param $path :: Path of the folder/file
*
* */
function recursive_scan($path){
global $file_info;
$path = rtrim($path, '/');
if(!is_dir($path)) $file_info[] = $path;
else {
$files = scandir($path);
foreach($files as $file) if($file != '.' && $file != '..') recursive_scan($path . '/' . $file);
}
}
recursive_scan('/var/www/html/wp-4.7.2/wp-content/plugins/site-backup');
print_r($file_info);
Create a scan function and call it recursively...
e.g:
<?php
function scandir_rec($root)
{
echo $root . PHP_EOL;
// When it's a file or not a valid dir name
// Print it out and stop recusion
if (is_file($root) || !is_dir($root)) {
return;
}
// starts the scan
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue; // skip . and ..
}
$path = $root . '/' . $dir;
scandir_rec($path); // <--- CALL THE FUNCTION ITSELF TO DO THE SAME THING WITH SUB DIRS OR FILES.
}
}
// run it when needed
scandir_rec('./rootDir');
You can do a lot variation of this function. Printing a 'li' tag instead of PHP_EOL for instance, to create a tree view.
[EDIT]
<?php
function scandir_rec($root)
{
// if root is a file
if (is_file($root)) {
echo '<li>' . basename($root) . '</li>';
return;
}
if (!is_dir($root)) {
return;
}
$dirs = scandir($root);
foreach ($dirs as $dir) {
if ($dir == '.' || $dir == '..') {
continue;
}
$path = $root . '/' . $dir;
if (is_file($path)) {
// if file, create list item tag, and done.
echo '<li>' . $dir . '</li>';
} else if (is_dir($path)) {
// if dir, create list item with sub ul tag
echo '<li>';
echo '<label>' . $dir . '</label>';
echo '<ul>';
scandir_rec($path); // <--- then recursion
echo '</ul>';
echo '</li>';
}
}
}
// init call
$rootDir = 'rootDir';
echo '<ul>';
scandir_rec($rootDir);
echo '</ul>';
Modern way:
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
$path = '/var/www/path/to/your/files/';
foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, RecursiveDirectoryIterator::SKIP_DOTS ) ) as $file ) {
// TODO: Uncomment to see additional information. Do your manipulations with the files here.
// var_dump( $file->getPathname() ); // Or simple way: echo $file;
// var_dump( $file->isFile() );
// var_dump( $file->isDir() );
// var_dump( $file->getFileInfo() );
// var_dump( $file->getExtension() );
// var_dump( $file->getDepth() );
}
function deepScan($dir = __DIR__){
static $allFiles = [];
$allFiles[$dir] = [];
$directories = array_values(array_diff(scandir($dir), ['.', '..']));
foreach($directories as $directory){
if(is_dir("$dir\\$directory")){
foreach(deepScan("$dir\\$directory") as $key => $value) $allFiles[$key] = $value;
}
else{
$allFiles[$dir][] = "$directory";
}
}
return $allFiles;
}

How to load images and categorise with Unknown Prefix in filename?

This is the code which loads images with different Prefix and the prefix is printed under every image.
I need Prefix as a Title of every set of images as Category of Images
CODE :
$images = glob($dirname . "*.jpg");
foreach ($images as $image) {
if (strpos($image, '#') !== false) {
} else {
?>
<li><?php $mn_img = str_replace("/thumbs", "", $image); ?>
<div class="th [radius]">
<a href="<?php echo $mn_img ?>"><img align="middle"
src="<?php echo $image; ?>"> </a>
</div>
<p style="text-align: center">
<?php
$str = $mn_img;
$s = end(explode("/", $str));
$e = explode(".", $s);
$n = explode('-', $e[0]);
$nm = $n[0];
if ($nm === 'non') {
echo 'general';
} else {
$title = str_replace("_", " ", $nm);
echo $title;
}
?>
</p>
</li>
<?php }
}
I expect the possibility :)
MY Prefix Format is
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Manager_fileoriginalname_random.jpg
Prefix is "Manager"
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Matketing_fileoriginalname_random.jpg
Prefix is "Marketing"
is the preg_match function is what you want :
$returnValue = preg_match( '/(.*)_.*_.*$/', 'Manager_fileoriginalname_random.jpg', $matches );
in $matches[1] you have the prefix, you just need to remplace 'Manager_fileoriginalname_random.jpg' by your var $mn_img
If i can make and advise, can use parse_url() to extract url components : http://php.net/manual/fr/function.parse-url.php

How to sort floats in an array?

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);
...
}

Categories