How to pass variables from a php file to another while it is not html inputs ,just i have a link refer to the other file and i want to pass variables or values to it
Example:
File1.php
<?php
$name='OdO';
echo "<a href='File2.php'>Go To File2</a>";
?>
File2.php
<?php
echo $name;
?>
Use sessions to store any small value that needs to persist over several requests.
File1.php:
session_start();
$_SESSION['var'] = 'foo';
File2.php:
session_start();
$var = $_SESSION['var']; // $var becomes 'foo'
Try to use sessions. Or you can send a GET parameters.
You can use URLs to pass the value too.
like
index.php?id=1&value=certain
and access it later like
$id = $_GET['id'];
$value = $_GET['value'];
However, POST might be much reliable. Sessions/Cookies and database might be used to make the values globally available.
Here's one (bad) solution, using output buffering:
File 1:
<?php
$name = 'OdO';
echo 'Go To File2';
?>
File 2:
<?php
ob_start();
include 'File1.php';
ob_end_clean();
echo $name;
?>
Related
Hey guys I'm trying to pass a php variable to another page. I tried it with sessions but no result.
newspaper.php
$newspaper= $newspaper['newspath'];
print_r($newspaper);
this outputs:
path/to/the/newspaper.
Now I want to use the variable in the second page.
newspaperviewer.php
echo $newspaper;
$SESSION = $newspaper;
I tried the first one but no result. The second one seems to be faulty.
Hope you guys can help me out.
Session is what you are looking for. A session variable can store a value and use this value on all pages of your project.
First thing to do is to start session on each file on your project. You can do this like this example
<?php
session_start(); //declare you are starting a session
$_SESSION['newspaper'] = "New York Times"; //Assign a value to the newspaper session
?>
On the other file you can use the value of the session by trying something like this
<?php
session_start(); //always start session don't forget!!
echo $_SESSION['newspaper'];
// This will echo New York Times
?>
Store the variable after starting session on page A, like so:
// FIRST PAGE (foo.php)
session_start();
$_SESSION['name'] = 'Jack';
Now, on the second page (or any page that you want to have access to $_SESSION, simply do the same but pull the variable.
// SECOND PAGE (bar.php)
session_start();
$name = $_SESSION['name'];
$_SESSION['name'] = null; // Or use session_unset() to delete all SESSION vars.
And that's how you pass variables using $_SESSION.
Please use this code to set session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
You can write like this
newspaper.php
session_start();
$newspaper= $newspaper['newspath'];
$_SESSION['newspaper'] = $newspaper;
Now you can use this session variable in
newspaperviewer.php
session_start();
$newspaper = $_SESSION['newspaper'];
echo $newspaper;
session_unset(); // remove all session variables
First
newspaper.php
$newspaper= $newspaper['newspath'];
//print_r($newspaper);
session_start(); //it starts your session here
$_SESSION['newspaper']=$newspaper; //it sets a session variable named as newspaper
Second
$newspaper= isset($_SESSION['newspaper'])?$_SESSION['newspaper']:''; //checks and sets value
echo $newspaper; //outputs value
For more see session_start
http://php.net/manual/en/session.examples.basic.php
First you will need to start the session by using session_start() at the top of your page. Second, a session variable is written like this: $_SESSION['foo'].
I suggest you read these pages to get a better understanding of what's going on.
http://php.net/manual/en/reserved.variables.session.php
http://www.w3schools.com/php/php_sessions.asp
I am currently in file1.php and I want a variable from file1.php to pass to file2.php
How do I pass a variable from one php file to another?
I too want to go from file1.php to file2.php
I did following in file1.php:
session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");
and did following in file2.php :
<?php
echo "abc";
echo $_SESSION['akknum'];
?>
The file2.php is opening and abc is printing but no value of "jkl" is printing. What am I doing wrong?
You need to add session_start(); in file2.php.
session_start();
echo "abc";
echo $_SESSION['akknum'];
Basic usage.
you need to session_start the second file too.
If you want to use $_SESSION on a different file, you'll need to call session_start();
file1.php
<?php
session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");
?>
file2.php
<?php
session_start();
echo $_SESSION['akknum'];
//jkl
?>
Read more about php sessions
I have a simple question, with maybe not so simple of an answer. I want to be able to set a variable in one script and pass that value and variable to another script. Without passing it through the url, and having the ability to pass an array.
So I have index.php in there I have a variable
<?php
$myvariable = '';
<form action=editRecord.php>
do some form actions here and submit moving to editRecord.php
</form>
?>
Now in editRecord.php
<?php
header('Location: go back to index.php);
run functions and edit the Mysql DB
//Ok now here is where I want to assign a value to $myvariable and pass it back to index.php
?>
Is this possible? I am sorry for the amateurish question, but I am very green when it comes to php.
Thank You.
you can set it in the $_SESSION variable:
<?php
session_start();
$_SESSION["myVar"] = "blabla";
....
Of course you can store an array() in this variable too.
Just pass that information in the querystring. Then you can access it via $_GET. If it doesn't exist, just set the value to an empty string or whatever default value you want it to have.
// editRecord.php
<?php
// do db dtuff
header('Location: index.php?myvariable=somevalue');
?>
// index.php
<?php
$myvariable = (isset($_GET['myvariable'])) ? $_GET['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can also use session variables:
// editRecord.php
<?php
session_start();
// do db stuff
$_SESSION['myvariable'] = 'somevalue';
header('Location: index.php');
?>
// index.php
<?php
session_start();
$myvariable = (isset($_SESSION['myvariable'])) ? $_SESSION['myvariable'] : '';
<form action="editRecord.php" >
</form>
?>
You can use sessions, POST data, GET data, cookies and database data.
I've read this post(how do i send a variable in the url in javascript), but can't get it to work. I must add that I don't know javascript at all. I'm trying to open an new "printer friendly" page in php, but in order for that I need to send the userid with the url, my code looks like this:
Page1
<?php
session_start();
$userid = $_SESSION['userid'];
?>
<head>
<script type="text/javascript">
function open_win()
{
window.open("http://www.mysite.com/exams/print.php?uid_print=$userid",'','width=200,height=100')
}
</script>
</head>
<?php
if ($_SESSION['auth']) {
include 'datalogin.php';
echo "<input type='button' value='Print this page' onclick='open_win()' />";
Page2(print.php)
<?php
session_start();
include 'datalogin.php';
$uid_print1 = $_GET['uid_print'];
echo $uid_print1;
But my ouput is: $userid
window.open("http://www.mysite.com/exams/print.php?uid_print=<?php echo $userid; ?>",'','width=200,height=100')
At the moment the variable in your javascript tag is not replaced because it is not enclosed by PHP tags. You can easily do it like this:
window.open("http://www.mysite.com/exams/print.php?uid_print=<?php echo $userid; ?>",'', 'width=200,height=100')
Modify your window.open line to looks like this:
window.open("http://www.mysite.com/exams/print.php?uid_print=<?php echo $userid; ?>",'','width=200,height=100');
You have to 'enter' PHP block, and print out $userid variable to HTML (JavaScript) output.
This line in your JS script:
window.open("http://www.mysite.com/exams/print.php?uid_print=$userid",'','width=200,height=100')
Outputs '$userid' directly. You need to replace $userid with something like:
<?php echo $userid; ?>
Use <?php....?> tags:
...print.php?uid_print=<?php echo $userid;?>
Replacing:
window.open("http://www.mysite.com/exams/print.php?uid_print=$userid",'','width=200,height=100')
With:
window.open("http://www.mysite.com/exams/print.php?uid_print=<?php echo $userid; ?>",'','width=200,height=100')
Should probably do the trick.
You can also use the shorthand <?= $userid ?> which, to my eyes is more readable.
please concatenate $userid in your javascript.
it can be concatenated like uid_print='.$userid.' and you will get the value in $_GET["uid_print"]
you can also echo the $userid in string like
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();
?>