在 PHP 中获取 Javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18527781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:17:12  来源:igfitidea点击:

Get a Javascript variable in PHP

phpjavascriptvariablesiframe

提问by MM PP

I have a simple javascript code, that tells me if my website is in iframe.

我有一个简单的 javascript 代码,它告诉我我的网站是否在 iframe 中。

<script>
if ( window.self === window.top ) { 
    var iframe = '0';
} else { 
    var iframe = '1';
}
</script>

How can I get the "iframe" variable from javascript, in php?

如何在 php 中从 javascript 获取“iframe”变量?

I want to do something like this:

我想做这样的事情:

<?php if ($iframe == "0") {
 //mysite for iframe
} else {
 //mysite general
}
?>

Is this possible?

这可能吗?

PS.: I want to be SEO, too.

PS.: 我也想当 SEO。

Thank you so much!!!

太感谢了!!!

回答by PherricOxide

PHP is server side, Javascript is client side. You'll have to do something like Ajax to transfer the value from the web browser (Javascript) to the web server (PHP).

PHP 是服务器端,Javascript 是客户端。您必须执行类似 Ajax 的操作才能将值从 Web 浏览器 (Javascript) 传输到 Web 服务器 (PHP)。

回答by nl-x

Since the order is:

由于顺序是:

-first parse PHP and send HTML to client
-then client runs Javascript that is in HTML

- 首先解析 PHP 并将 HTML 发送到客户端
- 然后客户端运行 HTML 中的 Javascript

to do what you want will take multiple requests.

做你想做的事将需要多个请求。

What you could do is:

你可以做的是:

-Load an HTML page that uses Ajax (a second request) to send the javascript variable to the server. The server then responds to the Ajax request with XML, and javascript should already know what to do with the answer.
-Load an HTML page that directly refreshes itsself, but sends along the javascript variable as a request variable (POST or GET). Something like:

- 加载一个 HTML 页面,该页面使用 Ajax(第二个请求)将 javascript 变量发送到服务器。然后服务器用 XML 响应 Ajax 请求,javascript 应该已经知道如何处理响应。
- 加载一个直接刷新自身的 HTML 页面,但将 javascript 变量作为请求变量(POST 或 GET)发送。就像是:

