PHP - include a php file and also send query parameters

PhpParametersInclude

Php Problem Overview


I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

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

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

Can someone please tell me how to achieve this? Thanks.

Php Solutions


Solution 1 - Php

Imagine the include as what it is: A copy & paste of the contents of the included PHP file which will then be interpreted. There is no scope change at all, so you can still access $someVar in the included file directly (even though you might consider a class based structure where you pass $someVar as a parameter or refer to a few global variables).

Solution 2 - Php

You could do something like this to achieve the effect you are after:

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

However, it sounds like you are using this include like some kind of function call (you mention calling it repeatedly with different arguments).

In this case, why not turn it into a regular function, included once and called multiple times?

Solution 3 - Php

An include is just like a code insertion. You get in your included code the exact same variables you have in your base code. So you can do this in your main file :

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

And in "myFile.php" :

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

This will output :

> My id is 12345 !

Solution 4 - Php

If you are going to write this include manually in the PHP file - the answer of Daff is perfect.

Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:

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

?>

I'm using this variable variable construction very often.

Solution 5 - Php

In the file you include, wrap the html in a function.

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

In the file where you want it to be included, include the file and then call the function with the parameters you want.

Solution 6 - Php

The simplest way to do this is like this

index.php

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

second.php

<?php echo $active; ?>

You can share variables since you are including 2 files by using "include"

Solution 7 - Php

I know this has been a while, however, Iam wondering whether the best way to handle this would be to utilize the be session variable(s)

In your myFile.php you'd have

<?php 

$MySomeVAR = $_SESSION['SomeVar'];

?> 

And in the calling file

<?php

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

Would this circumvent the "suggested" need to Functionize the whole process?

Solution 8 - Php

I have ran into this when doing ajax forms where I include multiple field sets. Taking for example an employment application. I start out with one professional reference set and I have a button that says "Add More". This does an ajax call with a $count parameter to include the input set again (name, contact, phone.. etc) This works fine on first page call as I do something like:

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

User presses a button that makes an ajax call ajax('references.php?count=1'); Then inside the references.php file I have something like:

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

I also have other dynamic includes like this throughout the site that pass parameters. The problem happens when the user presses submit and there is a form error. So now to not duplicate code to include those extra field sets that where dynamically included, i created a function that will setup the include with the appropriate GET params.

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

The function checks for query params, and automatically adds them to the $_GET variable. This has worked pretty good for my use cases.

Here is an example on the form page when called:

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

Just another example of including GET params dynamically to accommodate certain use cases. Hope this helps. Please note this code isn't in its complete state but this should be enough to get anyone started pretty good for their use case.

Solution 9 - Php

You can use $GLOBALS to solve this issue as well.

$myvar = "Hey";

include ("test.php");


echo $GLOBALS["myvar"];

Solution 10 - Php

Your question is not very clear, but if you want to include the php file (add the source of that page to yours), you just have to do following :

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

As long as the variable is named $someVar in the myFile.php

Solution 11 - Php

I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:

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

Solution 12 - Php

If anyone else is on this question, when using include('somepath.php'); and that file contains a function, the var must be declared there as well. The inclusion of $var=$var; won't always work. Try running these:

one.php:

<?php
    $vars = array('stack','exchange','.com');

    include('two.php'); /*----- "paste" contents of two.php */

    testFunction(); /*----- execute imported function */
?>

two.php:

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

Solution 13 - Php

Try this also

we can have a function inside the included file then we can call the function with parametrs.

our file for include is test.php

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

then we can include the file and call the function with our parameters as a variables or directly

index.php

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

Solution 14 - Php

Do this:

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

And add to your insert.php file:

$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";
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlostInTransitView Question on Stackoverflow
Solution 1 - PhpDaffView Answer on Stackoverflow
Solution 2 - PhpPaul DixonView Answer on Stackoverflow
Solution 3 - PhpNicolasView Answer on Stackoverflow
Solution 4 - PhpNikolay IvanovView Answer on Stackoverflow
Solution 5 - PhpMark BuikemaView Answer on Stackoverflow
Solution 6 - PhpKenneth BillonesView Answer on Stackoverflow
Solution 7 - PhpNepaView Answer on Stackoverflow
Solution 8 - PhpiLLinView Answer on Stackoverflow
Solution 9 - PhpDulacosteView Answer on Stackoverflow
Solution 10 - PhpafewccView Answer on Stackoverflow
Solution 11 - Phphackick7View Answer on Stackoverflow
Solution 12 - PhpultracasualView Answer on Stackoverflow
Solution 13 - PhpAbdulAhmad MatinView Answer on Stackoverflow
Solution 14 - PhpJaydip GodhaniView Answer on Stackoverflow