-2

I'm having a struggle with the php code below

<?php
$list = 0;
$screenWidth = '<script 
type="text/javascript">document.write(screen.availWidth);</script>';

if($screenWidth > 700){
   $list = 1;
}

echo $screenWidth; 
?>

The echo is printing the value of $screenWidth (screen width) correctly.

So it means the js works and is assigning the value from screen.availWidth to $screenWidth correctly but somehow $list is always 0 ! Even when the screen width is 1920

Thanks for your help!

Ceco

  • 6
    You reallize that php runs on server and JS in user browser window? – dfsq May 13 '17 at 17:29
  • JS is client side, PHP is only on the server. https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming – chris85 May 13 '17 at 17:29
  • yes, so ? echo prints correctly – Tzvetan Jordanov May 13 '17 at 17:30
  • Your variable is always the literal ``, it is never the integer that JS returns. – chris85 May 13 '17 at 17:31
  • PHP is used on the server to generate HTML. When it is done, server sends it to your broweser and **the php process gets killed**. And only then Javascript code runs on your web-browser. – tereško May 13 '17 at 17:31
  • Maybe this thread is useful http://stackoverflow.com/questions/1504459/getting-the-screen-resolution-using-php – chris85 May 13 '17 at 17:32
  • So how to do it then ? Thanks for your help! – Tzvetan Jordanov May 13 '17 at 17:32
  • No real/best way to do it. Only hack would be for javascript to store data in cookie and php reading data from cookie but, not the best. http://stackoverflow.com/questions/21620133/how-to-assign-javascript-variable-value-to-php-variable – Robert Rocha May 13 '17 at 17:36
  • Anyway I didn't understand why echo is printing the correct value and why I cannot convert it to integer – Tzvetan Jordanov May 13 '17 at 18:04

1 Answers1

0

Your code doesnt echo the Screen width, it echoes the js:

echo '<script  type="text/javascript">document.write(screen.availWidth);</script>';

And on client side, this JS runs and prints out the screen width ( document.write).

However, as $screenWidth is a String, comparing it to 700 is not really working...

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • Ok I understand that my code prints the js output of screen.availWidth and it is a string but normally we can (int)$string ... I don't know ... Guys, do you understand what I am asking ? Why echo prints the value of $screenWidth which is the js output screen.availWidth but cannot convert it to integer and compare it to let say 700 – Tzvetan Jordanov May 13 '17 at 18:20