-2

I am using the simple tag below to get the screen width.

$DeviceTypeWidth = "<script>document.write(screen.width);</script>";

if($DeviceTypeWidth >= 1000){
echo 'Above 1000';
}else{
  echo 'Below 1000';
}

However no matter what I try the always triggers the ELSE value regardless of screen size.

Thanks

I have tried all manner of things

  • That's because `$DeviceTypeWidth` is a simple string, and it won't give you the screen width. You can't get the screen width with PHP. Try searching the site for solutions, [like here](https://stackoverflow.com/questions/1504459/getting-the-screen-resolution-using-php) – tola May 05 '23 at 13:34
  • This code makes no sense. JavaScript code doesn't execute until it reaches the browser. That happens after the PHP script has finished (because the output of the PHP script is the content which is sent to the browser as the page). PHP runs on the server, JS runs in the browser. They are completely separate languages, with completely separate runtimes, executing in completely separate contexts, and usually on completely separate computers. They don't interweave in the way you seem to have imagined here. – ADyson May 05 '23 at 13:37
  • In fact, PHP doesn't even know whether the place it's outputting the data to is even a web browser - the client could just as easily be a bot, or a tool like Postman, or a command-line script, or anything else. It just echoes exactly what it's told to echo, and then stops. So it cannot possibly directly receive the result of that document.write command. The output of `document.write` ends up _in the browser_, not in PHP. – ADyson May 05 '23 at 13:39
  • Have a good read of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) and try and get the concept clear in your mind. It's vital that you understand the structure and lifecycle concepts if you want to write web applications (or any other kind of application with a disconnected, (optionally stateless) client-server architecture). – ADyson May 05 '23 at 13:40
  • Anyway, why would PHP even need to know or care about screen width? I can't think of a use case for that. What was your overall intention here? If you want to make your web page show differently depending on the screen size, then you should learn about Responsive Design with HTML and CSS. If done properly, that wouldn't even require any JS code in the vast majority of cases, let alone server-side PHP. – ADyson May 05 '23 at 13:41

1 Answers1

1

Hm, it feels like you are in PHP (backend) when writing your code?

But, going for a general answer: Don't ever use document.write (it's deprecated since many years back).

Do something like:

function getScreenWidth() {
  console.log(window.innerWidth);
  return window.innerWidth;
}

getScreenWidth();
window.addEventListener('resize', getScreenWidth);
Thomas Frank
  • 1,404
  • 4
  • 10