Passing parameters via GET to any url in universal way - php

I have back_url given to me from the outside. I need to generate a hash and to make redirect to this back_url with this param: header("Location: $back_url?hash=123sdf"). But the problem is that I don't know the format of back_url.
It may be www.example.com and I do header("Location: $back_url/?hash=123sdf") sj that's fine.
It maybe www.example.com/?param=value and if I do header("Location: $back_url/?hash=123sdf") it's wrong, because it would be www.example.com/?param=value/?hash=123asd.
And so on. The question is: what's the universal way to pass params to back_url ignoring its format?

A complex but very clean way is
Use parse_url() to extract the query string (if any) from the URL into an array
Add hash to the resulting array: $params["hash"] = "1234";
Use http_build_query() to glue the parameters back into a query string
Take all the components returned by parse_url() and glue them back into a full URL
one thing to note is that this dissects the URL into it components and glues it back together, so it's likely it won't work with URLs that are broken in the first place.

Have you tried using http://php.net/manual/en/function.parse-url.php ?

If you have the PECL HTTP extension, use http_build_url:
$url = '...';
$hash = '...';
$new_url = http_build_url($url, array('hash' => $hash), HTTP_URL_JOIN_QUERY);
If you don't have http_build_url, you can use parse_url to find the different parts if a URL. Then it's just a matter of pasting them together. Here's a solution in the manual which can be tailored for your needs.

Well, you would need to detect if $back_url has other query parameters (or GET variables) and append your hash using ?hash=123asd if it hadn't, or using &hash=123asd if indeed it had query parameters.
If you know that $back_url is a full url like http://whatever.com/blah/blah (the important part being http://whatever.com, you can use parse_url to get all components, and then continue with Pekka's answer. If your $back_url doesn't begin with http://..., then prepend the right value (I assume http://$_SERVER['host'] and, again, continue with Pekka's answer.

Wrote this function:
private function addUrlParam(array $params, $url){
$parsed = parse_url($url);
if(!isset($parsed['query']))
{
$slash = '';
if(substr($url, -1) !== '/')
$slash = '/';
$start_with = $slash.'?';
}
else
$start_with = '&';
$scheme = '';
if(!isset($parsed['scheme']))
$scheme = 'http://';
$query = http_build_query($params);
return $scheme.$url.$start_with.$query;
}
Looks like it's perfect for me. Thanks everyone.

Related

Get last word from URL after equals sign

I can't find a solution for this problem. I have this URL http://examplesite.com/?skill-type=new and I want to get the very last word after the = sign, using PHP only. "skill-type" stays the same all the time Thanks in advance :)
This snippet should do:
$url = 'http://examplesite.com/?skill-type=new';
$skillType = explode('&', parse_url($url, PHP_URL_QUERY))['skill-type'];
Check parse_url for more details.
If you meant that the request comes in to that particular url, just use $_REQUEST['skill-type'] to retrieve the value.
Considering you already have the URL in a variable, let's say
$url = 'http://examplesite.com/?skill-type=new;
One possible way (certainly there are others) would be:
$urlArray = explode('=',$url);
$last = $urlArray[sizeof($urlArray)-1];
Note:
only applicable if you don't know how the URL comes, if you do, consider on using $_GET
Use the PHP $_GET Global Variable
$skill_type = $_GET['skill-type'];
PHP will automatically parse GET variables for you. To access the value of the skill-type variable, you need only use $_GET['skill-type']. For instance:
echo $_GET['skill-type'];
Will display
new
Generate your url by $_SERVER variable and then split it like this
$url = "http://examplesite.com/?skill-type=new";
$array = explode("=", $url);
$last_word = $array[1];
Use substr (url, posstr (url,'=')+1) or if this is the page being loaded $_GET ['skill-type']

Check whether the URL scheme is HTTP or HTTPS

I'm using the following code to add http:// to the URL.
(substr(strtolower($url), 0, 7) == 'http://'?"":"http://").$url
but how can I check whether the original URL contains https? I don't want to use an OR clause.
preg_match("#^https?://#", $url)
Answer
echo parse_url($url, PHP_URL_SCHEME);
Reference
docs https://www.php.net/manual/en/function.parse-url.php
parse_url(string $url, int $component = -1): mixed
parse_url function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial and invalid URLs are also accepted, parse_url() tries its best to parse them correctly.
Use preg_match and a regular expression on your url :
preg_match(^http(s)?://);
If it returns true, then your URL is ok, whether it uses http of https.
strncmp($url, 'https:', 6) === 0
!empty($_SERVER['HTTPS']) ? 'https' : 'http'
I think the best way is to use parse_url() function.
Like this :
if (empty($url['scheme'])) {
$url = 'https://' . $url;
}

Get parts of URL in PHP

I am just wondering what the best way of extracting "parameters" from an URL would be, using PHP.
If I got the URL:
http://example.com/user/100
How can I get the user id (100) using PHP?
To be thorough, you'll want to start with parse_url().
$parts=parse_url("http://example.com/user/100");
That will give you an array with a handful of keys. The one you are looking for is path.
Split the path on / and take the last one.
$path_parts=explode('/', $parts['path']);
Your ID is now in $path_parts[count($path_parts)-1].
You can use parse_url(), i.e.:
$parts = parse_url("http://x.com/user/100");
$path_parts= explode('/', $parts[path]);
$user = $path_parts[2];
echo $user;
# 100
parse_url()
This function parses a URL and returns an associative array containing
any of the various components of the URL that are present. The values
of the array elements are not URL decoded.
This function is notmeant to validate the given URL, it only breaks it
up into the above listed parts. Partial URLs are also
accepted, parse_url() tries its best to parse them correctly.
$url = "http://example.com/user/100";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
I know this is an old thread but I think the following is a better answer:
basename(dirname(__FILE__))

PHP Get From URL

I was wondering how I could remove a certain part of a url using PHP.
This is the exact url in questions:
http://www.mysite.com/link/go/370768/
I'm looking to remove the number ID into a variable.
Any help would be great, Thanks!
There are many (many!) ways of extracting a number from a string. Here's an example which assumes the URL starts with the format like http://www.mysite.com/link/go/<ID> and extracts the ID.
$url = 'http://www.mysite.com/link/go/370768/';
sscanf($url, 'http://www.mysite.com/link/go/%d', $id);
var_dump($id); // int(370768)
Use explode()
print_r(explode("/", $url));
You could use mod_rewrite inside of your .htaccess to internally rewrite this URL to something more friendly for PHP (convert /link/go/370768/ into ?link=370768, for example).
I suspect that you are using some kind of framework. There are two ways to check the $_GET variables:
print_r($_GET);
or check the manual of the manual of the framework and see how the GET/POST is passed internally, for example in CakePHP you have all parameters save internally in your controller you can access them like that:
$this->params['product_id'] or $this->params['pass']
There is another solution which is not very reliable and professional but might work:
$path = parse_url($url, PHP_URL_PATH);
$vars = explode('/', $path);
echo $vars[2];
$vars should contain array like this:
array (
0 => link
1 => go
2 => 370768
)

How can I replace a variable in a get query in PHP?

I have an URL
http://example.com/test?xyz=27373&page=4&test=5
which I want to tranform by replacing the page=4 through page=XYZ
how can I do that with preg_replace?
Yes, you can use
$oldurl = "http://test.com/test?xyz=27373&page=4&test=5"
$newurl = preg_replace("/page=\d+/", "page=XYZ", $oldurl);
Or you can reconstruct the URL from $_GET superglobal.
Do you want to set the value of xyz to the page value? I think you might need to specify a bit more. But this is easy to modify if you dont know regex.
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
$urlQuery = parseUrl($url, PHP_URL_QUERY);
parse_str($urlQuery, $queryData);
$queryData['page'] = $queryData['xyz'];
unset($queryData['xyz']);
$query = http_build_query($queryData);
$outUrl = substr_replace($url, $query, strpos($url, '?'));
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
preg_match('/xyz=([^&]+)/', $url, $newpage);
$new = preg_replace('/page=([^&]+)/', $newpage[0], $url);
$new = preg_replace('/xyz=([^&]+)&/', '', $new);
This will turn
http://test.com/test?xyz=27373&page=4&test=5
into
http://test.com/test?page=27373&test=5
Forgive me if this isn't what you were looking to do, but your question isn't quite clear.
I'm sure you could do something with a regular expression. However, if the URL you've given is the one you're currently handling, you already have all the request variables in $_Request.
So, rebuild the URL, replacing the values you want to replace, and then redirect to the new URL.
Otherwise, go find a regexp tutorial.
If this is your own page (and you are currently on that page) those variables will appear in a global variable named $_GET, and you could use something like array_slice, unset or array_filter to remove the unwanted variables and regenerate the URL.
If you just have that URL as a string, then what exactly are the criteria for removing the information? Technically there's no difference between
...?xyz=27373&page=4&test=5
and
...?test=5&xyz=27373&page=4
so just removing all but the first parameter might not be what you want.
If you want to remove everything except the xyz param. Take a look at parse_url and parse_str
What exactly are you trying to do? The question is a little unclear.
$XYZ = $_GET['xyz'];
$PAGE = $_GET['page'];
?
Are wanting to replace each value with another, or replace both with one?

Categories