PHP - include a php file and also send query parameters - php

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.

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

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?

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 !

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.

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"

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.

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?

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.

You can use $GLOBALS to solve this issue as well.
$myvar = "Hey";
include ("test.php");
echo $GLOBALS["myvar"];

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

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

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

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

Related

View included by $this->include does note recieve passed params

Is possible pass parameter to view when i use $this->include method in another view?
In example:
<?php
foreach ($destaques as $camping) {
$this->include('partial', ['camping' => $camping])
}
?>
But partial.php dont recieve $camping value.
When using $this->include you're making an echo of a view into an other one. So by default, the view you're loading will have acces to any data you gave to the parent view but not variables you declared into it.
A few options in your case :
Using the view method :
foreach ($destaques as $camping) {
echo view('partial', ['camping' => $camping]);
}
Moving your foreach loop in the partial view so you'll use $destaques into it.
<?php
// dont forget to echo
echo $this->include('partial')
?>
// or this way with short tags enabled
<?= $this->include('partial') ?>
And just embed your partial view in your previous foreach loop
foreach ($destaques as $camping) {
// whatever your partial view is
}
Hello I try using the parameter option. I test code and it s working. But note the include view layout method work like php default include function and it does not display until you echo it.
Here is my code which I use to test yours and it worked for me. Check it
$inc = '';
foreach ($destaques as $camping) {
$inc .= $this->include('partial', ['camping' => $camping])
}
echo $inc;
And this displayed and worked for me check it. if this is not what you were expecting, just call my attention

setting a variable/ marker to use in a php function in the same php file

i want to set a marker like variable which will be set in a particular page and used for validation in common functions. i tried $REQUEST but its not working. Any suggestion? also not able to read input hidden value..
in php section
<?php $GLOBALS['isRayaPromo'] = "rtrtr";
get_template_part('includingFilewithFunctionHere');
?>
<div class="btn_photo_wrapper">
code here invoking above function
</div>
say m having function A to called on click of a button. Function A is a common function used in different page flows. But for my page i need to do a specific change in Function A. Which is why i need a marker in my php so tahat the function does the change only for my page based on this marker validation.
also tried with regular php variable.
cannot pass teh variable in function call as it is a common function which is already being used in other flows and i cannot change the signature of teh function.
I am a beginner so plz suggest
A few things to note:
You are using globals. This is deprecated and strongly discouraged.
You forgot the _ in $_REQUEST
It's better to use constants instead
An example:
define('SOMEVAR', 'I want to use this string e----ve---ry---whereeeee');
function stupidFunction()
{
echo SOMEVAR;
}
You can also just pass variables to functions:
$var = "Some stupid text";
function doSomethingAwesome($var)
{
echo $var;
}
Edit
In order to do what you want, you need to pass by reference. Take a look at the following sample code and take a close look at the & that I am using in the function. The & sign means that the variable that I pass into the function will not only change in the function scope but in the global scope as well.
define('PROMORAYA', '1');
var_dump(PROMORAYA); // Returns string(1) "1"
$isPromo = 0;
whoopdidooptidoo($isPromo);
function whoopdidooptidoo(&$isPromo)
{
if (PROMORAYA == '1') {
$isPromo = 1;
}
}
var_dump($isPromo); // int(1)
You can use constants if value to be used is fixed like this.
<?php
define("isRayaPromo", "rtrtr");
get_template_part('includingFunctionHere');
?>
<div class="btn_photo_wrapper">
<?php echo isRayaPromo;?>
</div>

