GET URL parameter in PHP - php

I'm trying to pass a URL as a url parameter in php but when I try to get this parameter I get nothing
I'm using the following url form:
http://localhost/dispatch.php?link=www.google.com
I'm trying to get it through:
$_GET['link'];
But nothing returned. What is the problem?

$_GET is not a function or language construct—it's just a variable (an array). Try:
<?php
echo $_GET['link'];
In particular, it's a superglobal: a built-in variable that's populated by PHP and is available in all scopes (you can use it from inside a function without the global keyword).
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['link'])) {
echo $_GET['link'];
} else {
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'link', FILTER_SANITIZE_URL);
Last but not least, you can use the null coalescing operator (available since PHP/7.0) to handle missing parameters:
echo $_GET['link'] ?? 'Fallback value';

Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...

Use this:
$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;
Or just use:
$parameter = $_GET['link'];
echo $parameter ;

To make sure you're always on the safe side, without getting all kinds of unwanted code insertion use FILTERS:
echo filter_input(INPUT_GET,"link",FILTER_SANITIZE_STRING);
More reading on php.net function filter_input, or check out the description of the different filters

The accepted answer is good. But if you have a scenario like this:
http://www.mydomain.me/index.php?state=California.php#Berkeley
You can treat the named anchor as a query string like this:
http://www.mydomain.me/index.php?state=California.php&city=Berkeley
Then, access it like this:
$Url = $_GET['state']."#".$_GET['city'];

I was getting nothing for any $_GET["..."] (e.g print_r($_GET) gave an empty array) yet $_SERVER['REQUEST_URI'] showed stuff should be there. In the end it turned out that I was only getting to the web page because my .htaccess was redirecting it there (my 404 handler was the same .php file, and I had made a typo in the browser when testing).
Simply changing the name meant the same php code worked once the 404 redirection wasn't kicking in!
So there are ways $_GET can return nothing even though the php code may be correct.

$Query_String = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)
Array
(
[ 0] => link=www.google.com
)

Related

Ajax php return include [duplicate]

