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
Related
I'd like to be able to search a directory for a file that starts with a specific string, for example:
- foo
- 1_foo.jpg
- 2_bar.png
How would I check directory foo for files that begin with "1_"?
I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.
Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
<?php
foreach (glob('1_*.*') as $filename) {
echo "$filename\n";
}
?>
The above example will output something similar to:
1_foo.png
1_bar.png
1_something.png
Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.
I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).
You can use the glob() function
<?php
$list = glob('1_*.*');
var_dump($list);
I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):
if ($handle = opendir('path/to/folder/'))
{
while ( false !== ($entry = readdir($handle)) ) {
if ( $entry != "." && $entry != ".." ) {
// echo "$entry<br>";
if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
{
// $found_it = TRUE;
}
}
}
closedir($handle);
}
in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...
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]));
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.