Reputation: 9074
I am generating PDFs and emailing it to users , on my website dynamically using FPDF. But the name of the PDFs generated contains slashes and plus signs ( + , / , \ , [ , ] ) etc. due to which the following error occurs :
fopen:( Unable to find the file or directory )
as soon as I remove the slashes and braces , the PDF is generated successfully and emailed too.
Need a solution to deal with the file-names? The filenames are created dynamically , so it is not in my hand to change them ? So I think I need to first strip off all those special characters from the PDF file name and then send it to FPDF output. But how to do this ?
Upvotes: 0
Views: 633
Reputation: 10074
You can urlencode
:
file_put_contents(urlencode('asd#$%21234 /&11 /!@##$$%&&*()_'), 'test');
But then you get strange chars.
Or you just can strip and leave allowed chars
file_put_contents(preg_replace('/[^A-Za-z0-9_\-]/', '','asd#$%21234 /&11 /!@##$$%&&*()_'), 'test');
Upvotes: 2
Reputation: 154553
OWASP ESAPI4PHP library has some very decent sanitizers for file names and other types data.
See also comparison of filename limitations.
Upvotes: 1
Reputation: 746
I think that slashes cannot be used in file name because it is also used to determine file path. For instance a file nammed foo/bar.php is actually a file named bar.php but in foo folder.
A workaround may be to first create foo directory. Then when you ask for "foo/bar.php" file, you'll get bar.php file from foo directory (not tested).
Or you can remove all unwanted characters. For my projects I use this to "normalize" text:
$string = preg_replace('#[^a-z0-9]+#', '-', $string);
Upvotes: 1