1

In this case works:

$var = "05/20/2016 12:00";
echo gettype ($var);
$ini = strtotime($var)*1000;

But when I use javascript variable and although both are format string it returns zero. Why?

$var = "<script>document.write(date)</script>";
echo gettype ($var);
$ini = strtotime($var)*1000;
Bibi
  • 33
  • 1
  • 1
  • 10

1 Answers1

1

PHP is being compiled first on the server, you are assuming that

$var = "<script>document.write(date)</script>";

is resolving to something like $var = "05/20/2016 12:00"; but it isn't because the javascript compiling doesn't kick in until the output has reached the client.

You're passing the literal string "<script>document.write(date)</script>" to PHP's strtotime() function, hence returning a zero.

If you echo $var prior to echo gettype($var) you'll see exactly what is being passed to strtotime.

var_dump() is even better for debugging the current value of a variable.

$var = "<script>document.write(date)</script>";
var_dump($var)
echo gettype ($var);
$ini = strtotime($var)*1000;
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
GreensterRox
  • 6,432
  • 2
  • 27
  • 30
  • 1
    The problem with both `echo` and `var_dump` here is that they will dump a valid HTML script tag to the browser, which will show as nothing (except maybe an error because `date` is undefined) – Niet the Dark Absol May 20 '16 at 14:56
  • @NiettheDarkAbsol: Maybe something like `echo htmlspecialchars($var);`? – gen_Eric May 20 '16 at 14:58
  • 1
    The beatuty of `var_dump` is that it tells you the **length** of the variable too, so if it looks blank but says the string is 44 characters long you know that something is being hidden. Also, using the browsers 'view_source' will expose the true raw string. – GreensterRox May 20 '16 at 15:04