Good question: is PHP date formatter safe from SQL injection?
I assume the starting point is the hard-coding format according to your example. A date format string allows you to include raw characters in a formatted date that may contain unsafe characters, so if you use a variable for a format string, then the answer is definitely “No”, it is unsafe.
If you use a hard-coded format, as in the example you specified, then this is a more complicated question, but it boils down to “Can the output of DateTime::format ever deviate from the desired format?”
The answer to this question is: “Yes, it can - it can print false if it fails. It will not destroy your SQL, but may give you unexpected results.
In theory, this should be as bad as it gets.
However, you must think about protection. Needless to say, a subtle error will not be detected in the DateTime class, which will cause it to output a poorly formatted date. Typically, this error is not considered a security issue; that would be just annoyance. Especially if it is difficult to reproduce under normal use. But combined with passing it directly to SQL, this can easily be a security issue.
The lesson is defensive programming: sanitize everything. Even if you are sure that it is safe. Do not assume that your language or framework is error free. Defensive programming means being protected at every level, so an unexpected error in the program or out of your control cannot leave your code open to attack.
Sdc
source share