how to search for a file with php

bigjim picture bigjim · Jun 1, 2017 · Viewed 20.6k times · Source

First thing is first. I am not a php developer this is something that is needed for my job so I took it on and I am learning as i go

Right now we have an excel sheet that holds links for a manuals for the items we make and these have to be updated manually. It can take hours to do. so I am trying to find a way to do this to cut the time.

I can read the excel file to get the info I need using javascript and then I send that to php with an ajax call.

I have made sure I get the data I need and make it look how they do on the server.

I have been googling all day trying to get it to work but I just keep coming up empty.

Here is my code in the php file.

    <?php
$search = isset($_POST['urlData']) ? rawurldecode($_POST['urlData']) : "Nope Still not set";
$path = $_SERVER['DOCUMENT_ROOT'];


$it = new RecursiveDirectoryIterator( $path );
foreach (new RecursiveIteratorIterator($it) as $file){
    $pathfile = str_replace($path,'',$file);
    if (strpos($pathfile, $search) !== false) {
        echo " pathFile var => ". $pathfile . "| Search var => " . $search;
        $encodedUrl = rawurlencode($pathfile .$search);
        echo 'link = http://manuals.myCompany.com/'. $doneUrl .'<br>';

    }else{

        echo "File does not exist => ";
        echo $path. "<= Path " . $search."<= Search ". $pathfile . "<= Pathfile";

    }
    break;
}

So I need to give the php file the name of a manual and see if it is in the directory somewhere.

this file is searchManuals.php stored in the manuals folder (manuals/searchManuals.php).The files I look for are in folders in the same directory with it (manuals/english/jdv0/pdf/manual.pdf).

Answer

VK321 picture VK321 · Jun 1, 2017

Try this:

$file_to_search = "abc.pdf";

search_file('.',$file_to_search);




function search_file($dir,$file_to_search){

$files = scandir($dir);

foreach($files as $key => $value){

    $path = realpath($dir.DIRECTORY_SEPARATOR.$value);

    if(!is_dir($path)) {

        if($file_to_search == $value){
            echo "file found<br>";
            echo $path;
            break;
        }

    } else if($value != "." && $value != "..") {

        search_file($path, $file_to_search);

    }  
 } 
}