Scandir Array display without file extensions - php

I'm using the following to create a list of my files in the 'html/' and link path.
When I view the array it shows, for example, my_file_name.php
How do I make it so the array only shows the filename and not the extension?
$path = array("./html/","./link/");
$path2= array("http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/html/","http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/link/");
$start="";
$Fnm = "./html.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."\n");
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
while( $file2 = readdir($folder2) ) {
if (substr($file2,0,strpos($file2,'.')) == substr($file,0,strpos($file,'.'))){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
fwrite($inF,"");
closedir($folder);
fclose($inF);

pathinfo() is good, but I think in this case you can get away with strrpos(). I'm not sure what you're trying to do with $imagename, but I'll leave that to you. Here is what you can do with your code to compare just the base filenames:
// ...
$folder = opendir($path[0]);
while( $file = readdir($folder) ) {
if (($file != '.')&&($file != '..')&&($file != 'index.htm')) {
$folder2 = opendir($path[1]);
$imagename ='';
$fileBaseName = substr($file,0,strrpos($file,'.'));
while( $file2 = readdir($folder2) ) {
$file2BaseName = substr($file2,0,strrpos($file2,'.'));
if ($file2BaseName == $fileBaseName){
$imagename = $file2;
}
}
closedir($folder2);
$result="<li class=\"ui-state-default ui-corner-top ui-tabs-selected ui-state-active\">\n\n$file2\n<span class=\"glow\"><br></span>
</li>\n";
fwrite($inF,$result);
}
}
I hope that helps!

Related

Auto Photo Albums in codeigniter

I have used Auto Photo Albums – Multi Level Image Grid for integration of my gallery in my website, it is easily integrated in core PHP but when am using codeigniter frame work for integration of this plugin am unable to get the images
The plugin consists of three files with a directory
reader.php
gallery.html
Reader.php
<?php
//CONFIGURATION
$imgTypes = array('jpeg', 'jpg', 'png', 'gif'); // The extensions of Images that the plugin will read
$imagesOrder = $_GET['imagesOrder']; //byDate, byDateReverse, byName, byNameReverse, random
$folderCoverRandom = $_GET['folderCoverRandom'];
$albumsOrder = $_GET['albumsOrder'];
function getList ($directory, $type='none') {
global $imgTypes;
global $imagesOrder;
global $albumsOrder;
$order = $imagesOrder;
if($type == 'albums'){
$order = $albumsOrder;
}
if( !is_dir($directory)){
return array();
}
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != ".." && $file != ".DS_Store" && $file != "#eaDir") {
$extension = preg_split('/\./',$file);
$extension = strtolower($extension[count($extension)-1]);
if($type == 'none'){
//do nothing
}else if($type == 'albums'){
if( !is_dir($directory.'/'.$file) ){
continue;
}
}else if($type == 'images'){
if( is_dir($directory.'/'.$file) ){
continue;
}
}
if( (array_search($extension,$imgTypes) !== FALSE || is_dir($directory.'/'.$file)) && $file != "thumbnails" ){
$ctime = filemtime($directory .'/'. $file) . ',' . $file; //BRING THE DATE OF THE IMAGE
if($order == 'byName' || $order == 'byNameReverse'){
$ctime = $file;
}
$results[$ctime] = $file;
}
}
}
closedir($handler);
if($order == 'byDate' || $order == 'byNameReverse'){
krsort($results);
}else if($order == 'byDateReverse' || $order == 'byName'){
ksort($results);
}else if($order == 'random'){
shuffle($results);
}
return $results;
}
function fixArray($list, $directory){
global $folderCoverRandom;
$return = array();
foreach ($list as $key => $value) {
$val = "";
if( is_dir($directory.'/'.$value) ){
$val = "folder";
$arr = getList($directory.'/'.$value);
$folderImg = "";
$folderImgCover = "";
$thumb = 'no';
$numImg = 0;
$numFolders = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
$numFolders++;
}else{//IF IT IS AN IMAGE
//PICK THE FIRST IMAGES FROM THE FOLDER TO USE IT AS COVER IMAGE
if( $folderImg == "" ){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
//VERIFY IF THERE IS ANY "folderCover" IMAGE IN THE FOLDER SO WE CAN USE IT AS COVER IMAGE
$arrName = preg_split('/\.(?=[^.]*$)/',$value2);
$imgName = $arrName[0];
if( $folderImgCover == "" && $imgName == "folderCover" ){
$folderImgCover = $value2;
}
if($imgName != "folderCover"){
$numImg++;
}
}
}
//PICK A RANDOM IMAGES FROM THE FOLDER TO USE IT AS RANDOM IMAGE
if($folderCoverRandom == 'true'){
$rand = rand(0,$numImg-1);
$cont = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
// DO NOTHING
}else{//IF IT IS AN IMAGE
if($cont == $rand){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
$cont++;
}
}
}
//IF THERE IS A COVER IMAGE INSIDE THE FOLDER THEN USE IT!
if( $folderImgCover != "" ){
$folderImg = $folderImgCover;
$thumb = "no";
}
$val = array('numImages' => $numImg, 'numFolders' => $numFolders, 'image' => $folderImg, 'thumb' => $thumb);
}else{
$thumb = 'no';
if( file_exists( $directory.'/thumbnails'.'/'.$value ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
$val = $thumb;
}
$return[$value] = $val;
}
return $return;
}
$directory = $_GET['directory'];
//THE RESULT OF THE JSON CALL
$output = array();
$list = array();
if($albumsOrder != 'none'){//Apply a different order to the folders
$albums = getList($directory, 'albums');
$images = getList($directory, 'images');
$list = $albums + $images;
}else{
//GET LIST OF IMAGES AND FOLDERS
$list = getList($directory);
}
$output = fixArray($list, $directory);
// print_r($output);
//echo json_encode($output, JSON_FORCE_OBJECT); // if you are using PHP 5.3 plase use this line instead of the one below
echo json_encode($output);
?>
Gallery.html
<div class="container-fluid">
<div id="grid" data-directory="Gallery"></div>
</div>
All the images are loaded into the directory i,e Gallery Folder the images are retrieved into the page by using the reader file
When i have integrated the same files in codeigniter the are images are unable to load
I have created reader.php as a library and i have called it in the controller but it shows error
Undefined index: imagesOrder
Undefined index: folderCoverRandom
Undefined index: directory
Gallery Output :http://www.davidbo.dreamhosters.com/plugins/AutoAlbums/plugin/index2.html
Plugin : https://codecanyon.net/item/auto-photo-albums-multi-level-image-grid/5319229
Please help me out how can i integrate this to codeigniter

