Instead of the traditional navigation, I am trying to emulate the terminal navigation, or how you navigate with vim.
Example:
..
index
otherfile
This is my code:
$dir = realpath(dirname(__FILE__));
if(is_dir($dir)){
if($open = opendir($dir)){
while(($file = readdir($open)) !==false){
if(is_dir($file)){
if($file == '.'){ }
else{
echo "".$file."<br/>";
}
}
else{
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
}
}
}
else{
echo $dir." Was not found";
}
}
How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list.
I want to sort files by given them a number example '1file.php' '2anotherfile.php'..
How could I sort them by the number, then remove the number and '.php', and finally print it out?
If you feel like refactoring something please do so...
"How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list."
Just check if the current item is the current file, if it is then skip it:
else {
if ($name == basename(dirname(__FILE__))) continue; // if this is the current file, go to the next iteration of the loop
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
Note that this assumes you are in the same directory as the file (which it can do because $dir is always the directory the script is in), if not you can just add a directory check as well.
"How can add a number to the start of the file or folder, example 1index.php, then on the code, organize all the files and folder by number, and print them without the number and '.php'?"
Well I'm not too sure what you mean by this, but if you mean sort alphabetically, then it is already alphabetically sorted when you get the list.
Related
I have a script I am using to filter some ROM and ISO files.
I have (with a lot of help) got a working script where files are filtered by filename, however I am trying to add a section in which I can include extra ad-hoc filenames to be filtered for me by providing them in a local .txt file. This is working OK, however in my .txt file I am having to put the full filename (including the .txt extension) into the .txt - for example my "manualregiondupes.txt file looks like this:
Game One.zip
Game Two.zip
Game Three.zip
Whereas I want it to just type them in my .txt file like so:
Game One
Game Two
Game Three
The current regex i'm using is trying to match the full filename it finds (including the .zip extension) whereas I want it to just match the section before the file extension. I have to be careful, however - as I don't want a game like:
"Summer Heat Beach Volleyball (USA)" being matched if "Beach Volleyball (USA)" is in the .txt.
Same goes for words on the other side - like
"Sensible Soccer (USA) (BETA)" being matched if "Sensible Soccer (USA)" is in the .txt
Here is my script;
// Make sure what manualregiondupes.txt is doing
if (file_exists('manualregiondupes.txt'))
{
$manualRegionDupes = file('manualregiondupes.txt', FILE_IGNORE_NEW_LINES);
$manualRegionPattern = "/^(?:" . implode("|", array_map(function ($i)
{
return preg_quote(trim($i) , "/");
}
, $manualRegionDupes)) . ')$/';
echo "ManualRegionDupes.txt has been found, ";
if (trim(file_get_contents('manualregiondupes.txt')) == false)
{
echo "but is empty! Continuing without manual region dupes filter.\n";
}
else
{
echo "and is NOT empty! Applying the manual region dupes filter.\n";
}
}
else
{
echo "ManualRegionDupes.txt has NOT been found. Continuing without the manual region dupes filter.\n";
}
// Do this magic for every file
foreach ($gameArray as $thisGame) {
if (!$thisGame) continue;
// Probably already been removed
if (!file_exists($thisGame)) continue;
// Filenames in manualregiondupes.txt
if (file_exists('manualregiondupes.txt'))
{
if (trim(file_get_contents('manualregiondupes.txt')) == true)
{
if (preg_match($manualRegionPattern, $thisGame))
{
echo "{$thisGame} is on the manual region dupes remove list. Moved to Removed folder.\n";
shell_exec("mv \"{$thisGame}\" Removed/");
continue;
}
}
}
... SCRIPT CONTINUES HERE BUT ISN'T RELEVANT!
What's the easiest way of doing this? I think i've just asked a very long question when it's actually quite simple, but oh well - I am not very good with PHP (or any script to be honest!) so apologies and thankyou's in advance! :D
You can use pathinfo in regex like -
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
it gives you perfect file name output without extension for
file.txt -> file
file.sometext.txt -> file.sometext
I have been working on some project and through time it got messed up with images which I tested it, so now I want to make a script which is going to search in articles img tags and find the img name (artiles are stored in mysql with attribute 'text') after scanning the folder where images are stored if they are not in any article included then to delete those images (unused images). Has anyone done this before so I could see an example or any good approach about this case?
Here's what you'll need to do what you want:
Loop through your directory of files (if they are on the filesystem):
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
Ref. http://php.net/readdir
Loop through your files (if they are on the database):
Ref. http://www.php.net/manual/en/mysqli.query.php
Compare file names (obvious once you are looping through your resource).
Delete unused images like so http://www.php.net/unlink
Approach is simple
Query database and get list of all image URLs - add to an array
Loop through each folder that contains images and make an array of every image on the site/
here is how to find all items that are in one array but not another (may be a better answer more specific to you - array_Intesect is what you need.
with the new array simply loop through the list and delete the files.
All of the above you can search individually and then string them together.
I would recommend backing everything up before trying!!!!
I recently came accross such thing where I wanted to remove unused files that users left behind / change the profile picture but they were stored on the webserver. To fix this I used this :
$images = scandir("uploads", 1);
foreach ($images as $itemlc)
{
$res=mysql_query("SELECT * FROM company WHERE c_logo='$itemlc'");
$count = mysql_num_rows($res);
$res2=mysql_query("SELECT * FROM users WHERE u_logo='$itemlc'");
$count2 = mysql_num_rows($res2);
if($count == 1)
{
echo $itemlc; echo " exists <br><br>";
}
else if ($count2 == 1)
{
echo $itemlc; echo " exists <br><br>";
}
else{ $file_path = 'uploads/'; $src=$file_path.$itemlc; #unlink($src); }
}
Hope this helps if there is someone who needs this!
So I have a URL which contains &title=blabla
I know how to extract the title, and return it. But I've been searching my ass off to get the full path to the filename when I only have the filename.
So what I must have is an way to search in all directories for an html file called 'blabla' when the only thing it has is blabla. After finding it, it must return the full path.
Anyone who does have an solution for me?
<?php
$file = $_GET['title'];
if ($title = '') {
echo "information.html";
} else {
//here it must search for the filepath and echo it.
echo "$filepath";
}
?>
You can use the solution provided here.
It allows you to recurse through a directory and list all files in the directory and sub-directories. You can then compare to see if it matches the files you are looking for.
$root = '/'; // directory from where to start search
$toSearch = 'file.blah'; // basename of the file you wish to search
$it = new RecursiveDirectoryIterator($root);
foreach(new RecursiveIteratorIterator($it) as $file){
if($file->getBasename() === $toSearch){
printf("Found it! It's %s", $file->getRealPath());
// stop at the first match
break;
}
}
Keep in mind that depending on the number of files you have, this can be slow as hell
For a start this line is at fault
if ($title = '') {
See http://www.php.net/manual/en/reserved.variables.files.php
I have a double question. Part one: I've pulled a nice list of pdf files from a directory and have appended a file called download.php to the "href" link so the pdf files don't try to open as a web page (they do save/save as instead). Trouble is I need to order the pdf files/links by date created. I've tried lots of variations but nothing seems to work! Script below. I'd also like to get rid of the "." and ".." directory dots! Any ideas on how to achieve all of that. Individually, these problems have been solved before, but not with my appended download.php scenario :)
<?php
$dir="../uploads2"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
?>
<p><a href="http://www.duncton.org/download.php?file=login/uploads2/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
While you can filter them out*, the . and .. handles always come first. So you could just cut them away. In particular if you use the simpler scandir() method:
foreach (array_slice(scandir($dir), 2) as $filename) {
One could also use glob("dir/*") which skips dotfiles implicitly. As it returns the full path sorting by ctime then becomes easier as well:
$files = glob("dir/*");
// make filename->ctime mapping
$files = array_combine($files, array_map("filectime", $files));
// sorts filename list
arsort($files);
$files = array_keys($files);
I have a directory containing sub directories which each contain a series of files. I'm looking for a script that will look inside the sub directories and randomly return a specified number of files.
There are a few scripts that can search a single directories (not sub folders), and other scripts that can search sub folders but only return one file.
To put a little context on the situation, the returned files will be included as li's in an rotating banner.
Thanks in advance for any help, hopefully this is possible.
I think I've got there, not exactly what I set out to achieve but works good enough, arguably better for the purpose, I'm using the following function:
<?php function RandomFile($folder='', $extensions='.*'){
// fix path:
$folder = trim($folder);
$folder = ($folder == '') ? './' : $folder;
// check folder:
if (!is_dir($folder)){ die('invalid folder given!'); }
// create files array
$files = array();
// open directory
if ($dir = #opendir($folder)){
// go trough all files:
while($file = readdir($dir)){
if (!preg_match('/^\.+$/', $file) and
preg_match('/\.('.$extensions.')$/', $file)){
// feed the array:
$files[] = $file;
}
}
// close directory
closedir($dir);
}
else {
die('Could not open the folder "'.$folder.'"');
}
if (count($files) == 0){
die('No files where found :-(');
}
// seed random function:
mt_srand((double)microtime()*1000000);
// get an random index:
$rand = mt_rand(0, count($files)-1);
// check again:
if (!isset($files[$rand])){
die('Array index was not found! very strange!');
}
// return the random file:
return $folder . "/" . $files[$rand];
}
$random1 = RandomFile('project-banners/website-design');
while (!$random2 || $random2 == $random1) {
$random2 = RandomFile('project-banners/logo-design');
}
while (!$random3 || $random3 == $random1 || $random3 == $random2) {
$random3 = RandomFile('project-banners/design-for-print');
}
?>
And echoing the results into the container (in this case the ul):
<?php include($random1) ;?>
<?php include($random2) ;?>
<?php include($random3) ;?>
Thanks to quickshiftin for his help, however it was a little above my skill level.
For info the original script which I changed an be found at:
http://randaclay.com/tips-tools/multiple-random-image-php-script/
Scrubbing the filesystem every single time to randomly select a file to display will be really slow. You should index the directory structure ahead of time. You can do this many ways, try a simple find command or if you really want to use PHP my favorite choice would be RecursiveDirectoryIterator plus RecursiveIteratorIterator.
Put all the results into one file and just read from there when you select a file to display. You can use the line numbers as an index, and the rand function to pick a line and thus a file to display. You might want to consider something more evenly distributed than rand though, you know to keep the advertisers happy :)
EDIT:
Adding a simple real-world example:
// define the location of the portfolio directory
define('PORTFOLIO_ROOT', '/Users/quickshiftin/junk-php');
// and a place where we'll store the index
define('FILE_INDEX', '/tmp/porfolio-map.txt');
// if the index doesn't exist, build it
// (this doesn't take into account changes to the portfolio files)
if(!file_exists(FILE_INDEX))
shell_exec('find ' . PORTFOLIO_ROOT . ' > ' . FILE_INDEX);
// read the index into memory (very slow but easy way to do this)
$aIndex = file(FILE_INDEX);
// randomly select an index
$iIndex = rand(0, count($aIndex) - 1);
// spit out the filename
var_dump(trim($aIndex[$iIndex]));