【问题标题】:PHP - include a php file and also send query parametersPHP - 包含一个 php 文件并发送查询参数
【发布时间】:2010-11-16 22:55:03
【问题描述】:

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

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

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

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

【问题讨论】:

  • myFile.php 在您的情况下实际上做了什么?除非您通过 HTTP 请求包含,否则您无法向文件名添加参数,但您可以通过某种全局变量影响其行为。

标签: php parameters include


【解决方案1】:

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

【讨论】:

  • 另请注意:$_GET 对于所有包含的文件都是相同的。因此,如果这是存储查询参数的位置,它仍然会看到它们。另请注意:它不是类中的函数。
【解决方案2】:

你可以这样做来达到你想要的效果:

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

但是,听起来您使用这个包含就像某种函数调用(您提到使用不同的参数重复调用它)。

既然如此,为什么不把它变成一个普通的函数,包含一次,多次调用呢?

【讨论】:

  • 我同意,这听起来绝对应该是函数调用而不是包含。
  • 你的代码和include("myFile.php?id=$somevar");一样吗?
  • 注意:include("myFile.php?... 无法按预期工作。
【解决方案3】:

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

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

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

【讨论】:

    【解决方案4】:

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

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

    在“myFile.php”中:

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

    这将输出:

    我的 id 是 12345!

    【讨论】:

      【解决方案5】:

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

      在你的 myFile.php 中你会有

      <?php 
      
      $MySomeVAR = $_SESSION['SomeVar'];
      
      ?> 
      

      在调用文件中

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

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

      【讨论】:

      • 你想让它成为一个函数,这样你就不会发起一堆请求。问题不在于如何将信息获取到包含的 PHP 中——OP 的方法已经实现了这一点。
      【解决方案6】:

      如果您要在 PHP 文件中手动编写此包含 - Daff 的答案是完美的。

      无论如何,如果您需要解决最初的问题,这里有一个简单的小功能来实现:

      <?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);
      }
      

      ?>

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

      【讨论】:

        【解决方案7】:

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

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

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

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

        我在整个站点中还有其他类似的动态包含传递参数。当用户按下提交并且出现表单错误时,就会出现问题。因此,现在为了不重复代码以包含那些动态包含的额外字段集,我创建了一个函数,该函数将使用适当的 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]);
        }
        ?>
        

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

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

        <?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;
         }
        }
        ?>
        

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

        【讨论】:

          【解决方案8】:

          这样做:

          NSString *lname = [NSString stringWithFormat:@"var=%@",tname.text];
          NSString *lpassword = [NSString stringWithFormat:@"var=%@",tpassword.text];
          
          NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://localhost/Merge/AddClient.php"]];
          [request setHTTPMethod:@"POST"];
          [request setValue:@"insert" forHTTPHeaderField:@"METHOD"];
          
          NSString *postString = [NSString stringWithFormat:@"name=%@&password=%@",lname,lpassword];
          NSString *clearpost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];
          NSLog(@"%@",clearpost);
          [request setHTTPBody:[clearpost dataUsingEncoding:NSUTF8StringEncoding]];
          [request setValue:clearpost forHTTPHeaderField:@"Content-Length"];
          [NSURLConnection connectionWithRequest:request delegate:self];
          NSLog(@"%@",request);
          

          并添加到您的insert.php 文件中:

          $name = $_POST['name'];
          $password = $_POST['password'];
          
          $con = mysql_connect('localhost','root','password');
          $db = mysql_select_db('sample',$con);
          
          
          $sql = "INSERT INTO authenticate(name,password) VALUES('$name','$password')";
          
          $res = mysql_query($sql,$con) or die(mysql_error());
          
          if ($res) {
              echo "success" ;
          } else {
              echo "faild";
          }
          

          【讨论】:

            【解决方案9】:

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

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

            【讨论】:

              【解决方案10】:

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

              一个.php:

              <?php
                  $vars = array('stack','exchange','.com');
              
                  include('two.php'); /*----- "paste" contents of two.php */
              
                  testFunction(); /*----- execute imported function */
              ?>
              

              两个.php:

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

              【讨论】:

                【解决方案11】:

                您也可以使用$GLOBALS 来解决此问题。

                $myvar = "Hey";
                
                include ("test.php");
                
                
                echo $GLOBALS["myvar"];
                

                【讨论】:

                • 那行得通。但我需要为包含使用不同的值,我应该做什么 //
                【解决方案12】:

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

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

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

                【讨论】:

                  【解决方案13】:

                  最简单的方法是这样的

                  index.php

                  <?php $active = 'home'; include 'second.php'; ?>
                  

                  second.php

                  <?php echo $active; ?>
                  

                  您可以共享变量,因为您使用“包含”包含 2 个文件

                  【讨论】:

                    【解决方案14】:

                    也试试这个

                    我们可以在包含的文件中有一个函数,然后我们可以使用参数调用该函数。

                    我们的包含文件是test.php

                    <?php
                    function testWithParams($param1, $param2, $moreParam = ''){
                        echo $param1;
                    }
                    

                    然后我们可以包含文件并使用我们的参数作为变量或直接调用函数

                    index.php

                    <?php
                    include('test.php');
                    $var1 = 'Hi how are you?';
                    $var2 = [1,2,3,4,5];
                    testWithParams($var1, $var2);
                    

                    【讨论】:

                      猜你喜欢
                      • 2012-10-14
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-12-08
                      • 1970-01-01
                      • 2012-02-13
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多