简体   繁体   中英

How to show uploaded pdf files from a server directory on the browser in PHP

I've been trying to implement a flow where an admin uploads the pdf's of his choice to the server, under directory name "doc_files". This is what I've done:

<form action="upload_file.php" method="post" enctype="multipart/form-data">

    <input type="file" name="file" size="50" />

    <br />

    <input type="submit" value="Upload" name="submit"/>

Next I want a page where he/she can view all the uploaded files on a single page. Can anyone please suggest a way to achieve it in PHP?

Uploaded files are moved to a temporary directory after they are sent to the server using forms. You have to manually move them to the directory of your choice.

The names of the uploaded files (or errors) are stored in a global array $_FILES .

Look up move_uploaded_file() and use it in your upload_file.php script:

move_uploaded_file ($file, "/my/files/".$new_filename);

For $new_filename you can use your original file name but a good practice is to make sure that similar file does not already exist in that directory with file_exists() . If so, act appropriately (eg suggest a more appropriate name, throw an error or use unique hashes and store original file names in a database).

Then you can use readdir to find out all the files in the directory like so:

if ($handle = opendir('/my/files')) {
while (false !== ($file = readdir($handle))) {
    if($file!="." && $file!="..") echo "$file\n";
}

If upload dir belongs to your server root, you may look up for directory listing by server(apache, nginx, etc.). It might be the simpliest way. Another way is make your own files-viewer. Something like this:

foreach(glob('YOUR_DIR/*.pdf') as $file) {
    // build your custom link
    echo "www.yourdomain.com/path/to/dir/" . $file; //or basename($file)
}

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