Search code examples
phpjoomla

PHP - is_file says file does not exists but it does


I'm trying to get 3 pdf files attached to an email, the problem I have is that is_file gives a false on the first two files but the third file it works. The files come from a textbox and are exploded like this:

$pdfs = explode("\n", $string);

And I put it in a foreach loop to attach to an email like this:

foreach($pdfs as $pdf) {
        if (is_file(JPATH_ROOT . $pdf)) {
            $mail['attachment'][] =
                array('name' => basename($pdf), 'file' => JPATH_ROOT . $pdf);
        }
    }

When I run this code I only get the third pdf file attached, however if I remove the is_file() they are in the array but won't attach to the sent email. So the results then are:

[attachment] => Array
    (
        [0] => Array
            (
                [name] => pdf_file_1.pdf
                [file] => /home/psinke/domains/*****/public_html/pdf_file_1.pdf
            )

        [1] => Array
            (
                [name] => pdf_file_2.pdf
                [file] => /home/psinke/domains/*****/public_html/pdf_file_2.pdf
            )

        [2] => Array
            (
                [name] => pdf_file_3.pdf
                [file] => /home/psinke/domains/*****/public_html/pdf_file_3.pdf
            )

    )

But the first two files do not attach to the sent email.


Solution

  • Likely the line break that separates those entries in your input data is not just \n ... so you might have left a \r at the end of the first two, which of course makes PHP not find those files.

    The third file won’t have this problem, because likely after that line there is no more line break.

    The files come from a textbox

    Assuming you mean an HTML textarea element - all modern browsers send \r\n for a line break in a textarea - so if you only get your content from there, exploding at "\r\n" should work. If you are not sure about the exact line break format used beforehand, you can also use a preg_split solution as shown here, https://stackoverflow.com/a/36851287/1427878