Making a file directory and having clickable download links in PHP
on my website I want to be able to show a list of files, photos to be exact, and then have them individually linked, so that when someone clicks on one, they can download it.
i'm trying this:
[code]
$path = "c:/users/jon/desktop/pictures";
// Open the folder
$dir_handle = @opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
if($file == "." || $开发者_JAVA百科file == ".." || $file == "index.php" )
continue;
echo "<a href=\"$file\">$file</a><br />";
}
// Close
closedir($dir_handle);
?> [/code]
this lists the files but when I click on them I get object not found, but there definetly there!
what am I doing wrong?
thanks
The path that you have in your href "c:/users/jon/desktop/pictures;" is the path from your file system. You will have to make the picture folder accessible from the web (may need to get your hands dirty with Apache config).
An example of config you can add to your apache.conf (Taken from my apache on linux and modified):
Alias /mypics/ c:/users/jon/desktop/pictures/
<Location /mypics/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Location>
If you can see a list of files from http://localhost/mypics/ so it means the folder is accessible.
And you can update your path relative to your document root
echo "<a href=\"".$path."/".$file."\">$file</a><br />";
to
echo "<a href=\""/mypics/$file."\">$file</a><br />";
If you dont want to the list of files anymore, change
Options Indexes FollowSymLinks MultiViews
to
Options FollowSymLinks MultiViews (not sure about the other options here)
The files are on the C: drive of the server.
The user cannot access the whole of the C: drive of the server, the server is only serving files that are provided from a specified location - this is the place where the PHP files are stored.
You need to put your image files in the same place, and then point your script towards them there.
If you don't want to/can't move them, then you have to make your webserver access the folder, and you should do this as described by ccheneson if you're using apache.
Try this, it is good for me I'm using xampp
$path = "./pictures";
Replace:
echo "<a href=\"$file\">$file</a><br />";
with:
echo "<a href=\"".$path."/".$file."\">$file</a><br />";
The string returned by readdir is the file name not the file path so you have to add the folder path before the filename
精彩评论