Creating default object from empty value in OT Scroller

I have problem with warning on my Joomla website. More precisely "Warning: Creating default object from empty value in /public_html/modules/mod_ot_scroller/helper.php on line 40"
Here is whole helper.php file:
<?php
defined('_JEXEC') or die;
class modOTScrollerHelper
{
function getImages(&$params, $folder, $type)
{
$files = array();
$images = array();
$dir = JPATH_BASE.DS.$folder;
// check if directory exists
if (is_dir($dir))
{
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..' && $file != 'CVS' && $file != 'index.html' && $file != 'Thumbs.db') {
$files[] = $file;
}
}
}
closedir($handle);
foreach($type as $tp){
$tp=trim($tp);
$i = 0;
foreach ($files as $img){
if (!is_dir($dir .DS. $img))
{
if (preg_match("#$tp#i", $img)) {
$images[$i]->name = $img;
$images[$i]->folder = $folder;
++$i;
}
}
}
}
}
return $images;
}
function getFolder(&$params)
{
$folder = $params->get( 'folder' );
$LiveSite = JURI::base();
// if folder includes livesite info, remove
if ( JString::strpos($folder, $LiveSite) === 0 ) {
$folder = str_replace( $LiveSite, '', $folder );
}
// if folder includes absolute path, remove
if ( JString::strpos($folder, JPATH_SITE) === 0 ) {
$folder= str_replace( JPATH_BASE, '', $folder );
}
$folder = str_replace('\\',DS,$folder);
$folder = str_replace('/',DS,$folder);
return $folder;
}
}
?>
Whole website works fine and images shown properly.
What can I do to get rid of it?
Yeah, thats a warning, because you did not specify what $images[$i] should be. If you want to, initialize it using $images[$i] = new \stdClass();

how to make this find specific extensions and show only the file name

