DateTime::__construct(): Failed to parse time string - php

I configured redmine with my website for handling exceptions. Now when website is on production environment I have strange exception.
StackTrace:
An exception has been thrown during the rendering of a template ("DateTime::__construct(): Failed to parse time string (date) at position 0 (d): The timezone could not be found in the database") in "ToFrontendBundle:Page:cruise-periodic.html.twig" at line 8.
#95: To\FrontendBundle\Controller\PageController->cruisePreviewAction(8, way, date)
#106: Symfony\Bundle\FrameworkBundle\Controller\Controller->render("ToFrontendBundle:Page:cruise-periodic.html.twig", array)
#112: Symfony\Bundle\TwigBundle\TwigEngine->renderResponse("ToFrontendBundle:Page:cruise-periodic.html.twig", array, NULL)
#83: Symfony\Bundle\TwigBundle\TwigEngine->render("ToFrontendBundle:Page:cruise-periodic.html.twig", array)
#53: Symfony\Bridge\Twig\TwigEngine->render("ToFrontendBundle:Page:cruise-periodic.html.twig", array)
#4423: Twig_Template->render(array)
#4416: Twig_Template->display(array)
#4446: Twig_Template->displayWithErrorHandling(array, array)
But, I handle exception like:
try {
$date = new \DateTime($date);
$date = $date->format('j-n-Y');
} catch (\Exception $e) {
$date = new \DateTime("now");
$date = $date->format('j-n-Y');
$first = false;
}
My cruise-periodic.html.twig:
<span class="padding-left-10 light-green text-14 selected-date" data-date="{{ date | date('j/n/Y') }}">{{ date | toDateFormat }}</span>
What I do wrong?
EDIT
Someone is causing the exception but i cannot tell how. I cannot manually test this situation. String variables "date" and "way" are replaced in js. Possibly that someone is finding the dom href and invoking it blindly. Could it be robots or bots ? How I can prevent them from accessing this action?

I meant try to execute next code:
try {
$date = new \DateTime('2010-10-10');
$date = $date->format('j-n-Y');
} catch (\Exception $e) {
$date = new \DateTime("now");
$date = $date->format('j-n-Y');
$first = false;
}
Is it also catch this exception or it work?

Related

Memory Usage on Fatal Error, should I Try Catch every line?

