PDA

View Full Version : This must be a simple one


arabab
05-03-2007, 08:32 PM
Hi guys, I'm a NEWBIE :o and I had a simple question. I've been trying to get the screen resolution using javascript and store it in a php variable, but so far I've been unable to do so. The following has been my approach:

$resolution = <script type=\"text/javascript\">document.write(window.screen.width + ' x ' + window.screen.height);</script>;

echo "$resolution";



Resulting page: blank

Please note that I am not trying to just report the screen resolution in which case I woudn't need to use php. I am trying to store it in a variable so that I can do with it whatever I want, later, like write it to a file, etc.

Thanks in advance.

iLLin
05-03-2007, 08:40 PM
Can't be done like that. JavaScript is client side, php is server side. You can include php variables into you javascript, but you can't include javascript variables into your php code.

Fumigator
05-03-2007, 08:42 PM
It is simple, once you understand how PHP works (http://us.php.net/manual/en/getting-started.php). It does not interact with the browser or Javascript in any way; you are assigning a string to a variable in PHP, which means nothing to PHP, and then sending the results to your browser. Once the browser gets it, it will process it just like an ordinary HTML page with Javascript in it.

SOoo.... the way to get the screen resolution to a PHP variable? Write the page out to a browser, put the screen resolution values in a form's hidden input fields, submit the page to itself, and read the $_POST variables from the form. You can use the onload() Javascript event to submit the form.

It is possible to use Ajax to get Javascript to make a "pass" over to PHP and back, but you should understand how PHP works before attempting that.

CFMaBiSmAd
05-03-2007, 08:49 PM
Here is a working example from the PHP manual that shows how to get the screen width and height into a php script - http://www.php.net/manual/en/faq.html.php#faq.html.javascript-variable

I have used a modification of this to get the visitors PC time into a php script.

arabab
05-03-2007, 08:57 PM
You guys are absolutely right. How stupid of me to try to do something like that. This just never crossed my mind. Javascript is executed after it is downloaded by the browser by which time php is done being processed on the server. Only the resulting page is sent to the browser. Anyways, thanks a lot for clarifying that. By the way, I like the "hidden input" approach. I'll definitely try it. Thanks again.