Pierre Odendaal Pierre Odendaal - 7 months ago 27
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

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);

echo basename($test);

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

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',
// shouldn't the following be $personID, not personID?
$test = preg_grep('/'.$personID.'/', $personFiles);
$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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download