Is there any security risks involved if using below code?

$val = $_GET['date'];
$date = new DateTime($val);
  • What are you doing with that $date after that?
    – Vilican
    Jun 25, 2017 at 7:17
  • I am doing this after that: $date->format('Y-m-d H:i:s');
    – MagExt
    Jun 25, 2017 at 19:22

1 Answer 1


If your question is: "are there currently known security issues with PHP that can exploit this?" ... consider the scenario where unexpected input could:

  • make DateTime give out an error or cause an exception that your program isn't handling further down; it could cause wrong output or worse, an HTTP 5xx.
  • someone maintaining this code after you could use the input in ways you didn't do (yes, this can lead to debates about poor programmers / inattention, but hey it happens more often than you think).

There are security risks every time you use untrusted external input in your code directly. Nasty bugs have a way of turning up at most inconvenient times

  • Buffer overflows, especially in widely used software like PHP shouldn't be common, but rarer things have happened.
  • Context escapes could be possible

These don't have to happen with the current version of PHP that you are using / testing with. Where all will your code be deployed? Will older versions or different PHP engines / libraries be used? Will a newer version / engine have an undiscovered bug?

So finally the question will boil down to: What is the compelling reason for you to take this risk - especially when the safer alternative is not expensive (effort or resource-wise)?

  • 1
    I know I can always escape them, but I want to know what worse could happen if left unescaped.
    – MagExt
    Jun 25, 2017 at 19:23
  • Thanks. Totally agree it would lead to 5xx server error, but still site/server would be not at risk of compromise.
    – MagExt
    Jun 25, 2017 at 19:25
  • The opposite, in fact. It would indicate a risk of compromise to defenders. A HTTP 500 that impacts only that user (i.e., not bring the server down for everyone) may not look too bad upfront, but it is the first signal any adversary looks for when attempting injection attacks. A defender's main source of confidence at that point could only be that "it is not exploitable". I would have a tough time being confident of that. :)
    – Sas3
    Jun 26, 2017 at 1:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .