Pierre Odendaal Pierre Odendaal - 1 month ago 11
PHP Question

Getting a file url for a logged in user and display on screen

Firstly, I am "new"(only been coding for a couple months) to PHP and am trying to get a file for a logged in user to display.

I have tried a few options including

baseband
and
url
but it just dosn't seem to work the way I need it to.

Here is a snippet of my code:

$personCalendar = '/folder\calendars\people';
$personFiles = scandir($personCalendars);

$personID = $_SESSION['Person_ID'];

$test = preg_grep('/'.personID.'/',$personFiles);
print_r($test);

echo basename($test);


The output from the
print_r
gives me
Array ( [312] => s15399.ics )
which is great, but I just need the
s15399.ics
part and have it append to the end of the page url something like
https://servername.com/index.php/calendar?s15399.ics
so they can take the file and "subscribe" to their calendar.

baseband
does not being anything but I am not that surprised by that.

Is this possible, if not, what would be the best way you recommend to do this?

Answer Source
// using \ in a file path is not going to work. Use / instead.
// $personCalendar = '/folder\calendars\people';
$personCalendar = '/folder/calendars/people';

// scandir will work but it will eventually run into problems 
// if you have lots and lots of files.
$personFiles = scandir($personCalendars);


$personID = $_SESSION['Person_ID'];
function url(){
    return sprintf('%s//%s%s',
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
        $_SERVER['SERVER_NAME'],
        $_SERVER['REQUEST_URI']
    );
}
// shouldn't the following be $personID, not personID?
$test = preg_grep('/'.$personID.'/', $personFiles);
print_r($test);
$filename = reset($test);
if ( $filename ) {
    $fullUrl = url() . $filename;
    echo $fullUrl;
} else {
    echo "File not found\n";
}

If you need to find a file and you know the file name, you don't need to read all the files. If the file name is the same as the person id, then:

$filename = "s{$personID}.ics";
if ( file_exists($filename) ) {
    //
} else {
    //
}