PHP include make the whole page appear? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Okay, my code is simple:
<?php include 'formvalidation.php';
echo $name; ?>
I want to make only the $name appear, but the whole 'formvalidation.php' shows up.
How can I fix that?
"I want that after I pressed the button, the function I had written will be excute to check the input, and then if the input is right, it'll redirect to another page, which can display the input."
If you wish to redirect after a form has been submitted and show a name afterwards, you will need to use sessions and a header.
Here is an example, (see comments in code) to be added inside formvalidation.php:
<?php
session_start();
// all other codes you already have
$name = "John"; // this is an example
// replace above with your POST variable
// such as $name = $_POST['name'];
$_SESSION['showname'] = $name;
header("Location: your_other_file.php");
exit; // keep this
N.B.: Make sure there is nothing else above <?php session_start(); such as your form, because this will throw a warning, stating Headers already sent...
your_other_file.php
<?php
session_start();
if(isset($_SESSION['showname'])){
$name = $_SESSION['showname'];
echo $name;
}
$name = "John"; // this is an example
Replace above in code with your POST variable.
Such as $name = $_POST['name']; as an example, since you have not provided additional code as to what your superglobal variable is for the name.
You can use session feature to call the variable instead of including a page, because it will indeed load an entire page. Please be more specific about your goal, perhaps we can help more by knowing more.
The whole HTML content of formvalidation.php will come up on the screen (so everything outside of <?php ?> just like all the outputs (echo etc ...) of the included file will come up on the screen.
You can avoid that by removing the outputs and only putting functions and variable declarations into the included file formvalidation.php.
The content of formvalidation.php could eg. be:
<?php
$name = 'test';
?>
It's going to execute whatever's in formvalidation.php. All the include function does is basically replace that line with the contents of your included file.
So if you don't want to show what's in that file - enclose the entire file in a function, or multiple functions. This is the way your library files (that you include) should be. Nothing in that file should be outside of a function definition.
Example (it's a crappy programming practice, but for example) -
formvalidation.php was ->
<?php
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
?>
Everything gets shown when I include it.
formvalidation.php now ->
<?php
function validate_form() {
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
}
?>
Now the way I've changed the file - nothing will get printed until I call validate_form();
Does that make sense?
When you use include 'someFile.php'; it's like you are taking all the contents of that file and pasting it in the code. For example if I had:
someFile.php
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
then:
include 'someFile.php';
echo $name;
Is the same as:
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
echo $name;
As others have said, that's what include does. I assume that you define $name inside the formvalidation.php file and that is why you are including it.
The right solution here would be to seperate the code in formvalidation.php into a function/class/file which does the data processing and another which creates the output. The you include/call only the first in the situation where you don't want the output
However, it is possible to capture the output and then discard it, using output buffering:
<?php
ob_start(); //Start capturing output
include 'formvalidation.php';
ob_end_clean(); // Stop capturing output and discard whatever was captured
echo $name;
?>
That said I would really not recommend this. The recommended way to fix this is to seperate your back-end code from your output generating code and only call what you actually need in any given situation.
Edit
An example of how to seperate the issues properly could be the following.
Lets assume your current formvalidation.php is something like:
<?php
$name = $_REQUEST['name'];
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
In a new file validator.php you could do:
<?php
class MyValidator{
public $name;
function read_data(){
$this->name = $_REQUEST['name'];
}
function validate(){
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
}
}
Then you change you formvalidtion.php to
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
$val->validate();
While the file you have above becomes
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
echo $val->name;

change body of if statement based on its condition

Here is my question
I have a class say ABC and a function XYZ defined inside it and that function is returning something based on the above logic in it.
class ABC {
function XYZ{
..........
.......
return "--- ";
}
}
Now there is an object on another page of this class which calls this method.
$z= new ABC;
if( $z->XYZ() )
{
some output
}
else{
another output
}
My problem is i dont have access to PAGE 2. but i need to change the output of else statement. I have only access to class ABC because i am overriding it in a module. so, in short i can only alter function XYZ. Whats the solution??
If its of any significance, i am working on MAGENTO ECOMMERCE Platform and class is a block class and page 2 is a template
You can alter the output html with an observer with the http_response_send_before event.
Capture the html and do your stuff.
You have a good explanation here
I hope this can help you
you can also do as follow :
<?php
ob_start();
// do your stuff
// ...
// here you capture all the output that it is generated by your scripts
$v = ob_get_contents();
// alter the value of $v by detecting if it should be changed. you can user regex for example to
// detect and update
// ...
// here you clean all data stored in buffer
ob_clean();
// and put the updated data in buffer
print $v;
// end of buffer operations
ob_end_flush();
?>
hope it helps,
You need a way to differentiate PAGE1 from PAGE2, lets say by the URL if it's possible. So you would have to change your method that will check on which page is currently and according to it, it will change the output, but you must write the output in the method itself instead of writing it in the template.
class ABC {
function XYZ {
$result = $this->getResult(); //Helper method to get the result.
if ($result) {
//Do something when result is true.
} else {
$url = $this->checkUrl(); //Check URL of the page.
if ($url == PAGE2) { //If you are on PAGE2
//Do something specific for the PAGE2
} else {
//Do something for all other pages
}
}
}
}
I know it's not the perfect solution, but I hope it will help you somehow.
The page number has to be specified somewhere in the $_GET or the $_POST array (or in another query). Check that variable and implement the alternative logic.

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

Categories