<?php
    if (!isset($_REQUEST['iframe']) { // php checks if this it got the variable
        // it is not given yet, so let javascript refresh and give the variable
?>
        <script>
            var url = window.location.href.split('#')[0];
            var devider = url.indexOf('?') == -1 ? '?' : '&';
            var hash = typeof window.location.href.split('#')[1] == 'undefined' ? '' : '#' + window.location.href.split('#')[1];
            if ( window.self === window.top ) {
                window.location.href = url + devider + 'iframe=0' + hash;
            } else { 
                window.location.href = url + devider + 'iframe=1' + hash;
            }
        </script>
<?php
    } else {
        // it is given to php, lets do something with it...
        if ($_REQUEST['iframe'] == 1) {
            // ok, we're in an iframe. So what do you want to do?
        } else {
            // ok, we're not in an iframe. So what do you want to do?
        }
    }
?>

回答by NETCreator Hosting

You can simple use:

您可以简单地使用:

<script>
    if ( window.self === window.top ) { 
            window.location = window.location + '?iframe=0';
    } else { 
            window.location = window.location + '?iframe=1';
    }
</script>

You said that you want to be SEO too, so you can put a canonical link rel in <head></head>:

你说你也想成为 SEO,所以你可以放一个规范链接 rel <head></head>

<?php
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$canonical = 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
?>

 <link rel="canonical" href="<?php echo $canonical; ?>"/>

回答by Iesus Sonesson

As Javascript is client side code and PHP is Server side code, the variables must somehow be passed to the server.

由于 Javascript 是客户端代码而 PHP 是服务器端代码,变量必须以某种方式传递给服务器。

There are a few decent ways of doing this, by far the most common is GET and POST variables. then you can pick them up in php and do whatever you wish with it.

有一些不错的方法可以做到这一点,到目前为止最常见的是 GET 和 POST 变量。然后你可以在 php 中选择它们并用它做任何你想做的事情。

You may pass variables like this: file.php?EEEE=YYY then fetch that variable with

你可以传递这样的变量:file.php?EEEE=YYY 然后用

$_GET['EEEE']

回答by Eugene

Looks like you can't. But you can send it with ajax to server and load requested changes:

好像不能 但是您可以使用 ajax 将其发送到服务器并加载请求的更改:

if ( window.self === window.top ) { 
    var iframe = '0';
} else { 
    var iframe = '1';
    // here ajax requested that will load instructions about how to change a page
}

Or u can use window.location = url;for change url of page. For example you can add get parameter ?iframe=true and then use it in php:

或者您可以window.location = url;用于更改页面的 url。例如,您可以添加获取参数 ?iframe=true 然后在 php 中使用它:

if (isset($_GET['iframe'])) {
    // here something
}

回答by LuigiEdlCarno

Check this out: Ajax

看看这个:阿贾克斯

This is a short example of how to do Ajax calls, as PHP is run on the serverside, whereas javscript is clientside.

这是如何进行 Ajax 调用的简短示例,因为 PHP 在服务器端运行,而 javscript 在客户端运行。

So essentially, your client function sends a request to the server, which then executes one of you PHP-implemented functions and returns the result.

所以本质上,您的客户端函数向服务器发送一个请求,然后服务器执行您的一个 PHP 实现的函数并返回结果。

回答by Dave Chen

Check out $_SERVER['HTTP_REFERER'], if the page is loaded from the frame, the refer should be different from the frame's src.

检查一下$_SERVER['HTTP_REFERER'],如果页面是从框架加载的,则引用应该与框架的 src 不同。

A quick test:

快速测试:

main.html:

主文件:

<iframe src="frame.php"></iframe>

frame.php

框架.php

echo $_SERVER['HTTP_REFERER'];

Visiting the page at main.html shows localhost/main.htmlwhile visiting at frame.php shows localhost/frame.php.

访问 main.html 页面显示,localhost/main.html而访问 frame.php 显示页面localhost/frame.php

This is simply for SEO purposes, as this variable shouldn't be trusted for security reasons.

这仅用于 SEO 目的,因为出于安全原因不应信任此变量。

回答by Swapnil Dalvi

You can do one thing make ajax call and send that variable to php file like At your javascript side==

你可以做一件事让ajax调用并将该变量发送到php文件,比如在你的javascript端==

jQuery.ajax({
            type: 'get', // type of request either Get or Post
            url: 'getValue.php', // Url of the file to set value in Session  
            data: "value="+iframe,  //that value which you want to use in php  
            success: function(data) 
            {}  });

At your php side

在你的 php 端

<?php
session_start();
$val = $_GET["value"]; //receive data from ajax call
$_SESSION['value']=$val; //set that value in session
echo $_SESSION['value']; //way to access value which is stored in session
?>

<?php
session_start();
$val = $_GET["value"]; //receive data from ajax call
$_SESSION['value']=$val; //set that value in session
echo $_SESSION['value']; //way to access value which is stored in session
?>

now to access that value in php just need to write on the start of php file
session_start();
and access that variable using
$_SESSION['value'];
there is also another way i.e pass that variable through url e.g "http://www.example.com/index.php?value=123456"
in your index.php
$received_fr_url=$_REQUEST['value'];will take the value from url

现在要在 php 中访问该值只需要在 php 文件的开头写入
session_start();
并使用
$_SESSION['value'];
另一种方法访问该变量,即通过 url 传递该变量,例如“ http://www.example.com/index.php?value =123456"
在您的 index.php 中
$received_fr_url=$_REQUEST['value'];将从 url 中获取值