PHP - 包含一个 php 文件并发送查询参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1232097/
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-08-25 01:37:43  来源:igfitidea点击:

PHP - include a php file and also send query parameters

phpparametersinclude

提问by lostInTransit

I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

我必须根据某些条件从我的 php 脚本中显示一个页面。我有一个 if 条件,如果条件满足,我正在做一个“包含”。

if(condition here){
  include "myFile.php?id='$someVar'";
}

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

现在的问题是服务器有一个文件“myFile.php”,但我想用一个参数(id)调用这个文件,“id”的值会随着每次调用而改变。

Can someone please tell me how to achieve this? Thanks.

有人可以告诉我如何实现这一目标吗?谢谢。

回答by Daff

Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).

想象一下包含它是什么:包含的 PHP 文件内容的复制和粘贴,然后将被解释。根本没有范围更改,因此您仍然可以直接访问包含文件中的 $someVar(即使您可能考虑基于类的结构,其中将 $someVar 作为参数传递或引用一些全局变量)。

回答by Paul Dixon

You could do something like this to achieve the effect you are after:

你可以做这样的事情来达到你所追求的效果:

$_GET['id']=$somevar;
include('myFile.php');

However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).

但是,听起来您正在像某种函数调用一样使用此包含(您提到使用不同的参数重复调用它)。

In this case, why not turn it into a regular function, included once and called multiple times?

在这种情况下,为什么不把它变成一个常规函数,包含一次并多次调用?

回答by Nicolas

An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :

包含就像代码插入一样。您可以在包含的代码中获得与基本代码中完全相同的变量。所以你可以在你的主文件中做到这一点:

<?
    if ($condition == true)
    {
        $id = 12345;
        include 'myFile.php';
    }
?>

And in "myFile.php" :

在“myFile.php”中:

<?
    echo 'My id is : ' . $id . '!';
?>

This will output :

这将输出:

My id is 12345 !

我的ID是12345!

回答by Nikolay Ivanov

If you are going to write this include manually in the PHP file - the answer of Daffis perfect.

如果您打算在 PHP 文件中手动编写这个包含 - Daff的答案是完美的。

Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:

无论如何,如果你需要做最初的问题,这里有一个简单的小函数来实现:

<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
    // find ? if available
    $pos_incl = strpos($phpinclude, '?');
    if ($pos_incl !== FALSE)
    {
        // divide the string in two part, before ? and after
        // after ? - the query string
        $qry_string = substr($phpinclude, $pos_incl+1);
        // before ? - the real name of the file to be included
        $phpinclude = substr($phpinclude, 0, $pos_incl);
        // transform to array with & as divisor
        $arr_qstr = explode('&',$qry_string);
        // in $arr_qstr you should have a result like this:
        //   ('id=123', 'active=no', ...)
        foreach ($arr_qstr as $param_value) {
            // for each element in above array, split to variable name and its value
            list($qstr_name, $qstr_value) = explode('=', $param_value);
            // $qstr_name will hold the name of the variable we need - 'id', 'active', ...
            // $qstr_value - the corresponding value
            // $$qstr_name - this construction creates variable variable
            // this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
            // the second iteration will give you variable $active and so on
            $$qstr_name = $qstr_value;
        }
    }
    // now it's time to include the real php file
    // all necessary variables are already defined and will be in the same scope of included file
    include($phpinclude);
}

?>

?>

I'm using this variable variable construction very often.

我经常使用这个变量变量构造。

回答by Mark Buikema

In the file you include, wrap the html in a function.

在您包含的文件中,将 html 包装在一个函数中。

<?php function($myVar) {?>
    <div>
        <?php echo $myVar; ?>
    </div>
<?php } ?>

In the file where you want it to be included, include the file and then call the function with the parameters you want.

在您希望包含它的文件中,包含该文件,然后使用您想要的参数调用该函数。

回答by iLLin

I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:

