上传,以PHP格式查看PDF

时间:2015-06-04 09:37:09

标签: php mysql pdf

所以我正在为我的网站上传,查看文件,但似乎只有图像和txt文件可以查看,PDF和word文档甚至都没有显示。有人可以告诉我如何更改这个以便我可以在浏览器中查看pdf和word文档?

这是upload.php:

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{    

    $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
    $folder="uploads/";

    // new file size in KB
    $new_size = $file_size/1024;  
    // new file size in KB

    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {
        $sql="INSERT INTO tbl_files(file,type,size) VALUES('$final_file','$file_type','$new_size')";
        mysql_query($sql);
        ?>
        <script>
        alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
        <?php
    }
    else
    {
        ?>
        <script>
        alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
        <?php
    }
}
?>

这是view.php(更新并正在工作):

 <?php
  $file = 'uploads/.pdf';
  $filename = 'yolo.pdf';
  header('Content-type: application/pdf');
  header('Content-Disposition: inline; filename="' . $filename . '"');
  header('Content-Transfer-Encoding: binary');
  header('Accept-Ranges: bytes');
  @readfile($file);
?>

我只需要这样就可以查看任何PDF而无需在代码中使用特定名称:$filename = 'yolo.pdf';

我有一个PDF文件列表供用户查看。单击视图按钮时,是否可以读取数据库中pdf文件的ID并将其存储在将放置在代码中的变量中?这样php将查看特定文件,而无需为每个文件更改代码......

我知道这可能听起来有些混乱,所以任何问题都只是说。

2 个答案:

答案 0 :(得分:1)

首先在表格中添加一个数字自动递增ID:

ALTER TABLE `tbl_files` 
    ADD `id` INT NOT NULL AUTO_INCREMENT FIRST, 
    ADD PRIMARY KEY (`id`) ;

然后使用自动生成的id作为文件名,而不是使用rand(1000,100000)生成随机数。在使用mysql_insert_id

插入后,您会获得此ID

upload.php

// [snip]

// fetch original file extension
$extension = pathinfo($final_file, PATHINFO_EXTENSION);

$allowedExtensions = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"];

// check if the file extension is allowed
if (! in_array($extension, $allowedExtensions))
{
    // report error and abort
}

// use a transaction to rollback the insert 
// in case move_uploaded_file fails
mysql_query("BEGIN");

// insert file into database
$sql = "INSERT INTO tbl_files(file,type,size) VALUES('".mysql_real_escape_string($final_file)."','".mysql_real_escape_string($file_type)."','".mysql_real_escape_string($new_size)."')";
mysql_query($sql);

// fetch generated id
$id = mysql_insert_id();

// move file to $folder and rename it to "$id.$extension"
$fileMoved = move_uploaded_file($file_loc,$folder.$id.".".$extension);

if ($fileMoved)
    mysql_query("COMMIT");
else
    // deletes file entry from the db
    mysql_query("ROLLBACK");

我花时间为你的插入添加转义以防止sql注入。如果可以的话,你真的不应该再使用旧的mysql界面,而是切换到PDOprepared statements

使用ID:view.php?id=1337

提供您的文件
<?php
  $id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);

  if (! $id)
       header("HTTP/1.1 400 Bad Request");

  $result = mysql_query("SELECT * FROM tbl_files WHERE id = ".$id);
  // $id is of type int here, so no sql injection possible

  if (! $result)
       header("HTTP/1.0 404 Not Found");

  $file = mysql_fetch_assoc($result);

  // fetch original file extension or store it the database
  $extension = pathinfo($file["file"], PATHINFO_EXTENSION);

  header('Content-type: application/pdf');
  header('Content-Disposition: inline; filename="' . $file["file"] . '"');
  header('Content-Transfer-Encoding: binary');
  header('Accept-Ranges: bytes');
  @readfile("uploads/$id.$extension");
?>

