I'd like to replace content within my page based on the URL parameter.
Ideally I'd like to use PHP to get:
if {{parameter is X}} display {{content X}}
if {{parameter is Y}} display {{content Y}}
..for a few pages.
Current set up:
<?php if ($CURRENT_PAGE == "Index") { ?>
<div id="firstDiv">this is the standard page</div>
<?php } ?>
<?php if ($CURRENT_PAGE == "p1") { ?>
<div id-"secondDiv">this is a variation of the page</div>
<?php } ?>
And using include("includes/content.php"); to call the html blocks to the page
The firstDiv displays in index.php as expected, but adding the URL parameter changes nothing - the same div still shows (I'd like it to be replaced with the secondDiv)
It seems $CURRENT_PAGE doesn't like URL parameters - what is the alternative?
Hopefully this makes sense, I'm pretty new to PHP. Happy to provide more details if required.
Thanks in advance for any help.
-- UPDATE --
Thank you for the answers so far!
It seems I missed part of my own code (Thanks to vivek_23 for making me realise this - I'm using a template, excuse me!!)
I have a config file that defines which page is which, as so:
<?php
switch ($_SERVER["SCRIPT_NAME"]) {
case "index.php/?p=1":
$CURRENT_PAGE = "p1";
break;
default:
$CURRENT_PAGE = "Index";
}
?>
Before I learn $_GET, is there a way I can use my current set up?
Thanks again.
-- UPDATE 2 --
I have switched to using the $_GET method, which seems to be working well so far. My issue now is when the parameter is not set it is giving an undefined error. I'll try to remember to update with the fix.
$p = ($_GET['i']);
if($p == "1"){
echo '<div id="firstDiv"><p>this is the first div</p></div>';
}
Thanks to the two answerers below who suggested using $_GET
You can used $_GET like
if($_GET['p']==1){
echo '<div id="firstDiv">this is the standard page</div>';
}else if($_GET['p']==2){
echo '<div id="secondDiv">this is a variation of the page</div>';
}
The other way! you can used basename() with $_SERVER['PHP_SELF']
//echo basename($_SERVER['PHP_SELF']); first execute this and check the result
if(basename($_SERVER['PHP_SELF']) == 'index'){
echo '<div id="firstDiv">this is the standard page</div>';
}else{
echo '<div id="secondDiv">this is a variation of the page</div>';
}
You need to send the parameters on the URL query string, like:
yourdomain.com?p=1
So, with this URL, the query string is "?p=1", where you have a GET parameter named 'p' with a value of '1'.
In PHP to read a GET parameter you can use the associative array $_GET, like this:
$current_page = $_GET['p'];
echo $current_page; // returns '1'
The rest of your logic is OK, you can display one div or the other based on the value of the p parameter.
You can read more about how to read query string parameters here: http://php.net/manual/en/reserved.variables.get.php
Related
I've been trying to conditionally include a banner which incorporates a form into a php site. Previously the banner was part of the header but I need to exclude it from certain pages in order for other elements to be included.
I'm using $_SERVER['SCRIPT_NAME'] to define a variable on the page and then check for this. I'm a little confused though as to where the variable should be placed. Will it work if placed in the header or does it need to be included in every separate page?
This is what I've got:
<?php $currentPage = $_SERVER['SCRIPT_NAME']; ?>
<?php if ($currentPage != "/ecoProcess.php") {
include ("includes/banner.php");
} else {
echo "ECO";
}
?>
For further info, I've updated the code because of my schoolboy error with -= instead of != but neither of the conditions works now (no banner, no "ECO"). The pages are being called using this method:
<?php if($_GET['action']=='boiler_installation_replacement') {?> class="active"<? php } ?>>Boiler Installation and Replacement
I've been advised to try var_dump which reveals this:
' string(14) "/ths/index.php" ' everytime. I guess this is due to the way the pages are called but I don't know how to get around this.
-= means subtract right value from left side. Eg.
$a = 5;
$a -= 3;
echo $a; // will print 2 because 5 - 3 = 2 :)
Change it to comparison == or better ===. You can also use !=/ !== for opposite cases.
Change your condition like this.
<?php
$currentPage = $_SERVER['SCRIPT_NAME'];
if ($currentPage == "/ecoProcess.php") {
include ("includes/banner.php");
} else {
echo "ECO";
}
?>
Try this:
just change your if statement because it is not logically correct.
Use this
if ($currentPage == "/ecoProcess.php")
instead of
if ($currentPage -= "/ecoProcess.php")
Thanks
I have a link, an offer page and a destination page. I need to carry the variables from the original link and input them into the links on the offer page.
original link
www.example.com/offerpage.php?offer=1&aff_id=var1&aff_sub=var2
Where you see var1 and var2, those could be any number.
I'm assuming I could do something like this (this is a total guess, just want to make sure I do it correctly).
<?php
if(array_key_exists('aff_id', $_GET)){
$aff_id = $_GET;
}
else {
$aff_id = '1';
}
?>
Then the links on the offer page would be
www.offer.com/index.php?offer=1&aff_id=<?php echo $aff_id; ?>&aff_sub=<?php echo $aff_sub; ?>
and whats the correct format for doing multiples?
This should probably do what you want:
if (!array_key_exists('aff_id', $_GET)) {
$_GET['aff_id'] = 1;
}
echo http_build_query($_GET);
If the query string is offerpage.php?offer=1&aff_id=var1&aff_sub=var2then the output will be:
offer=1&aff_id=var1&aff_sub=var2
And, if the query string doesn't contain aff_id, i.e. offerpage.php?offer=1&aff_sub=var2 then the output will be:
offer=1&aff_sub=var2&aff_id=1
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
I am fairly new to PHP and am using a couple of _GET variables to determine page layout/web service data and some other logic on the page. I am not storing the data or writing to a DB of any kind. What kind of sanitization should I be using for this?
For example, one var I'm using is like this:
$querystring = $_SERVER['QUERY_STRING'];
if(isset($_GET['semester']) && $_GET['semester'] != ''){
$listxml = simplexml_load_file("http://path/to/webservice/?".str_replace('semester','term',$querystring));
What's going on there is if the querystring has the ?semester= set and not blank then I replace it with 'term' and pass through the querystring as is to a web service URL (the web service uses the term variable but the term variable interferes with wordpress and redirects to the posts page for that 'term' (tag/category in WP) so I pass it through WP as semester and then just change it to term for the web service call.
So in this case I'm not doing anything with the _GET except passing it on as is to a web service what the web service does with the querystring is out of my hands, but should I 'prep' it in any way for them?
--
I've also got cases similar to this:
$display = '';
if (isset($_GET['display'])) {
$display = $_GET['display']; //set sort via querystring
} else {
$display = 'interest'; //set to default by interest
}
later:
<div id='byalphabet' class='<?php global $display; if($display != 'alphabet'){echo 'hide';} ?>'>
and
<div id="byinterest" class="<?php global $display; if($display != 'interest'){echo 'hide';} ?>">
--
Also using for some dynamic javascript:
$view = '';
if (isset($_GET['view'])) {
$view = $_GET['view']; //set view via querystring
}
Later:
<script>
<?php if ($view != ''){ $view = str_replace('/','',$view); ?>
jQuery('#<?php echo $view; ?>').trigger('click'); //activate view option accordion pane
jQuery('html,body').animate({'scrollTop':jQuery('#<?php echo $view; ?>').offset().top - 50},500); //scrollTo view
</script>
--
Other cases include searching an array for a _GET value array_search($_GET['major'], $slugs); and redirecting a page using:
$parts = explode('/',$_SERVER['REQUEST_URI']);
Header( "HTTP/1.1 301 Moved Permanently" ); //SEO friendly redirect
Header( "Location: http://www.site.ca/programs/outline/".$parts[3]."/" );
Edit: I have read many of the suggested similar questions that popped up but they mostly refer to using the data in some other way such as inserting into a DB.
You should always sanitize input parameters. Even if you aren't using them in the database, you are still vulnerable to cross site scripting/XSS attacks.
<?php $view = $_GET['view'] ?>
<script>jQuery('#<?php echo $view; ?>').trigger('click');</script>
For example given the above code, everything is fine if ?view=page_one because your JavaScript looks like jQuery('#page_one').trigger('click');.
But what if your querystring is ?view=hacked%27)%3B%20alert(document.cookies)%3B%20jQuery(%27%23page_one - now your javascript looks like the following on the page:
jQuery('#hacked'); alert(document.cookies); jQuery('#page_one').trigger('click');
The alert() could just as easily be an AJAX request to send auth tokens, etc to a different server.
Ultimately the type of sanitizing you do depends on the context that you are using the input. In this example, you might want to make sure you escape single quotes for example, but what is appropriate may differ between implementations.
Good article on sanitizing inputs here: http://coding.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/
How would I for example, take a url with some $_GET data, for example http://www.website.com/something?food=steak
How would I then output steak? My current situation is that I'm trying to use the Header function to redirect to a page where I have it so that if $_GET["duplicate"] is equal to 1, then echo this, else, echo nothing. But its not taking the $_GET data I can tell I did a var_dump($_GET);
<?PHP if ($_GET["duplicate"] == 1 )
{
echo "<h1>Username Taken!</h1>";
}
else
{
echo "";
}
?>
The above is using the url http://something.com/register?duplicate=1
It's just a variable, treat it like one:
echo $_GET['food'];
Everything after question mark is available in form of global array $_GET.
$a=$_GET["food"];
echo $a;
also
if url has ?food=steak&color=red;
$a=$_GET["food"];
$b=$_GET["color"];
more than one is possible. Also search for $_POST.
Alright, so I figured my issue out. I have a $_GET variable that gets the end of the page and declares it as "p" for page. I need to do the following to get it to work.
?p=createuser&duplicate=1