1) how can i make this read only ".txt" files
2) how can i make it show only the file name so i can design it how i'd i like..
(<h1>$file</h1> for example)
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos($filename, '.') + 1)) == 'txt')
{
$files[] = $filename;
}
}
sort($files);
echo $files;
what it shows right now is:
Array ( [0] => . [1] => .. [2] => [23.7] Hey.txt [3] => [24.7] New
Website.txt [4] => [25.7] Example.txt )
Now, this is another way i could do it, i like it bit better:
if( $handle = opendir( 'includes/news' ))
{
while( $file = readdir( $handle ))
{
if( strstr( $file, "txt" ) )
{
$addr = strtr($file, array('.txt' => ''));
echo '<h1>» ' . $addr . "</h1>";
}
}
closedir($handle);
}
but the my issue with this one is that there is no Sorting between the files.
everything is ok with the output, just the order of them. so if one of you can figure out how to sort them right, that would be perfect
Okay, try this:
$files = array();
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle )) {
if ($file != '.' && $file != '..') {
// let's check for txt extension
$extension = substr($file, -3);
// filename without '.txt'
$filename = substr($file, 0, -4);
if ($extension == 'txt')
$files[] = $file; // or $filename
}
}
closedir($handle);
}
sort($files);
foreach ($files as $file)
echo '<h1><a href="?module=news&read=' . $file
. '">» ' . $file . "</a></h1>";
I think this should accomplish what you want to do. It uses explode and a negative limit to find only .txt files and returns only the name.
$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))){
$fileName = explode('.txt', $node, -1)[0];
if(count($fileName) )
$files[] = '<h1>'.$fileName.'</h1>';
}
try to make it as simple as possible
try this
function check_txt($file){
$array = explode(".","$file");
if(count($array)!=1 && $array[count($array)-1]=="txt"){return true;}
return false;
}
if($handle = opendir( 'includes/news' )) {
while( $file = readdir( $handle ))
{
if( check_txt($file) )
{
echo '<h1>» ' . $file . "</h1>";
}
}
closedir($handle);
}

Using PHP Sub String to Link Thumbnails

So I am making this simple gallery that fetches images from a directory. All images have names like tree_th.jpg and I would like to use sub string (I assume this is correct) to slice out the _th and link out to just tree.jpg
<?
$imagetypes = array("image/jpeg", "image/gif");
function getImages($dir) {
global $imagetypes;
$dir = "img/";
$retval = array();
if(substr($dir, -1) != "/") $dir .= "/";
$fulldir = "/$dir";
//echo $fulldir;
$d = #dir($fulldir) or die("");
while(false !== ($entry = $d->read())) {
if($entry[0] == ".") continue;
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array( 'file' => "$dir$entry", 'size' => getimagesize("$fulldir$entry") );
break;
}
}
}
$d->close(); return $retval;
}
$thumbs = getImages("img");
foreach($thumbs as $img) {
echo "<img class=\"photo\" src=\"{$img['file']}\" {$img['size'][1]} alt=\"\">\n";
}
?>
One way you can do this is with str_replace() function in PHP.
$large_image_path = str_replace("_th","",$thumb_path);
The substring command you would have to first evaluate the position of the _th, then reassemble the string with a length and concat so I think str_replace would be easier for you.

PHP delete all subdirectories in a directory having expired date?

There is a directory /home/example/public_html/users/files/. Within the directory there are subdirectories with random names like 2378232828923_1298295497.
How do I completely delete the subdirectories which have creation date > 1 month?
There is a good script that I use to delete files, but it don't work with dirs:
$seconds_old = 2629743; //1 month old
$directory = "/home/example/public_html/users/files/";
if( !$dirhandle = #opendir($directory) )
return;
while( false !== ($filename = readdir($dirhandle)) ) {
if( $filename != "." && $filename != ".." ) {
$filename = $directory. "/". $filename;
if( #filectime($filename) < (time()-$seconds_old) )
#unlink($filename); //rmdir maybe?
}
}
you need a recursive function for this.
function remove_dir($dir)
{
chdir($dir);
if( !$dirhandle = #opendir('.') )
return;
while( false !== ($filename = readdir($dirhandle)) ) {
if( $filename == "." || $filename = ".." )
continue;
if( #filectime($filename) < (time()-$seconds_old) ) {
if (is_dir($filename)
remove_dir($filename);
else
#unlink($filename);
}
}
chdir("..");
rmdir($dir);
}
<?php
$dirs = array();
$index = array();
$onemonthback = strtotime('-1 month');
$handle = opendir('relative/path/to/dir');
while($file = readdir($handle){
if(is_dir($file) && $file != '.' && $file != '..'){
$dirs[] = $file;
$index[] = filemtime( 'relative/path/to/dir/'.$file );
}
}
closedir($handle);
asort( $index );
foreach($index as $i => $t) {
if($t < $onemonthback) {
#unlink('relative/path/to/dir/'.$dirs[$i]);
}
}
?>
If PHP runs on a Linux server, you could use a shell command, to improve performance (a recursive PHP function can be inefficient in very large directories):
shell_exec('rm -rf '.$directory);

Categories