how to pass a variable through the require() or include() function of php?

后端 未结 9 2087
梦如初夏
梦如初夏 2021-02-06 21:34

when I use this:

require(\"diggstyle_code.php?page=$page_no\");

the warning is :failed to open stream: No error in C:\\xampp\\htdocs\\4ajax\\ga

相关标签:
9条回答
  • 2021-02-06 22:08

    I had this problem and I noticed if you use http:// in your url then it doesn't work

    0 讨论(0)
  • 2021-02-06 22:11

    this should work, but it's quite a dirty hack:

    $_GET['page'] = $page_no;
    require('diggstyle_code.php');
    

    you probably want to refactor your code to use functions and/or objects and call them from your files instead of including them (spaghetti code alert)

    0 讨论(0)
  • 2021-02-06 22:18

    If your variable is global, there's no need to "pass"it, it is there already: PHP variable scope.

    The answer then is, don't do anything, if $page_no exists in the file in which you call require(), it will be available in the included file.

    0 讨论(0)
  • 2021-02-06 22:21

    if I've correctly understood, what you need is to call the file diggstyle_code.php passing an argument, so that no one can call that file and make it work, rather than your main file. Am I right?

    Thus supposing that your "main.php" has the lines

    require("diggstyle_code.php?page=$page_no");
    

    it means that: if anyone calls "main.php" gets diggstyle_code.php running. But if anybody in any manner calls directly diggstyle_code.php he/she shoudl get nothing.

    If I am right on my understanding, a way to achieve this, is to include into the main file a variable or a constant, that will be scoped by diggstyle_code.php

    Thus for instance: 'main.php'

    <?php
    define("_VERIFICATION_", "y");
    require("diggstyle_code.php");
    ?>
    

    and now diggstyle_code.php

    <?php
    if ( _VERIFICATION_ == "y" ) {
    //Here the code should be executed
    } else {
    // Something else
    }
    ?>
    
    0 讨论(0)
  • 2021-02-06 22:21

    require, require_once, include and include_once try to include files from the filesystem in the current file.

    Since there's no files named diggstyle_code.php?page=1, it's totally logical that PHP can't find it.

    You can't pass values that way, however, any variable declared in the current file will be accessible in the included files.

    0 讨论(0)
  • 2021-02-06 22:27

    require doesn't pull the file from the web server - it should refer to a file on the filesystem instead.

    Calling include or require just tells PHP to paste the contents of the given file in your code at this place, nothing more than that.

    0 讨论(0)
提交回复
热议问题