- display browser window width using PHP
- 4 Answers 4
- Description
- Sample
- Getting the screen resolution using PHP
- 22 Answers 22
- Fully Working Example
- Как определить ширину экрана PHP
- Введение
- Пример кода на PHP
- Результат
- Комментарии к коду
- Ваш HTTP_USER_AGENT
- How to determine variable window.width of screen.width to use in php?
- 4 Answers 4
- A way to determine browser width in PHP without javascript?
- 11 Answers 11
display browser window width using PHP
I would like my PHP script to be able to access the width of the browser window. I’ve been reading up on this, and PHP can’t access this information itself, but Javascript/jQuery can, and can then pass it to the server using AJAX, so PHP can get at it.
Following a few solutions online I’ve written the following test file, and called it «test.php»
Loading test.php displays «not set» which shows that the window_width variable is not being picked up by PHP. This seems weird to me, because Firebug shows that the variable is there (set at 1366 on my computer, as this is the width of my browser).
How can I ensure that $_POST[«window_width»] is set so that I can access it using PHP?
4 Answers 4
I don’t think you need to use ajax in this case, the ‘outer’ (?) page needs to receive the data, not the ‘inner’ ajax request.
Description
I dont understand whats you goal ist but it looks like you forgot to wait till the DOM is ready.
Sample
Your server side code doesn’t pause processing to wait for the JavaScript to run. You are dealing with two separate HTTP requests here.
- The browser requests the HTML document
- Since $_POST[‘window_width’] is not set for that request. PHP returns an HTML document that includes the script. Since $_POST[‘window_width’] is still not set for that request, it also echos not set.
- The browser receives the HTTP response and parses it. As part of this process, it runs the JavaScript.
- The JavaScript makes a POST request to … wherever jQuery sends requests to by default since you didn’t include a URI (which a very quick test suggests is the current URI).
- For this request $_POST[«window_width»] is set and included in the document returned to JavaScript.
- Since the JavaScript doesn’t have a success handler (or any other code that runs when the HTTP request comes back) the browser doesn’t do anything with that document.
Ajax is a shorthand way of saying «Talk to the webserver with JavaScript». It doesn’t stop HTTP being a stateless Request-Response protocol.
You haven’t stated your usecase for getting the window width (which can change after the page has loaded), so it is hard to suggest a good solution to whatever problem you have. (You appear to have asked an XY Problem).
The two common reasons for wanting to know the window width are:
- Statistics — in which case you can just process the data in PHP and not worry about rendering it to the client
- Changing the layout — which is usually better achieved with CSS media queries
Getting the screen resolution using PHP
I need to find the screen resolution of a users screen who visits my website?
22 Answers 22
You can’t do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.
Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:
jquery:
PHP (some_script.php)
All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser’s view port since that is actually where the page is rendered.
Directly with PHP is not possible but.
I write this simple code to save screen resolution on a PHP session to use on a image gallery.
PHP is a server side language — it’s executed on the server only, and the resultant program output is sent to the client. As such, there’s no «client screen» information available.
That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height — possibly via AJAX, or more likely with an initial «jump page» that finds it, then redirects to http://example.net/index.php?size=AxB
Though speaking as a user, I’d much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.
I found using CSS inside my html inside my php did the trick for me.
This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.
This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen’s width and height. First go to https://github.com/carhartl/jquery-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:
I have a test that you can execute: http://rw-wrd.net/test.php
Use JavaScript ( screen.width and screen.height IIRC, but I may be wrong, haven’t done JS in a while). PHP cannot do it.
Fully Working Example
I couldn’t find an actual working PHP example to «invisibly» (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.
JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POST ing to itself (the data now available in PHP) and returns the data in a table.
The returned data is extract ‘d into variables. For example:
- window.innerWidth is returned in $windowinnerWidth
You can try RESS (RESponsive design + Server side components), see this tutorial:
I don’t think you can detect the screen size purely with PHP but you can detect the user-agent..
Here’s a link to a more detailed script: PHP Mobile Detect
You can set window width in cookies using JS in front end and you can get it in PHP:
Here is the Javascript Code: (index.php)
Here is the PHP Code: (sqldb.php)
I hope that you know how to get the $userid from the Session, and for that you need an Database with the Table called users, and an Table inside users called screen ;=) Regards KSP
The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.
This can be done easily using cookies. This method allows the page to check the stored cookie values against the screen height and width (or browser view port height and width values), and if they are different it will reset the cookie and reload the page. The code needs to allow for user preferences. If persistant cookies are turned off, use a session cookie. If that doesn’t work you have to go with a default setting.
Как определить ширину экрана PHP
Введение
Часто бывает нужно заранее знать ширину экрана. В CSS за это отвечает тэг @media.
Например, если Вы не хотите показывать блок класса .rightBanner на экранах уже 1000px , Вы просто пишете
И браузер, получив такой CSS от сервера, скроет блок .rightBanner на узких экранах.
Но, что если Вы вообще не хотите отдавать браузеру какой-то контент. Чтобы сэкономить трафик или ускорить загрузку страницы.
Встаёт вопрос — как определить ширину экрана уже на этапе формирования ответа сервера.
Ответ — никак. По крайне мере если Вам нужна точная ширина и Вы не планируете делать финты с AJAX.
Если Вам просто нужно понять зашёл ли посетитель с мобильного устройства или с десктопа — это я покажу ниже
Пример кода на PHP
Результат
Если браузер клиента передал один из упомянутых заголовков, то правый блок вообще не будет ему послан.
Комментарии к коду
preg_match возвращает 1 если найдёт в $_SERVER[«HTTP_USER_AGENT»] один из перечисленных заголовков: android, avantgo, blackberry и так далее.
В таком случае $not_mobile это 0 или FALSE и условие if не выолняется.
Список заголовков наверняка уже устарел, когда Вы читаете эту статью, но, во-первых, Вы сами можете его дополнить. Во-вторых нужны ли все возможные заголовки или достаточно основных решать Вам.
Если Вы не собираетесь использовать функцию повторно, можно ограничиться строчкой:
$not_mobile = !(preg_match(«/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i», $_SERVER[«HTTP_USER_AGENT»]));
Ваш HTTP_USER_AGENT
В следующем блоке вы можете увидеть свой HTTP_USER_AGENT
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19
Проверка — распознал ли скрипт ваше устройство как мобильное или нет
Ваше устройство не распознано как мобильное
Если скрипт неверно распознал ваше устройство — напишите мне в телеграм @andreyolegovichru
How to determine variable window.width of screen.width to use in php?
I need to know the screen size in jQuery or JavaScript and I need this value printed in PHP variable that will determine whether or not an item is displayed.
4 Answers 4
mate, you never get the window width from your php code, php code is executing on your web server, you can only get your window size from javascript which is working on user’s browser, you just need find a way sending the width you got from js to your php code, that’s it !
If you just want to display elements based on the browser width, use CSS media queries and the display:none; property to hide elements.
I think I understand what you are asking but please tell me if I didn’t get it correctly.
An idea that came immediately to mind is where you gather the viewport width and height information as soon as possible and then reload the page but pass the viewport information variables through the URL and receive them in PHP.
Try this code for the suggestion above. Normally, you put your script in an onload function but in this case, you want the dimensions as soon as possible.
The second option is that you can do something complicated with AJAX. The third options is where you can use CSS media queries (as mentioned in the other answer[s]).
A way to determine browser width in PHP without javascript?
First off is there one? Or would I have to use javascript? I’d like to be able to make changes to which CSS is used, so frex I could load smaller fonts for a mobile device, or whatever.
11 Answers 11
There is no way to do this. If you want to detect what device is being used then you should examine $_SERVER[‘HTTP_USER_AGENT’] for clues.
Unfortunately there is no way to detect the users resolution with PHP only. If you use Javascript, you could set this value in a cookie, and all subsequent requests could check the value of that cookie. This seems to be a pretty popular method for those working with this issue.
You could also run a small javascript from the page that checks to see if a resolution-cookie is set. If it’s not, it sends an asynchronous request to the server containing the screen resolution. The server determines which CSS file to use by this value, and sends its path back to the javascript. A cookie is then set to indicate resolution has been determined, and the css file is subsequently loaded (via javascript) into the page. All future requests would cease assuming they’re contingent upon the resolution cookie.
Pure HTML and CSS trick to get the width of the display. This will get you within 10 pixels. It highlights in red down to the display width. The first black on white number should be the display width:
You can use $_SERVER[‘HTTP_USER_AGENT’] by using the following code:
Code:
Output
If tablet: ‘is tablet’
If mobile: ‘is mobile’
If desktop: ‘is desktop’
This may be of some use if you don’t want to use any JavaScript:
The best way to do it, is to use CSS with media types
Here I give you a example for what you want, i.e., it adapts the fonts size for many tags, and the divs[1,2,3] orientation (horizontal or vertical), depending on the browsers width
I use here ‘p5’ tag with a greater font than ‘p4’
use it preferably within a css external style file
The solution I have has actually worked real well for years now — no plugins, no classes. Basically, while outputting the HEAD part of the doc, I output some JavaScript that gets the browser width and writes it to a cookie. Then, later, further down the page, I simply read the cookie that has the exact width stored using the $_COOKIE function in php. It has not failed me once in any scenario.
You should look at Tera-WURFL, it is a PHP & MySQL-based software package that detects mobile devices and their capabilities. Here is the Tera-WURFL code that you would use to detect the browser width in PHP:
About all you can do is detect the browser model. From there you could match for common mobile browsers (iPhones all stick iPhone into the useragent string) and load smaller fonts by default and adjust from there.
Take a look at WURFL.
As Ignacio Vazquez-Abrams suggested in his answer, it uses the user agent string to «guess» the resolution for known devices. If you’re concerned about mobile devices that’s probably as accurate as you can get without the help of a client-side script/app.
You will have to use JavaScript. The server knows nothing about highly client-side data like that. Fortunately, JavaScript can manipulate styles and style sheets quite easily, so it should be able to tackle your problem without even involving anything server-side.
In the case of mobile devices, another easy tool is setting the media type on a style sheet to handheld.