What happens exactly on a PHP fatal error regarding memory usage and object destruction? Does memory automatically get freed on a fatal error?
I really would like to know more about the subject, and couldn't find it in the PHP manual.
Should I worry about Try{}catch{} my functions so I can destruct my objects in the catch{} or does it happen automatically ? Is it instant ?
Added Example:
$objectOne = new stdClass();
$objectOne->statement = "Hello";
$objectTwo = new stdClass();
randomFunctionThatShouldCauseAnError();
$objectTwo->statement = "Error before this";
In the above axample, will $objectOne be freed automatically on the error caused by randomFunctionThatShouldCauseAnError ? or I should do the following:
$objectOne = new stdClass();
$objectOne->statement = "Hello";
$objectTwo = new stdClass();
try{
randomFunctionThatShouldCauseAnError();
}catch (Error $e){
$objectOne = null;
$objectTwo = null;
}
$objectTwo->statement = "Error before this";
Sorry for the spam of questions, but I've been struggling with this for a while now, and I would like to know how to handle memory in case of a fatal error in my code.
Thanks a lot!
Should I worry about Try{}catch{} my functions so I can destruct my objects in the catch{} or does it happen automatically ? Is it instant ?
You should catch the exceptions if you want to keep the code running, otherwise you can easily have unexpected behavior from your program.
If you do not catch an exception, a fatal error can be thrown and stop your code execution and, consequently, the OS will dump anything from memory.
Also you should take care not to expose sensitive information (i.e. An PDOException can throw your SQL password to user's screen).
Try this:
<?php
class Test {
public $param;
public function canThrowAnError() {
$this->param = "Changed right before the exception";
if (true) {
throw new \Exception("Message", 10023);
}
}
}
And then
$test = new Test();
$test->param = "Yay, it works still...";
try {
$test->canThrowAnError();
} catch (\Exception $e) {
// Do something. Log, inform the user..
}
echo $test-param;
If you catch the exception the code will go on and everything will be as right before the exception. The following will result in:
"Changed right before the exception"
You should treat the error accordingly so you don't have unexpected behavior.

Can I avoid `DateTime::__construct` warning on invalid date?

This is about DateTime::__construct. According to this comment:
If time cannot be parsed an exception of type Exception is thrown which can be caught, however an E_WARNING is emitted as well. This might be confusing if you are converting warnings to exceptions in your error or shutdown handler.
Can I avoid the warning? I have a code like (I don't care if the date is well formed or not):
try {
$var = new DateTime('some invalid date format');
} catch (Exception $exception) {
$var = null;
}
But it still send a E_WARNING that is reported to my error catcher (I use NewRelic in a Laravel application). And I don't want this error to be reported because it's not an error, I catched it.
How can I avoid DateTime::__construct emit a warning?
This is possibly one of the few cases where it's acceptable to use:
try {
$var = #new DateTime('some invalid date format');
} catch (Exception $e) {
$var = null;
}
However you can avoid the # operator by doing:
try {
$oldErrorReporting = error_reporting();
error_reporting($oldErrorReporting & ~E_WARNING);
$var = new DateTime('some invalid date format');
error_reporting($oldErrorReporting);
} catch (Exception $e) {
$var = null;
}
Use the date_create() function instead.
It (I assume) internally works similar to the try/catch block you want to avoid and returns FALSE if the date is not valid. It doesn't trigger any error or warning.
The code:
$var = date_create('some invalid date format');
is, more or less, the same as:
try {
$var = new DateTime('some invalid date format');
} catch (Exception $exception) {
$var = false;
}
You should create an error handler like this:
//set_error_handler();
set_error_handler(function($msg, $code, $severity, $file, $lineno, $errText) {
if (0 === error_reporting()) {
return false;
}
throw new ErrorException($msg, $code, $severity, $file, $lineno);
});
Then,
try {
$var = new DateTime('some invalid date format');
} catch (ErrorException $exception) {
$var = null;
}

Error even when using a Try/Catch block in PHP

I have a Laravel/PHP application with the following code:
try {
//gets the day of the last record for logged in user
$lastRecord = $user->records()->orderBy('date', 'DESC')->first()->date;
//convert to date
$lastTime = \Carbon\Carbon::createFromFormat('Y-m-d', $lastRecord);
}
catch(Exception $e) {
$lastTime = \Carbon\Carbon::now($user->timezone)->addDays(-1);
}
but I still get the error:
ErrorException in Habit.php line 104:
Trying to get property of non-object
Now I'm confused.. The main idea was to fail sometimes, and then continue to the catch block. How come it's still raising an error?
Just a guess, but try this instead
try {
//gets the day of the last record for logged in user
$lastRecord = $user->records()->orderBy('date', 'DESC')->first()->date;
//convert to date
$lastTime = \Carbon\Carbon::createFromFormat('Y-m-d', $lastRecord);
}
catch(\Exception $e) {
$lastTime = \Carbon\Carbon::now($user->timezone)->addDays(-1);
}
That is, add a leading namespace separator in front of Exception. My guess is you're using this code in a namespaced file. When you do something like this
namespace App\Some\Somenamespace;
...
catch(Exception $e) {
...
PHP assumes you want to catch an exception with the name App\Some\Somenamespace\Exception. Since that's not the exception thrown, and there's no second catch for the global PHP \Exception, PHP complains about an uncaught exception. You'll want to explicitly refer to the exception as global
catch(\Exception $e) {
or import it into the current namespace
namespace App\Some\Somenamespace\;
use Exception;
...
catch(Exception $e) {
...
FWIW, I still do this all the time. Old habits are hard to break.
The exception says that you are accessing a property of a non-object. This means that either $user itself or one of the properies in chain does not exist. It may be possible to avoid this by checking return values.
But if you still want to catch the fatal error, you may install a global shutdown handler, like this:
register_shutdown_function( "shutdown_handler" );
function fatal_handler() {
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$error = error_get_last();
if( $error !== NULL) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
error_mail(format_error( $errno, $errstr, $errfile, $errline));
}
}
taken from this SO post and this SO post.

How to check for a failed DateTime in PHP?

When the following gets bad data PHP aborts.
PHP Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (980671) at position 4 (7): Unexpected character'
How can I catch this if the data is bad to take other action so the PHP problem doesn't fail?
$date = new DateTime($TRANSACTION_DATE_MMDDYY_raw);
Use try and catch
try {
$date = new DateTime($date);
} catch(Exception $e) {
echo "Invalid date... {$e->getMessage()}";
}
As #Rob W already said, you gotta catch that exception.
But what could cause that exception is inaproppriate datetime format.
To solve this, you could do instead:
try {
$dt = DateTime::createFromFormat("MMDDYY", $TRANSACTION_DATE_MMDDYY_raw) ;
} catch(Exception $e){
echo "Something went wrong: {$e->getMessage()} " ;
}
More about it: http://www.php.net/manual/en/datetime.createfromformat.php

PHP exception handling on DateTime object

Does anybody know why this function, when passed an invalid date (e.g. timestamp) to it, still throws an error despite the try-catch?
function getAge($date){
try {
$dobObject = new DateTime($date);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
}
catch (Exception $e) {
echo 'Error: ', $e->getMessage();
}
return $diff->y;
}
Error:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::_construct() [datetime.--construct]: Failed to parse time string (422926860) at position 7 (6): Unexpected character' in ... .php:4 Stack trace: #0 ... .php(4): DateTime->_construct('422926860') #1 ... .php(424): getAge('422926860') #2 {main} thrown in/... .php on line 4
Thank you very much in advance!
Chris, you cannot catch fatal errors, at very least you shouldn't.
Quoting keparo:
PHP won't provide you with any conventional means for catching fatal errors because they really shouldn't be caught. That is to say, you should not attempt to recover from a fatal error. String matching an output buffer is definitely ill-advised.
If you simply have no other way, take a look at this post for more info and possible how-tos.
Try this:
function isDateValid($str) {
if (!is_string($str)) {
return false;
}
$stamp = strtotime($str);
if (!is_numeric($stamp)) {
return false;
}
if ( checkdate(date('m', $stamp), date('d', $stamp), date('Y', $stamp)) ) {
return true;
}
return false;
}
And then :
if isDateValid( $yourString ) {
$date = new DateTime($yourString);
}

Categories