So I've search far and wide to try and find an example of this but found nothing. It seems like a simple thing however I continue to get errors.
Essentially what I've got is:
<?php
$articleCount = 3;
include('/newsArticles.php?id=$articleCount');
?>
It seems fairly self explanatory. What I need is an include that I can pass a value on into the file which I can then grab with $_GET['id'].
You can't add a query string (Something like ?x=yyy&vv=www) onto an include like that. Fortunately your includes have access to all the variables before them, so if $_GET['id'] is defined before you call:
include('/newsArticles.php');
Then newsArticles.php will also have access to $_GET['id'];
You don't need to pass a $_GET variable. Just set it, and reference it in your included file.
Your included file will have access to $articleCount without any additional work needed.
Try this:
$_GET['id'] = 3;
include('/newsArticles.php');
Since you are including a script it would seem as though you have access to the script itself. Even if you don't have access to the script you can edit the $_GET variable from within the script you showed above, like this:
<?php
$_GET['id'] = 3; // or $_GET['id'] = $articleCount;
include('/newsArticles.php');
?>
That's because the script newsArticles.php has the same access to the $_GET variable, unless the script was specifically created so that it extracts the variables from the URL.
Try it.
Related
So basically what I'm trying to do is if the url contents looks something like this:
www.some.com/dir/?variable=VAR&variable2=VAR2.
then the server would pick this up and I could add it to a variable like:
$var = [variable];
echo '<tag>'.$var.'</tag>';
and that would produce;
<tag>VAR</tag>
Sorry for the lack of code I just don't know how to do this with PHP and my searches are turning up blank.
What you want to do is iterate through your $_GET variables and print them out.
$key is variable and $value is VAR . to print key value combo use this. to print just value remove the '$key is ' part.
<?php
foreach($_GET as $key=>$value)
{
echo "<tag>$key is $value</tag>";
}
These variables are called query parameters and in PHP they can be accessed using the $_GET superglobal.
To use your example, the URL www.some.com/dir/?variable=VAR&variable2=VAR2 will populate $_GET['variable'] with 'VAR' and $_GET['variable2'] with 'VAR2'.
You can access $_GET just like any other array from anywhere in your code so it should be straightforward to put its contents in your HTML code:
<tag><?php echo $_GET['variable'] ?></tag>
<tag><?php echo $_GET['variable2'] ?></tag>
Do keep in mind this presents an HTML injection vulnerability. For example, the user could access the URL www.some.com/dir/?variable=<script>doUnfortunateThings()</script> and your script would dutifully render
<tag><script>doUnfortunateThings()</script></tag>
Which would be executed by the browser when the page loads. This might be fine since only the user messing with the URL will see it, but depending on the rest of your page it could pose a security risk, and could even be made permanent by other scripts running on the page or on the server. It could also bypass any content security policy settings your site is running under, depending on how that is configured if at all.
It is good practice to use the built-in PHP function htmlspecialchars on any user input before displaying it on the page to prevent any html tags from actually being rendered by the browser.
<tag><?php echo htmlspecialchars($_GET['variable']) ?></tag>
<tag><?php echo htmlspecialchars($_GET['variable2']) ?></tag>
If you already know variable name from url then you can use it as array index:
$variable = $_GET["var_name"];
In your case:
$variable = $_GET["variable"];
$variable2 = $_GET["variable2"];
In my php code there is a section which needs to be retrieved from another php file.
I tried accomplishing this by:
include "teams.php?id=".$matchid;
and in the teams.php
$matchid = $_GET['id'];
echo "MATCH ID IS ".$matchid;
The problem is when i open teams.php?id=".$matchid directly it displays the match id fine
however the include doesn't work - i checked the source code of the original page - no code is being inserted. Is there a way to do what i want? I need to get php code from another file whilst passing 2 variables onto that file
Problem
The problem is related to what $_GET really contains:
An associative array of variables passed to the current script via the URL parameters. (...)
And you do not pass $matchid to the script through URL... And you should not in this case.
Solution
But there is a way. PHP does not separate global variables among files, so variables available in one file are available also in the one included:
in file no. 1:
// Assume $matchid is defined
include "teams.php";
in file no. 2 (the one included):
// No need to redefine $matchid - it was defined in the first file
echo "MATCH ID IS ".$matchid;
Also make sure you add <?php at the beginning of the file (the closing tag is not required). Otherwise it will be treated as text and not executed.
The problem is that you aren't loading that page in the browser when you call the include function, so the variable you are appending is not being processed as a URL query param. You are really just taking everything inside teams.php and dumping it into the other file (the one including teams.php) at that position.
If you want to effectively pass something into teams.php then just declare a variable before the include.
Check out http://php.net/manual/en/function.include.php and all will become clear.
That's not how include's work. When you include a file, it's code is executed as if it was written in the same file it's being included in. So teams.php will have the variable $matchid when the including file has that variable, no need to pass it in. Also the way you called the include was incorrect. Doing what you did causes php to look for a file in the current directory called 'teams.php?id=0' (replace 0 with the $matchid value). This file does not exist, 'teams.php' exists, not the URI. It is possible to specify a url by prefixing it with 'http://' however the result would work with the code in teams.php as it would expect to be able to read the php source.
You can do like this include "include "teams.php?id={$matchid}"; and
$matchid = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING);
echo "MATCH ID IS {$matchid}";
If You will use this code, you will be safe from Injects too!
I hope you will apreciate this.
I want to know how to pass a variable from one page to another in PHP without any form.
What I want to achieve is this:
The user clicks on a link
A variable is passed which contains a string.
The variable can be accessed on the other page so that I can run mysql queries using that variable.
use the get method in the url. If you want to pass over a variable called 'phone' as 0001112222:
<a href='whatever.php?phone=0001112222'>click</a>
then on the next page (whatever.php) you can access this var via:
$_GET['phone']
You want sessions if you have data you want to have the data held for longer than one page.
$_GET for just one page.
<a href='page.php?var=data'>Data link</a>
on page.php
<?php
echo $_GET['var'];
?>
will output: data
You can pass via GET. So if you want to pass the value foobar from PageA.php to PageB.php, call it as PageB.php?value=foobar.
In PageB.php, you can access it this way:
$value = $_GET['value'];
check to make sure the variable is set. Then clean it before using it:
isset($_GET['var'])?$var=mysql_escape_string($_GET['var']):$var='SomeDefaualtValue';
Otherwise, assign it a default value ($var='' is fine) to avoid the error you mentioned.
You can use Ajax calls or $_GET["String"]; Method
If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.
I have a PHP script called customers.php that is passed a parameter via the URL, e.g.:
http://www.mysite,com/customers.php?employeeId=1
Inside my customers.php script, I pick up the parameter thus:
$employeeId = $_GET['employeeId'];
That works just fine. I also have an HTML file with a form that inputs the parameter, and runs another php script, viz:
<form method="post" action="listcustomers.php">
Employee ID: <input name="employeeId" type="text"><br>
<input type="submit" value="Show">
</form>
Then in my listcustomers.php script, I pick up the parameter so:
$employeeId = $_POST['employeeId'];
So far so good. But his is where I am stuck. I want to run my customers.php script, and pass it the parameter that I pave picked up in the form. I am sure this is really simple, but just cannot get it to work. I have tried:
include "customers.php?employeeId=$employeeId&password=password";
But that does not work. Nor does anything else that I have tried. Please help me.
You can't add a query string (Something like ?x=yyy&vv=www) onto an include like that. Fortunately your includes have access to all the variables before them, so if $_GET['employeeId'] is defined before you call:
include 'customers.php';
Then customers.php will also have access to $_GET['employeeId'];
PHP includes are really includes; they attach piece of code from that location to this location.
PaulPRO’s answer most likely tells what you want to achieve, but also other variables would be usable in the included file. So if you define $foo = "bar"; in index.php and include layout.php after that line, you could call this $foo variable in that layout.php file.
If you seriously want to pass an URL to the file, you can insert the URL into variable and in included file parse it with parse_url
EDIT: and yes, I do not suggest adding query params to actual include url as it starts to mess up with GET array and eventually you’ll just be confused what there should be and start smacking your head into wall.
Your include file will have access to the GET variables directly.
You can use $GLOBALS to solve this issue as well.
$tit = "Hello";
$GLOBALS["docTitle"] = $tit;
include ("my.php");
You can pass the value through Session
Like
<?php
$_SESSION['name']='peter';
$_SESSION['age']=28;
include('person_info.php');
?>
In person_info.php, start the session and put all session value in the variable and unset the session.
This is not so clean but this will work if you need to enter a static parameter:
if (true){
echo "<meta http-equiv='refresh' content='0;url=query_source.php?random=red%20bull' />";
}
else
{
echo "<meta http-equiv='refresh' content='0;url=query_source.php?random=blue%20bull' />";
}
Just put it within your source code for the page which calls the query_source.php.
Once again, it is NOT very clean...
I need to use include Function with variable.
but,when I try to do it I faced some errors .
Code :
$year=$_POST['year'];
$month=$_POST['month'];
$day=$_POST['day'];
include "Event.php?year=".$year."&month=".$month."&day=".$day;
so,can U help me ? : )
When you include files, you can't pass them any arguments. However they DO inherit any variables in the current scope (global or method).
I'm guessing at what your code does, but I assume you can just do this:
include "Event.php";
You dont need to use that kind of sintax.
The $year, $month and $day variables will be perfectly visible and accessible on the Event.php file.
To get along with what you want, check PHP manual on http://php.net/manual/en/function.include.php to see some examples.
I'm not sure what you're trying to achieve, but I have a couple of guesses handy.
1 - You are trying to redirect the user, with those parameters appended to the url, in which case you will probably need to utilise header:
header("Location: http://example.com/Event.php?year=$year&month=$month&day=$day");
2 - You are trying to capture the output of that page given the presence of certain GET parameters, in which case you can utilise file_get_contents:
$output = file_get_contents("http://localhost/Event.php?year=$year&month=$month&day=$day");
Include the Event.php directly and access the $_POST or $_GET variables from there.
include('Event.php');
// Event.php:
echo $_POST['year']; // works