PHP is back-end and Javascript is front-end.
What PHP does is generate a page, it can be html, txt, image, etc., or it runs on server before reaching your browser, Javassript runs on browser.
Read these responses, although the focus is other things, I explain how the interaction works requisition and reply, recommend you read:
What the server does is send only the answer of what PHP generated to your browser, PHP has already been run and finished, so there is no way Javascript can communicate with PHP unless it is by Ajax (which is a request in "background").
When you do that:
$width = '<script>document.write(width);</script>';
You’re not passing the value of width
for $width
, actually PHP is seeing <script>document.write(width);</script>
and not the value width
.
There is no way PHP can know in the same request the value of the screen size, what you can do is use Ajax, for example:
On your page add this to your page:
<script>
(function ()
{
function enviarTamanhoTela()
{
var querystring = "largura=" + screen.width;
querystring += "&altura=" + screen.height;
var oReq = new XMLHttpRequest();
//envia querystring como se fosse uma página normal
oReq.open("GET", "atualizatamanho.php?" + querystring, true);
//Função assíncrona que aguarda a resposta
oReq.onreadystatechange = function()
{
if (oReq.readyState === 4) {
alert(oReq.responseText); //Pega resposta do servidor
}
};
//Envia a requisição, mas a resposta fica sendo aguardada em Background
oReq.send(null);
}
if (/^(interactive|complete)$/i.test(document.readyState)) {
enviarTamanhoTela();
} else {
document.addEventListener('DOMContentLoaded', enviarTamanhoTela);
}
})();
</script>
And create a new file called atualizatamanho.php
, you can take the data like this:
<?php
if (isset($_GET['largura'], $_GET['altura'])) {
$largura = $_GET['largura'];
$altura = $_GET['altura'];
var_dump($largura, $altura); //Pode remover essa linha
//Resto do seu código aqui
}
What’s that for ?
– Diego Souza
@Zoobooman accurate screen size in a PHP variable.
– Lucas Caresia
Read What’s the difference between client-side and server-side code in web development?
– bfavaretto
But what for? Maybe there are other ways to do what you want.
– Diego Souza
When the server summed the variable in JS did not exist yet, as it is treated in the client
– Douglas Carvalho