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?

1
  • Looking back 11 years at the questions I asked on SO is so embarrassing 😂 Commented Mar 22, 2022 at 17:02

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Of course only if they're in the same scope, or the include script is non-procedural or $name resides within the globals.
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;
how to used varible globally?
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. :)

2 Comments

$_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.
@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.
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"

Comments

-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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.