mike mike - 3 months ago 15
PHP Question

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

I'm working on a project at the moment that uses an ajax call to generate site content as a word document or pdf file for the user to download - a simplified demonstration is posted below.

$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)
$pdf = new FPDF();
$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);

My question is that on the off-chance that something goes wrong with creating the file, how can I check if the file has been created, before returning either
success: path_to_file
, or
error: error_msg
? It's also worth noting that the file isn't created instantaneously - it takes a second or so to appear on the server, so I'd presume that this delay will need to be taken into account too.

Any suggestions, as always, are appreciated.


You can use file_exists(filepath) PHP function. This function allows you to check if file or directory exists or not and output true or false accordingly.