我在做包含多个字段集的 ajax 表单时遇到了这个问题。以就业申请为例。我从一个专业的参考集开始,我有一个按钮,上面写着“添加更多”。这会使用 $count 参数执行 ajax 调用,以再次包含输入集(姓名、联系人、电话等)这在第一页调用上工作正常,因为我执行以下操作:

<?php 
include('references.php');`
?>

User presses a button that makes an ajax call ajax('references.php?count=1');Then inside the references.php file I have something like:

用户按下一个按钮,进行 ajax 调用ajax('references.php?count=1');然后在references.php 文件中,我有类似的内容:

<?php
$count = isset($_GET['count']) ? $_GET['count'] : 0;
?>

I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.

我在整个站点中还有其他类似的动态包含传递参数。当用户按下提交并且出现表单错误时,就会出现问题。因此,现在为了不复制代码以包含那些动态包含的额外字段集,我创建了一个函数,该函数将使用适当的 GET 参数设置包含。

<?php

function include_get_params($file) {
  $parts = explode('?', $file);
  if (isset($parts[1])) {
    parse_str($parts[1], $output);
    foreach ($output as $key => $value) {
      $_GET[$key] = $value;
    }
  }
  include($parts[0]);
}
?>

The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.

该函数检查查询参数,并自动将它们添加到 $_GET 变量中。这对我的用例非常有效。

Here is an example on the form page when called:

这是调用时表单页面上的示例:

<?php
// We check for a total of 12
for ($i=0; $i<12; $i++) {
  if (isset($_POST['references_name_'.$i]) && !empty($_POST['references_name_'.$i])) {
   include_get_params(DIR .'references.php?count='. $i);
 } else {
   break;
 }
}
?>

Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.

这是动态包含 GET 参数以适应某些用例的另一个示例。希望这可以帮助。请注意,此代码未处于完整状态,但这应该足以让任何人开始使用他们的用例。

回答by Nepa

I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)

我知道这已经有一段时间了,但是,我想知道处理这个问题的最佳方法是否是利用 be 会话变量

In your myFile.php you'd have

在你的 myFile.php 你有

<?php 

$MySomeVAR = $_SESSION['SomeVar'];

?> 

And in the calling file

并在调用文件中

<?php

session_start(); 
$_SESSION['SomeVar'] = $SomeVAR;
include('myFile.php');
echo $MySomeVAR;

?> 

Would this circumvent the "suggested" need to Functionize the whole process?

这是否会规避“建议”需要使整个过程功能化?

回答by afewcc

Your question is not very clear, but if you want to includethe php file (add the source of that page to yours), you just have to do following :

您的问题不是很清楚,但是如果您想包含php 文件(将该页面的源添加到您的页面),您只需执行以下操作:

if(condition){
    $someVar=someValue;
    include "myFile.php";
}

As long as the variable is named $someVar in the myFile.php

只要变量在 myFile.php 中命名为 $someVar

回答by hackick7

I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:

我处于同样的情况,我需要通过发送一些参数来包含一个页面......但实际上我想做的是重定向页面......如果你是这种情况,代码是:

<?php
   header("Location: http://localhost/planner/layout.php?page=dashboard"); 
   exit();
?>

回答by ultracasual

If anyone else is on this question, when using include('somepath.php');and that file contains a function, the var must be declared there as well. The inclusion of $var=$var;won't always work. Try running these:

如果其他人在这个问题上,当使用include('somepath.php');并且该文件包含一个函数时,var 也必须在那里声明。包含$var=$var;并不总是有效。尝试运行这些:

one.php:

一个.php:

<?php
    $vars = array('stack','exchange','.com');

    include('two.php'); /*----- "paste" contents of two.php */

    testFunction(); /*----- execute imported function */
?>

two.php:

二.php:

<?php
    function testFunction(){ 
        global $vars; /*----- vars declared inside func! */
        echo $vars[0].$vars[1].$vars[2];
    }
?>