简体   繁体   中英

PHP & HTML: Download file link not working

The following code lists all the files contained in a certain folder in my local machine, as you can see I'm echoing the file path inside the tag using the href attribute correctly.

So the problem is that when I click on the tag, it doesn't take me to the file download unless I copy the link and paste it to another tab of the browser, why is this happening? How can I fix it?

<h5>Attached Files</h5>

<?php
    $date = $dateCreated->format('d-m-Y');
    $thepath = public_path().'/uploads/binnacle/'.$date.'/'.$activity->activity_id;

    $handle = opendir($thepath);
    $x = 1;
    while(($file = readdir($handle))!= FALSE) {
        if($file != "." && $file != ".." && $file != "thumbs" && $file != "thumbs.db") {

            echo $x.".- "."<a href='$thepath/$file' target='_blank'>$file</a><br>";

            $x++;
        }
    }
    closedir($handle);
?>

NOTE: This happens with all file types including images, excel files, text documents, etc.


SOLUTION BY @WereWolf - The Alpha:

<?php
    $date = $dateCreated->format('d-m-Y');
    $thepath = "/uploads/binnacle/".$date."/".$activity->activity_id;

    $handle = opendir(public_path().$thepath);
    $x = 1;
    while(($file = readdir($handle))!= FALSE) {
        if($file != "." && $file != ".." && $file != "thumbs" && $file != "thumbs.db")
            {
            echo $x.'.- '.'<a href="'.asset($thepath.'/'.$file).'" target="_blank">'.$file.'</a><br>';
            $x++;
        }
    }
    closedir($handle);
?>

Make some changes:

// Remove the public_path()
$thepath = 'uploads/binnacle/'.$date.'/'.$activity->activity_id;

Then in the link:

"<a href='" . asset($thepath/$file) . "' target='_blank'>$file</a><br>";

Note: Laravel has a File component, You may use that, check it in the source .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM