PHP $_SERVER and urls? - php

How can I get my full current url in php but minus all querystrings?
Example
echo 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
Would echo something like assuming query strings were in place...
http://www.example.com/example?tab=foo&dslip=yes
How can I get the same as above but cut off all the query strings?
How is this done in php.
Thanks.

PHP_SELF is what you need I believe.
echo('http' . ((empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF']);
Or the __FILE__ constant, depending on your exact configuration and situation.

Try this
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$part = explode('?',$url);
echo $part[0];

I think the solution is this:
echo 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
the $_SERVER['SCRIPT_NAME'] variable returns path of your script without the query string like you want.
if you like to see all variables available in php just try this
phpinfo();
Best regards

Related

How to replace GET parameters in URL

For example, if I have a URL http://example.com/?src=example&test_28934
How do I remove everything after ?, so the user always lands on http://example.com?
I have tried this and the URL stays the same.
$current_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$current_url = reset((explode('?', $current_url)));
You should check this https://www.php.net/manual/en/function.substr.php
and this Remove portion of a string after a certain character
For your example it will be
$current_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$current_url = substr($current_url, 0, strpos($current_url, "?"));
header("Location: " . "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "?");

How to make Canonicals with PHP

I've search around on SO, but can't find an exact answer to my needs.
Generating a URL is pretty easy...
Like so:
<link rel="canonical" href="https://example.com<?php echo ($_SERVER['REQUEST_URI']); ?>" />
But, the issue with this is, the $_SERVER['REQUEST_URI']) will always fetch the current file in use, so the canonical URL could potentially change.
So it could flick between www.example.com/hello.php and www.example.com/hello/, and many other variations depending on how the user accesses your site.
How do I make it so it's always the same url? (preferably without .php)
Worked it out myself, pretty basic:
<?php
$fullurl = ($_SERVER['REQUEST_URI']);
$trimmed = trim($fullurl, ".php");
$canonical = rtrim($trimmed, '/') . '/';
?>
Then...
<link rel="canonical" href="https://example.com<?php echo $canonical ?>" />
I'm sure there's different methods, but it works for me.
This is what i do.
<?php
// get the rigth protocol
$protocol = !empty($_SERVER['HTTPS']) ? 'https' : 'http';
// simply render canonical base on the current http host ( multiple host ) + requests
echo $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
I think your scripts require a bit of sanitisation, am I right?
I mean, if your page is
https://example.com/test.php
but a malicious - but harmless - person does
https://example.com/test.php/anotherThing.php
your canonical would become
https://example.com/anotherThing.php
you wouldn't want that to happen, though, am I right? Especially if the malicious person is not harmless and does worst things with your urls...
This will remove query parameters like ?search=abc&page=32
Option 1:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . strtok($_SERVER['REQUEST_URI'], '?');
Option 2 (does the same) :
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
Then echo
echo '<link rel="canonical" href="' . $url . '" />';

Replace part of URL within PHP variable

I am using PHP to set the current URL as a variable using
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
This would echo the string:
http://www.example.com/landing-page-demo/
I would like to replace the 'landing-page' part of the string with 'confirmation-page' and then save this updated URL as another variable.
I was thinking of using str replace, is this the most ideal method of doing this? Not sure how to approach the problem
Indeed, short of knowing regular expressions, str_replace will do the trick.
Perform str_replace on $_SERVER['REQUEST_URI']
Example:
$url = 'http://' . $_SERVER['SERVER_NAME'] . str_replace("landing", "confirmation", $_SERVER['REQUEST_URI']);
My current solution using Str Replace:
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; // Full URL var
$redirecturl = str_replace("landing","confirmation", $url);
Using str_replace is the easiest solution however you can do your logic with pathinfo($url)
$url = "http://www.example.com/landing-page-demo/";
$newURL = str_replace('landing', 'confirmation', $url);
echo $newURL;

How to safely get full URL of parent directory of current PHP page

I'm using:
$domain = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
$themeurl = $domain . $path;
But this of course gives the full URL.
Instead I need the full URL minus the current file and up one directory and minus the trailing slash.
so no matter what the browser URL domain is eg localhost, https://, http://, etc that the full real (bypassing any mod rewrites) URL path of the parent directory is given without a trailing slash.
How is this done?
Safely so no XSS as I guess (from reading) using anything but 'SCRIPT_NAME' has such risk.. not sure though ofc.. just been reading a ton trying to figure this out.
examples:
if given:
https://stackoverflow.com/questions/somequestions/index.php
need:
https://stackoverflow.com/questions
without the trailing slash.
and should also work for say:
http://localhost/GetSimple/admin/load.php
to get
http://localhost/GetSimple
which is what I'm trying to do.
Thank you.
Edit:
Here's the working solution I used:
$url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= htmlspecialchars($_SERVER['REQUEST_URI']);
$themeurl = dirname(dirname($url)) . "/theme";
it works perfectly.
Thats easy - using the function dirname twice :)
echo dirname(dirname('https://stackoverflow.com/questions/somequestions/index.php'));
Also note #Sid's comment. When you you need the full uri to the current script, with protocol and server the use something like this:
$url = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= $_SERVER['REQUEST_URI'];
echo dirname(dirname($url));
I have more simple syntax to get parent addres with port and url
lets try my code
dirname($_SERVER['PHP_SELF'])
with this code you can got a direct parent of adres
if you want to 2x roll back directory you can looping
dirname(dirname($_SERVER['PHP_SELF']))
dirname is fungtion to get parent addrest web and $_SERVER['PHP_SELF'] can showing current addres web.
thakyou Sir https://stackoverflow.com/users/171318/hek2mgl
I do not suggest using dirname()as it is for directories and not for URIs. Examples:
dirname("http://example.com/foo/index.php") returns http://example.com/foo
dirname("http://example.com/foo/") returns http://example.com
dirname("http://example.com/") returns http:
dirname("http://example.com") returns http:
So you have to be very carful which $_SERVER var you use and of course it works only for this specific problem. A much better general solution would be to use currentdir() on which basis you could use this to get the parent directory:
function parentdir($url) {
// note: parent of "/" is "/" and parent of "http://example.com" is "http://example.com/"
// remove filename and query
$url = currentdir($url);
// get parent
$len = strlen($url);
return currentdir(substr($url, 0, $len && $url[ $len - 1 ] == '/' ? -1 : $len));
}
Examples:
parentdir("http://example.com/foo/bar/index.php") returns
http://example.com/foo/
parentdir("http://example.com/foo/index.php") returns http://example.com/
parentdir("http://example.com/foo/") returns http://example.com/
parentdir("http://example.com/") returns http://example.com/
parentdir("http://example.com") returns http://example.com/
So you would have much more stable results. Maybe you could explain why you wanted to remove the trailing slash. My experience is that it produces more problems as you are not able to differentiate between a file named "/foo" and a folder with the same name without using is_dir(). But if this is important for you, you could remove the last char.
This example works with ports
function full_url($s)
{
$ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
$sp = strtolower($s['SERVER_PROTOCOL']);
$protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
$port = $s['SERVER_PORT'];
$port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
$host = isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];
return $protocol . '://' . $host . $port . $s['REQUEST_URI'];
}
$themeurl = dirname(dirname(full_url($_SERVER))).'/theme';
echo 'Theme URL';
Source: https://stackoverflow.com/a/8891890/175071
I'm with hek2mgl. However, just in case the script isn't always specifically 2 directories below your target, you could use explode:
$parts = explode("/",ltrim($_SERVER['SCRIPT_NAME'],"/"));
echo $_SERVER['HTTP_HOST'] . "/" . $parts[0];
As hek2mgl mentioned, it's correct, and a more dynamic approach would be dirname(dirname(htmlspecialchars($_SERVER['REQUEST_URI'])));.
EDIT:
$_SERVER['REQUEST_URI'] will omit the domain name. Referring #hek2mgl's post, you can echo dirname(dirname(htmlspecialchars($url)));
Here are useful commands to get the desired path:
( For example, you are executing in http:// yoursite.com/folder1/folder2/file.php)
__FILE__ (on L.Hosting) === /home/xfiddlec/http_docs/folder1/folder2/yourfile.php
__FILE__ (on Localhost) === C:\wamp\www\folder1\folder2\yourfile.php
$_SERVER['HTTP_HOST'] === www.yoursite.com (or without WWW)
$_SERVER["PHP_SELF"] === /folder1/folder2/yourfile.php
$_SERVER["REQUEST_URI"] === /folder1/folder2/yourfile.php?var=blabla
$_SERVER["DOCUMENT_ROOT"] === /home/xfiddlec/http_docs
// BASENAME and DIRNAME (lets say,when __file__ is '/folder1/folder2/yourfile.php'
basename(__FILE__) ==== yourfile.php
dirname(__FILE__) ==== /folder1/folder2
Examples:
*HOME url ( yoursite.com )
<?php echo $_SERVER['HTTP_HOST'];?>
*file's BASE url ( yoursite.com/anyfolder/myfile.php )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; ?>
*COMPLETE current url ( yoursite.com/anyfolder/myfile.php?action=blabla )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];?>
*CURRENT FOLDER's URL ( yoursite.com/anyfolder/ )
<?php echo $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']); ?>
*To get RealPath to the file (even if it is included) (change /var/public_html to your desired root)
<?php
$cur_file=str_replace('\\','/',__FILE__); //Then Remove the root path::
$cur_file=preg_replace('/(.*?)\/var\/public_html/','',$cur_file);
?>
p.s.for wordpress, there exist already pre-defined functions to get plugins or themes url.
i.e. get plugin folder ( http://yoursite.com/wp-content/plugins/pluginName/ )
<?php echo plugin_dir_url( __FILE__ );?>

How can I get the full URL in PHP?

How can I get the full URL, like http://www.domain.com/page.php?id=someid&page=1, not just http://www.domain.com/page.php?
$_SERVER['QUERY_STRING'] has the query string portion of the URL.
A quick answer:
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];

Categories