Pass Javascript variable value to a php variable

I have a piece of php code:

....
for ($i=0; $i < count($files); $i++) { $rows = array_chunk($files, 5); }
....

Where I want to have the chunk length ???5??? as dynamic (to display items different way in different view port width), accordingly to the visitor??�s browser??�s view port width. Exmpl:

if view port >= 800px ??� the chunk length = 5

if view port >= 680px ??� the chunk length = 4

etc??�

I know that I need to get the view port size (width) via Javascript and I know how to dial with that part, but all the problem is to pass that value to a php variable to implement it in that piece of code.

So I need to use GET or POST method, I tried several ways, but I can??�t make it work really. Maybe I need to create a page loading at first, to do this calculation and redirecting then user to the main page with that value in a PHP variable or something like this?.

Answer

Solution:

These kind of things should be done always with CSS and Javascript. PHP has no connection to these components. PHP is "static" while your viewport (width and height) are dynamically.

If you insist on doing it anyway then the following solution:

  1. read data via JavaScript (keyword "SelfHTML Document height" or "SelfHTML Window height")
  2. when you have the data, you pass the data
    • via $_POST and hidden input fields
    • via $_GET parameter or
    • via Ajax

The parameters you send to your PHP script can then be used.

But now again why you should not do it:

Problem A: I call your website, your PHP has received all possible data, has built me a layout, now I change the size, your PHP script has not noticed anything, and I have problems with the operation of your page.

Problem B: The values can open an unwanted security vulnerability, so I could pass e.g. as width or height or other information in the worst case a script via these parameters to infiltrate your server, ie you must ALWAYS validate these values.

Source