PHP echo文件内容

时间:2011-07-01 22:25:42

标签: php file pdf

我有一个pdf文件,位于我的网页根目录下。我想使用php将../cvs中的文件提供给我的用户。

以下是我所熟悉的代码:

header('Content-type: application/pdf');

$file = file_get_contents('/home/eamorr/sites/eios.com/www/cvs/'.$cv);
echo $file;

但是当我打电话给这个php页面时,什么都没打印出来!我想简单地提供存储名称为$cv的pdf文件(例如$cv = 'xyz.pdf')。

对这个PHP页面的ajax响应返回pdf(gobbldy-gook!)的文本,但是我想要文件,而不是gobbldy-gook!

我希望这是有道理的。

非常感谢,


这是我正在使用的AJAX

$('#getCurrentCV').click(function(){
    var params={
        type: "POST",
        url: "./ajax/getCV.php",
        data: "",
        success: function(msg){
            //msg is gobbldy-gook!
        },
        error: function(){

        }
    };
    var result=$.ajax(params).responseText;
});

我希望提示用户下载文件。

4 个答案:

答案 0 :(得分:11)

不要使用XHR(Ajax),只需链接到下面的脚本即可。脚本输出的HTTP标头将指示浏览器下载文件,因此用户不会离开当前页面。

<?php
// "sendfile.php"

//remove after testing - in particular, I'm concerned that our file is too large, and there's a memory_limit error happening that you're not seeing messages about.
error_reporting(E_ALL);
ini_set('display_errors',1);

$file = '/home/eamorr/sites/eios.com/www/cvs/'.$cv;

//check sanity and give meaning error messages
// (also, handle errors more gracefully here, you don't want to emit details about your
//  filesystem in production code)
if (! file_exists($file)) die("$file does not exist!");
if (! is_readable($file)) die("$file is unreadable!");

//dump the file
header('Cache-Control: public'); 
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="some-file.pdf"');
header('Content-Length: '.filesize($file));

readfile($file);

?>

然后,简化您的javascript:

$('#getCurrentCV').click(function(){
     document.location.href="sendfile.php";
});

答案 1 :(得分:2)

如何使用readfile呢?如果该文件存在,那应该工作。确保您的Web进程有权读取目录和文件。 readfile页面上有一个示例,它也设置了一些标题。

答案 2 :(得分:2)

  

我正在尝试提示用户下载pdf文件。

您不能(也不需要)使用Ajax将二进制下载发送到用户的浏览器。您需要将用户发送到PDF所在的实际URL。

使用@ timdev的代码,并使用例如

指向用户
location.href = "scriptname.php";

答案 3 :(得分:2)

听起来你正试图通过AJAX向用户提供pdf服务。

你想要做的是使用AJAX来确认文件是否存在,以及安全性(如果有的话),然后只需使用js将浏览器重定向到该文件url,或者在这种情况下是提供pdf的php脚本的url。当您的浏览器获得pdf标题时,它不会尝试重定向页面本身,但会提示下载,或者无论用户的浏览器设置是什么。

像: (JS)

window.location.href = http://example.com/getApdf.php?which=xyz

(PHP)

if( !isset( $_GET['which'] ) ) die( 'no file specified' );
if( !file_exists( $_GET['which'] . '.pdf' ) ) die( 'file doesnt exist');

header('Content-type: application/pdf');

readfile( $_GET['which'] . '.pdf' );
相关问题