1
votes

I am trying to get the browser timezone via JavaScript and capture it in a php variable with ob_start() and ob_get_clean. The value set by ob_get_clean shows as a string, but when I try to cast it to an int in php, the value goes to 0.

It doesn't matter how I cast this string, (int) $offset or intval($offset) or $offset * 1 the string starts as 420, but the result of casting it to an integer changes the value to integer 0.

<?php
    ob_start();
?>

<script>
    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>

<?php
     $offset = trim(ob_get_clean());  // timezone offset Colorado = 420 minutes
     echo $offset;  // 420
     echo gettype($offset); // string
     $offset += 0;
     echo gettype($offset); // integer
     echo $offset; // shows 0 - I expect the value to be 420

I expect $offset to be an integer with a value of 420. Now it I try similar code with a regular string, I get the expected results.

$strnum = '530';
echo gettype($strnum);  // string
$strnum += 0;
echo gettype($strnum);  // integer
echo $strnum;  // 530
?>

I can't see why the two examples don't work the same.

3
Have you try this $offset = (int)trim(ob_get_clean());Jigarb1992

3 Answers

2
votes

You can't to this, you can't catch the JS script output in php, you need to pass it throught ajax call. Check the SOURCE OUTPUT of the page and not the screen output.

screen output (in my case):

-60 string integer 0 

REAL OUTPUT (SOURCE):

<script>
    var d = new Date();
    document.write(d.getTimezoneOffset());
</script>
string
integer
0
0
votes

why u not use cast (int) or intval() function

example :

$var = (int) $yourstring

OR

$var = intval($youtstring)
0
votes

Try this out

 $offset = 'timezone offset Colorado = 420 minutes';  
 preg_match_all('!\d+!', $offset, $matches);
 echo $offset;  // 420
 print_r( $matches); //array
 echo $matches[0][0]; //420

 $matches[0][0] += 1;

 echo $matches[0][0];