在向ajax调用返回成功/错误之前检查该文件是否存在


check that file exists before returning success/error to ajax call

我目前正在做一个项目,这个项目使用ajax调用生成网站内容作为word文档或pdf文件供用户下载——下面是一个简化的演示。

<?php
$errors   = array(); // array to hold validation errors
$data     = array(); // array to pass back data
// initiate array and populate only checked values
$arr      = json_decode($_POST['txtComments']);
$filetype = $_POST['filetype'];
if (!empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $filepath = makePDF($arr);
    // check that the file has been created here....

    $data['success']  = true;
    $data['filename'] = $filepath;
}
// return all our data to an AJAX call
echo json_encode($data);

//Generate PDF file
function makePDF($comments)
{
    require_once('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Write(5, "Hello, World!'n'n'n");
    // Save File
    $file = "../tmp/" . uniqid('comments_') . ".pdf";
    $pdf->Output($file, 'F');
    // Should check that file has been created successfully here....
    return ($file);
}
?>

我的问题是,在创建文件时出现问题的机会不大,我如何检查文件是否已创建,在返回success: path_to_fileerror: error_msg之前?同样值得注意的是,文件不是立即创建的——它需要一秒钟左右的时间才能出现在服务器上,所以我认为这个延迟也需要考虑在内。

如有任何建议,一如既往,我们都很感激。

可以使用file_exists(filepath) PHP函数。该功能可以检查文件或目录是否存在,并相应输出truefalse