简体   繁体   English

如何在PHP浏览器中从服务器目录显示上载的pdf文件

[英]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". 我一直在尝试实现一个流程,在该流程中,管理员将其选择的pdf上载到目录名为“ 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? 任何人都可以提出一种用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 . 上传文件的名称(或错误)存储在全局数组$ _FILES中

Look up move_uploaded_file() and use it in your upload_file.php script: 查找move_uploaded_file()并在您的upload_file.php脚本中使用它:

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() . 对于$ new_filename,您可以使用原始文件名,但是一个好的做法是使用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: 然后,您可以使用readdir查找目录中的所有文件,如下所示:

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.). 如果上载目录属于您的服务器根目录,则可以按服务器查找目录列表(apache,nginx等)。 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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