php __FILE__ not working

1.9k views Asked by At

I am trying to load a php file B.PHP from another php file A.PHP, plus I want to send a variable via $_GET. Both files are stored on the same directory. I tried several ways:

1st) Directly write on my file:

require (__FILE__)."\b.php?action=1";

The result of doing an echo is: C:\xampp\htdocs\pfc\html\a.phpb.php?action=1, so INCORRECT!

So then I tried:

require (__FILE__)."\..\b.php?action=1"; INCORRECT again

2nd) On a different PHP I set:

define('MAINDIR',dirname(__FILE__) . '\\');
define('DL_DIR',MAINDIR . 'pfc\\html\\');   // Also tried with a normal '/'

And then on my file I just do:

require DL_DIR."b.php?action=1";  I also tried with include, but I guess this has nothing to do.

In this case, if I do an echo I get: C:\xampp\htdocs\pfc\html\b.php, so CORRECT!

However, when I run my program, I get the next error:

Warning: require (C:\xampp\htdocs\pfc\html\b.php?action=1): failed to open stream: No such file or directory in C:\xampp\htdocs\pfc\html\a.php on line 101

Warning: require (): Failed opening 'C:\xampp\htdocs\pfc\html\b.php?action=1' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\pfc\html\a.php on line 101

OBVIOUSLY it cannot find a file inside a file. So I tried again the '..\' wih this version... WRONG!

3rd) Adding realpath to the equation

require realpath(dirname(__FILE__)."\b.php?action=1");

And, again, I get:

Warning: require (): Filename cannot be empty in C:\xampp\htdocs\pfc\html\HTML_menu_supervisor.php on line 101

Warning: require (): Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\pfc\html\HTML_menu_supervisor.php on line 101

I really don't know what is going on. Please someone help me! And thanks in advance :-)

3

There are 3 answers

7
tptcat On

As far as I know, you can't pass parameters via require or include. Therefore I believe that your requires are actually looking for a file that doesn't exists (since you probably don't have a file named b.php?action=1.

You can just set whatever variable(s) you need to and reference them in the required files (assuming they're in the same scope).

4
demonking On

You don't have to get parameters to your include.

if you url looks something like this

localhost/myfunction.php?action=1

myfunction.php:

    require (__DIR__)."\..\b.php";

You could include your file and it will get the GET variable out of the box.

An include is a copy&paste of your included file .

So your b.php should look like this:

$allowedGetValues = array(1,2,3,4);


if(isset($_GET['action']) && array_key_exists($_GET['action'],$allowedGetValues) ){
    .. 
}
0
Anil Meena On

you have to use include or require function like below -

include('b.php');
or
require('b.php');