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).
Related
I have a url (as below). I'd like to get the value of "2". How can I get that?
http://domain.com/site1/index.php/page/2
What you're looking for is a combination of pathinfo and parseurl:
pathinfo(parseurl($url)['path'])['filename'];
pathinfo will break the path into well-defined parts, of which filename is that last part you're looking for (2). If you're looking instaed for the absolute location in the path, you may want to split the path on / and simply get the value at index 3.
We can test this like so:
<?php
$url = "http://domain.com/site1/index.php/page/2";
$value=pathinfo(parse_url($url)['path'])['filename'];
echo $value."\n";
And then on the command line:
$ php url.php
2
I use nathaniel fords example but if you run into a problem where files are named '2.html' some servers will load those even though you have '2'.
You can also do this.
home.php?page=2 as the web address
home.php
<?php
// check to see if $page is set
$page = $POST[page];
$page = preg_replace('/\D/', '', $page);
if(!isset($page)){
query page two stuff or what you need.
}
?>
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'];
?>
A have a delete link which goes to another page, call a function, if the function is successful, then I sent the user back to the page where they clicked delete.
I use this to go back:
if ($booking->deleteBooking($_GET['id']))
{
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
My link would look something like this:
/calendar.php?id=1&month=04&day=25&year=2014&t=11&v=true&f=true&reserved=true
Can I trim the link and remove &reserved=true when it's sent back?
Rather than performing string manipulations that could be prone to error, I suggest that you use PHP's URL functions to parse the HTTP_REFERER header and adjust it accordingly:
// parse the referrer
$referer = parse_url($_SERVER['HTTP_REFERER']);
// parse the querystring part
parse_str($referer['query'], $querystring);
// unset the reserved parameter (only if value is 'true'?)
if ($querystring['reserved'] === 'true') unset($querystring['reserved']);
// reconstruct the revised querystring
$referer['query'] = http_build_query($querystring);
// redirect to the adjusted URL
header('Location: ' . http_build_url($referer));
I suggest you avoid regex and str_replace because they will quickly fall flat when your URL structure changes.
I would put this in a class now because this is not the last time you'll need to do this (I just had to do it last week) or some other URL related thing. So, you should go ahead and encapsulate the functionality in one place now rather than later. You can always change the implementation later in one place if you find a better or more correct way to handle the task.
A few fairly important caveats regarding your script and possible solutions...
HTTP_REFERER can't really be relied upon. Browsers are not required to send it and many do not. You can get around that by sending the URL yourself in the query string (properly escaped) or possibly via a hidden form field. Otherwise, your redirect and script is going to fail in a lot of cases! See HTTP Referer not always being passed
You should always exit after sending a Location header if you want an immediate redirect... otherwise your script will keep chugging along happily doing stuff. (database queries, etc, etc) To that end, I would encapsulate your redirect code as well and have done so in my example solution.
http_build_url is not available by default in PHP. It's a pecl_http thing. Ultimately, it's not really required in this case and my example solution works without it.
Example Class Usage:
$referrer = 'http://example.com/calendar.php?id=1&month=04&day=25&year=2014&t=11&v=true&f=true&reserved=true';
$url = new URL($referrer);
$url->remove_param('reserved');
$url->redirect();
Class Code:
class URL
{
public $url = '';
function __construct ($url)
{
$this->url = $url;
}
function redirect ($response_code = 301)
{
header('Location: ' . $this->url, true, $response_code);
exit;
}
function remove_param ($param)
{
// Do nothing to URL without a Query String (hat tip #eggyal)
if (strpos($this->url, '?') === false) return $this->url;
// Split URL into base URL and Query String
list($url, $query) = explode('?', $this->url, 2);
// Parse Query String into array
parse_str($query, $params);
// Remove the parameter in question
unset($params[$param]);
// Rebuild Query String
$query = http_build_query($params);
// Piece URL back together and save to object
$this->url = $url . ($query ? "?$query" : '');
// Return URL in case developer really just wants an instant result
return $this->url;
}
}
Caveat: This will not retain any URL fragments (ie #fragment) In the case of HTTP_REFERER this should not matter as most browsers won't send that anyway. If that is functionality you decide you need, then it can easily be coded in at a later time.
Namespacing: For simplicity's sake, the code examples are not namespaced. However, for real life implementations, I suggest getting in the habit of using "namespace App;" at the top of any in-house class files and calling the class as such "new App\Class();" Especially if you're using or might ever use any third-party code in your project.
Performance Note: Don't worry about performance until it becomes a problem... your time is always the biggest bottleneck... not PHP. Value your time more than PHP's time! PHP will always be faster than spending your time copy pasta coding. Encapsulate your code (in classes or functions) and have time left to go outside and enjoy the weather now and in the future when you need to re-factor.
use preg_replace
preg_replace('/^&reserved=true/', '', $_SERVER['HTTP_REFERER']);
I am trying to find a way to create a simple dynamic URL, that gets its information from boxes where people enter something.
I got a google search machine and want to refer to it, so basically I wanted two boxes:
One for choosing which directory to search in (the google machine has different directories in its index I want people to be able to choose from those)
and the other for the search term they are looking for.
The URL looks like that:
http://searchengine.xx/search?q=SEARCHTERM&site=DIRECTORY&btnG=Suchen&entqr=0&ud=1&sort=date%3AD%3AL%3Ad1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8
I tried it with PHP like that:
<?php
$directory = $_GET['searchterm'];
echo "http://searchengine.xx/search?q=".$searchterm."&site=directory&btnG=Suchen& entqr=0&ud=1&sort=date%3AD%3AL%3Ad1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8'>URL</a>
?>
This doesnt seem to work well and I wondered if this was possible in any other way (simple HTML, JavaScript maybe?)
try to mix php and htaccess...
<?php
//get the text form the text box and put it in a variable eg.($text)
$url = 'index.php?searchterms=$text';
header("Location: $url");
?>
I think that something like this might work.
Get the text from the text box, then put the text onto a variable (i've used $text to exemplify).
Put the url that you want in a variable (i've used $url to exemplify), but in the end of the url put the text variable the way i did it.
Finally, use the header function to redirect to the url that you want.
Hope i helped
There are several problems with the PHP code in your question. $searchterm is never set and the echo statement is never ended. Try this instead:
<?php
$searchterm = $_GET['searchterm'];
$searchterm = strip_tags($searchterm);
echo "<a href='http://searchengine.xx/search?q=".$searchterm."&site=directory&btnG=Suchen&entqr=0&ud=1&sort=date%3AD%3AL%3Ad1&output=xml_no_dtd&oe=UTF-8&ie=UTF-8'>URL</a>";
?>
The strip_tags will ensure " and ' are removed so it doesn't break your link.
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
)