如果可以直接访问您的文件,您应该出于性能原因使用它:

  // [snip]

  // fetch original file extension or store it the database
  $extension = pathinfo($file["file"], PATHINFO_EXTENSION);

  // relocate to the pdf file to have apache/nginx/whatever 
  // serve the file instead of the php interpreter
  header("Location: uploads/$id.$extension");

对于其他读者:如果您不想授予直接访问权限,但仍然关心性能,则可以使用X-Sendfile来提供文件。 nginx原生提供此功能。对于apache,有一个模块很遗憾没有发货。

修复最终脚本

    <?php
    include_once 'config_db.php';
    if(isset($_POST['btn-upload']))
    {    

        $allowedExtensions = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"];

        $file = $id."-".$_FILES['file']['name'];
        $file_loc = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];
        $file_type = $_FILES['file']['type'];
        $folder="uploads/";

        // new file size in KB
        $new_size = $file_size/1024;  
        // new file size in KB

        // make file name in lower case
        $new_file_name = strtolower($file);
        // make file name in lower case

        $final_file=str_replace(' ','-',$new_file_name);
        $extension = pathinfo($final_file, PATHINFO_EXTENSION);

        // check if the file extension is allowed
        if (! in_array($extension, $allowedExtensions))
        {
            // report error and abort
            echo "<script>", 
                "alert('invalid file extension');",
                "window.location.href='index.php?fail'",
            "</script>";
        }
        else
        {
            $sql = "INSERT INTO tbl_ficheiros(file,type,size) VALUES('".mysql_real_escape_string($final_file)."','".mysql_real_escape_string($file_type)."','".mysql_real_escape_string($new_size)."')";

            mysql_query($sql);

            // fetch generated id
            $id = mysql_insert_id();

            // move file to $folder and rename it to "$id.$extension"
            $fileMoved = move_uploaded_file($file_loc,$folder.$id.".".$extension);

            if ($fileMoved)
            {
                mysql_query("COMMIT");

                echo "<script>", 
                    "alert('successfully uploaded');",
                    "window.location.href='index.php?success'",
                "</script>";
            }
            else
            {
                // deletes file entry from the db
                mysql_query("ROLLBACK");

                echo "<script>", 
                    "alert('error while uploading file');",
                    "window.location.href='index.php?fail'",
                "</script>";
            }
        }
    }
    ?>

答案 1 :(得分:0)

喜欢这个? :

    <?php
    include_once 'config_db.php';
    if(isset($_POST['btn-upload']))
    {    

        $allowedExtensions = ["jpg", "jpeg", "png", "gif", "pdf", "doc", "docx"];
        $file = $id."-".$_FILES['file']['name'];
        $file_loc = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];
        $file_type = $_FILES['file']['type'];
        $folder="uploads/";

        // new file size in KB
        $new_size = $file_size/1024;  
        // new file size in KB

        // make file name in lower case
        $new_file_name = strtolower($file);
        // make file name in lower case

        $final_file=str_replace(' ','-',$new_file_name);
        $extension = pathinfo($final_file, PATHINFO_EXTENSION);
        if(move_uploaded_file($file_loc,$folder.$final_file))
        {
            $sql = "INSERT INTO tbl_ficheiros(file,type,size) VALUES('".mysql_real_escape_string($final_file)."','".mysql_real_escape_string($file_type)."','".mysql_real_escape_string($new_size)."')";
mysql_query($sql);
            mysql_query($sql);
        // fetch generated id
$id = mysql_insert_id();

        // move file to $folder and rename it to "$id.$extension"
$fileMoved = move_uploaded_file($file_loc,$folder.$id.".".$extension);

        if ($fileMoved)
            mysql_query("COMMIT");
            <script>
                alert('successfully uploaded');
                window.location.href='index.php?success';
            </script>
        else
        // deletes file entry from the db
            mysql_query("ROLLBACK");
        }
    }
    ?>