PHP Require and Include GET
Asked Answered
D

4

6

I would like to require a file but also pass GET variables through the url, but when I write:

<?php
   require_once("myfile.php?name=savagewood");
?>

I get a fatal error. How would I accomplish this functionality in a different way, such that I don't get a fatal error?

Darcie answered 24/4, 2011 at 17:6 Comment(1)
Looking back 11 years at the questions I asked on SO is so embarrassing πŸ˜‚ – Darcie
A
21

variables will be available as normal you do not have to pass like this.

$name='savagewood';
require_once("myfile.php");

$name will be available in myfile.php

Arquit answered 24/4, 2011 at 17:8 Comment(3)
Of course only if they're in the same scope, or the include script is non-procedural or $name resides within the globals. – Antonio
in my case this is not working. $name = $_POST['test']; here i got value of $name. but in myfile.php not getting value of $name; – Magdalen
how to used varible globally? – Magdalen
E
1
<?php
$getVarsArray = $_GET;
$postVarsArray = $_POST;
/* n number of variables and lines of code*/
include('script-a.php');
?>

Now in script-a.php has access to $getVarsArray and $postVarsArray and if in any case you are in doubt you can use $GLOBALS to access any variable throughout the life cycle of a script. But using global variables is a sin. :)

Elater answered 24/4, 2011 at 17:23 Comment(2)
$_GET and $_POST are superglobals, meaning that they exist in every scope. Copying the GPC superglobals into another variable like this is beyond silly and borderline insane. Don't do that. – Hartsell
@Charles, using those GET and POST variables w/out treating them will be equally beyond silly and borderline insane. I never do that. The sane will treat those superglobals & will copy them and unset POST/GET vars. Or a paranoid may even write his own implementation for using GET/POST var. This being, not in the scope of the question, wasn't mentioned. My bad. – Elater
G
0

It is not necessary to pass the variables to the new file, because by including the new file the variables are maintained. Remember that $ _GET is an array, and it can be modified within the script.

<?php
   $_GET['name'] = "savagewood";
   require_once("myfile.php");
?>

On this case, $_GET['name'] is accesible from the "myfile.php"

Griddle answered 6/12, 2019 at 22:14 Comment(0)
W
-2

I think I have got a perfect solution to your problem. You can use implode function of PHP. But I would strongly recommend doing Shakti Singh's code.

SOLUTION CODE

echo implode(file('http://path-to-your-site/your-dir/myfile.php?name=savagewood'));
Ways answered 24/4, 2011 at 17:20 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.