i code the following
<?php
if ($id = mysql_real_escape_string(#$_GET['pid'])
&& $uid = mysql_real_escape_string(#$_GET['file']))
echo include "foo.php";
else
echo include "bar.php";
?>
When I use the include function in conjunction with a function that's designed to output to the page (e.g., or echo include 'foo.php'), it returns the include but with a "1" after the content that has been included.
echo include "foo.php"
should be
include 'foo.php';
Note that this can also happen when using include with shorthand echo:
<?= include 'foo.php'; ?>
This will also print out the return value of 1 when used inside a script. To get rid of this you need to use the regular PHP opening tag like so:
<?php include 'foo.php'; ?>
PHP will now include the contents of the file without printing the return value.
Okey so the answers here are actually not entirely correct; in some sense even misleading.
include takes the contents of the file and places them in context. One of the more common uses is to pass variable scope around, ie. passing scoped variables in your view by including them in the handler and using include on the view. Common, but there are also other uses; you can also return inside a included file.
Say you have a file like this:
<?php return array
(
'some',
'php'
'based'
'configuration',
'file'
); # config
Doing $config = include 'example-config-above.php'; is perfectly fine and you will get the array above in the $config variable.
If you try to include a file that doesn't have a return statement then you will get 1.
Gotcha Time
You might think that include 'example-config-above.php'; is actually searching for the file in the directory where the file calling the include is located, well it is, but it's also searching for the file in various other paths and those other paths have precedence over the local path!
So if you know you had a file like the above with a return inside it, but are getting 1 and potentially something like weird PEAR errors or such, then you've likely done something like this:
// on a lot of server setups this will load a random pear class
include 'system.php'
Since it's loading a file with out a return you will get 1 instead of (in the case of our example) the configuration array we would be expecting.
Easy fix is of course:
include __DIR__.'/system.php'
That is because the include function returns 1 on success. You get, as you say, 'my name is earl1' because the code inside the included file runs first, printing 'my name is earl' and then you local echo runs printing the return value of include() which is 1.
Let the file.txt contain xxx
echo include("file.txt");
This returns,
xxx1
The '1' is the return value of the include function, denoting the success that the file is accessed. Otherwise it returns nothing, in this case parse error is thrown.
echo print "hello";
This too returns,
hello1
Same as above; '1' denoting the success,it's printed.
echo echo "hello";
print echo "hello";
Both the above cases produces an error.
Since the echo function has no return value, hence undefined.
echo echo "hello"; print echo "hello";
(1st) (2nd)
Now the second 'echo' in the both cases produces an undefined.The first 'echo' or 'print' can't take in the hello output with the undefined (produced by the second echo).
A verification:
if((print "hello")==1)
echo "hey!";
output: hellohey! ('echo' in the 2nd line can be a print, it doesn't matter)
Similarly,
if((include ("file.txt"))==1)
echo "hey!";
output: xxxhey!
Other hand,
if((echo "hello")==1)
echo "hey!";
output: an error
In the first two cases the functions (print and include) returned 1, in the third case 'echo' produces no return value (undefined) hence the third case produces an error.
Well... I am using Codeigniter(php frame work). And I encountered the same problem. What I concluded is that when we try to print/echo the include method then it prints 1 on screen and when we just simply write the include command(example given below) it will only do what it is supposed to do.
<?php include('file/path'); ?> // this works fine for me
<?= include('file/path'); ?> // this works fine but prints "1" on screen
Hope my explaination will be helful to someone
= is assigning operator
== is for checking equal to
check for php operators
I have solved it returning nothing at the end of the included file:
$data = include "data-row.php";
return $data;
Inside data-row.php:
<div>etc</div>
...
<?php return; //End of file
I found the selected answer from this thread very helpful.
Solution 1
ob_start();
include dirname( __FILE__ ) . '/my-file.php';
$my_file = ob_get_clean();
You might also find this thread about the ob_start() function very insightful.
Solution 2
Add a return statement in the file that is being included.
E.g my-file.php
<?php
echo "<p>Foo.</p>";
return;
Drawn from the answer provided by #gtamborero.
To help you understand it the way I do now, just take this oversimplification:
There should always be a return statement otherwise include will return 1 on success.
Happy coding!
M5
Use return null in foo.php and bar.php
echo substr(include("foo.php"),1,-1);

How to get some portion in the url?

I am working in php. I want to get some portion of the url using php,
For Example, my url is "http://localhost:82/index.php?route=product/product&path=117&product_id=2153". i want route=product/product only.
Since the variable might not exist, you could (and should) ensure your code does not trigger notices with:
<?php
if (isset($_GET['route'])) {
$route = $_GET['route'];
}else{
// Fallback behaviour goes here
}
Alternatively, if you want to skip manual index checks and maybe add further validations you can use the filter extension:
<?php
echo filter_input(INPUT_GET, 'route');
You can read it using $_REQUEST as below:
<?php
echo $_REQUEST['route'];
?>
It sounds like simply $_GET['route'] will work, although that will only give you product/product. You can just fill in the rest yourself if you know the name of the parameter.
Those URL parameters are called get variables. You can retrieve them using the super global $_GET like so
$route = $_GET['route'];
try this,
<?php
$ans=$_GET['route'];
echo $ans;
?>
Using the following code,
<?php
if(isset($_REQUEST["route"]))
echo $_REQUEST['route'];
?>

Using URL as a condition on php

I want to show on my site an element depending on my site's url.
Currently i have the following code:
<?php
if(URL matches)
{
echo $something;
}
else
{
echo $otherthing;
}
?>
I wanted to know how do I get the URL on the if condition, because I need to have only one php archive to show on many diferent pages
EDIT: The solution provided by Rixhers Ajazi doesnt work for me, when i use ur code i get the same URI for both of my pages, so the if sentence always goes by the else side, is any way to get the exact string u can see on the browser to the PHP code
http://img339.imageshack.us/img339/5774/sinttulocbe.png
This is the place where it changes but, the URL i get on both sides is equal, im a little bit confused
To get the URL, use:
$url = http://$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Use following syntax with URL
http://mysite.com/index.php?var1=val&var2=val
Now you can get the values of variables in your $_GET variable and use in if condition like
if($_GET['var1'])
You can do so by using the $_SERVER method like so :
$url = $_SERVER['PHP_SELF']; or $url = $_SERVER['SERVER_NAME'];
Read up on this more here
if($url == 'WHATEVER')
{
echo $something;
}
else
{
echo $otherthing;
}
?>
You can use different variables, e.g., $_SERVER["PHP_SELF"], or $_SERVER["REQUEST_URI"]. The first one contains the path after the server name and until a possible ? in the URL (the part with the GET parameters is excluded). The second one contains also the GET parameters. You can also retrieve the hostname used to connect to the server (in case you have a virtual host situation) using $_SERVER["HTTP_HOST"]. Therefore by concatenating all these you can reconstruct the full URL (if you really need it, maybe the script name is enough).

link using $_GET whilst using isset cant find page

Im currently trying to get a link:
<a href='?p=bid?Sale_ID=$Sale_ID'>BID</a>
to work but I keep getting a "Page you are requesting doesn´t exist" message, this page works if i use this link:
<a href='include/bid.php?Sale_ID=$Sale_ID'>BID</a>
this leads me to believe that my problem lies with the isset im using to include pages on link:
<?php
if (isset($_GET['p']) && $_GET['p'] != "") {
$p = $_GET['p'];
if (file_exists('include/'.$p.'.php')) {
#include ('include/'.$p.'.php');
} elseif (!file_exists('include/'.$p.'.php')) {
echo 'Page you are requesting doesn´t exist<br><br>';
}
} else {
#include ('include/login-form.php');
}
?>
Ive tried adding another isset replacing p with q which just throws my pages in to dissaray.
So my question is, is there a way around this?
Thanks
You have two question marks here:
?p=bid?Sale_ID=$Sale_ID
Multiple querystring parameters are separated by ampersand:
?p=bid&Sale_ID=$Sale_ID
The query string you show: ?p=bid?Sale_ID=$Sale_ID is not valid. The structure of a URL with a string is:
filename.extension?first_parameter=first_value&second_parameter=second_value
So, if you want p to indicate which page:
?p=bid&Sale_ID=$Sale_ID
.. use the ampersand (&) to separate your query string values.
Also, please note that the approach you are using to include a file is insecure. What if I sent this:
?p=../../.htpasswd&Sale_ID=0
An attacker could use this method to output the contents of files that you do not wish to expose to the public. Make sure you are checking the value of this variable more carefully before blinding including the file.
I also wants to warn you against using the error suppressor (#). Errors are your friends! You want to know exactly what happens in your code, using the error suppressor prevents critical problems from being brought to your attention. Really -- never, ever use the error suppressor. Instead of #include, use include
I suggest something more like this:
$file_exists = false;
$page = false;
if (
isset($_GET['p']) &&
strlen(trim($_GET['p'])) > 0
){
$page = preg_replace("/[^a-zA-Z0-9 ]/", "", $_GET['p']);
$page = str_replace(" ", "-", $page);
$file_exists = file_exists('include/'.$page.'.php');
if ($file_exists) {
include ('include/'.$page.'.php');
} else {
$page = false;
echo 'Page you are requesting doesn´t exist<br><br>';
}
}
if (!$file_exists ||$page === false)
include ('include/login-form.php');
The first part of the code ensures that the query string value exists and has some content. Then it cleans out any non-alphanumeric characters (this helps prevent exploitation). Then, we check to see if it exists, storing that result in a variable so we can use it again.
If the page exists, the file is included. If not, a "page not found" message is output, and the login form file is included. If no page is specified in the query string, the login form file is included.
Documentation
$_GET - http://php.net/manual/en/reserved.variables.get.php
Query string on Wikipedia - http://en.wikipedia.org/wiki/Query_string
Exploiting PHP File Inclusion - an article about security when using include and $_GET - http://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/
preg_replace - http://php.net/manual/en/function.preg-replace.php
str_replace - http://php.net/manual/en/function.str-replace.php
?p=bid "redirects" to your default file, usually index.php. You want it to work in bid.php.
You can set the default file in apache with:
DirectoryIndex index.php bid.php
The other problem is you use multiple ? signs.
?p=bid&Sale_ID=$Sale_ID would work a lot better
Keep in mind that file_exists does not use the include path, so you should be doing this:
if (file_exists( get_include_path() . 'include/'.$p.'.php')) {
More info:
http://ca2.php.net/manual/en/function.file-exists.php

Pass multiple variables via URL and reading all of them on next page

I have a link that points to a webpage e.g. "land.php".
The link looks like this:
link
this takes me to the page land.php where I can read the first parametere with $id (and it is equal to 1, correctly), but I cannot read the second one. I either tried with $cd or $_GET['cd']. None of them works.
if I tried isset($cd) it says false. Same thing for isset($_GET['cd']).
How can I pass the second parameter too (and read it!)?
EDIT:
some code (so people are happy. I think it's pointless in this case..).
land.php
<?php
if($_GET['cd']==a)
echo "<h2>HI</h2>";
else
echo "<h2>BY</h2>";
?>
if I use $cd instead of $_GET['cd'] it doesn't work anyway..
EDIT2 I don't get any syntax error, it just doesn't behave how expected.
The value is stored in $_GET['cd'].
Try printing out the $_GET array, with print_r($_GET);
print_r($_GET) should output
Array
(
[id] => 1
[cd] => a
)
This should ofcourse be in the land.php page, as the get variables are only available in the requested page.
Your server might be set up to accept semicolon instead of ampersands. Try replacing & with ;
$_GET['cd'] is the correct syntax. Are you actually on the land.php page, ie does your browser's address bar read something like
example.com/land.php?id=1&cd=a
Also, it looks like you have register_globals enabled if you can read $id. This is a very bad idea.
Update
Your code snippet contains syntax errors. I recommend the following, including enabling decent error reporting for development
ini_set('display_errors', 'On');
error_reporting(E_ALL);
if(isset($_GET['cd']) && $_GET['cd'] == 'a') {
echo "<h2>HI</h2>";
} else {
echo "<h2>BY</h2>";
}

Categories