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;
}
Related
FILTER_VALIDATE_URL returns true when validating something like: http://example.com or http://www.example.com, but returns false for www.example.com
Is there any flag that would allow urls like www.example.com to be validated as valid? I tried looking in the documentation but there was nothing that could potentially address the problem.
If there is no such flag, what should I use as an alternative method for validating url(s)?
You can pass the string through parse_url, and then adding any elements which are missing, e.g.
if ( $parts = parse_url($url) ) {
if ( !isset($parts["scheme"]) )
{
$url = "http://$url";
}
}
Then you should use $url with FILTER_VALIDATE_URL.
Have a look Here
parse_url
Assuming I have the following URL on a webpage, how I can I utilize the explode() function to give me only the ID, and not the rest of the URL that follows the ID?
file.php?id=12345&foo=bar
I can get the ID, but there's always the following "&foo=bar".
Thanks.
If you need to treat a valid URL, you can use
parse_url
parse_url documentation
to explode the URL into different part (SCHEME, HOST, PORT, USER...)
and then, use
parse_str
parse_str documentation
on the QUERY part, in order to retrieve an array containing all your parameters.
Then, you can catch what you need.
parse_str($_SERVER['QUERY_STRING']);
echo $id;
parse_str will create PHP-variables from query-string variables.
http://www.php.net/manual/en/function.parse-str.php
If it's a full URL, you can use parse_url() to get the query string part.
If it's just a fragment, you can use explode() to get it, then parse_str():
list($path, $qs) = explode('?', $url, 2);
parse_str($qs, $args);
echo $args['id'];
The 2 tells explode() to break the string into a maximum of 2 parts (before and after the ?, in this case).
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
)
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.
I have the following code:
$array = parse_url($_SERVER['HTTP_REFERER']);
$Ur = $array['host'];
which displays the domain just fine, but when I use this with sessions, it doesn't work. Also, I tested it with gettype and it returns Null? I thought it was an array?
Anywho, how do I go about converting the above $Ur into a string?
Cheers!
Whenever you store or access the sessions, you have to call session_start() before you do or you won't see or be able to access the results later.
If you just want the referrer URL as a string, why not:
$url = $_SERVER['HTTP_REFERER'];
?
provide a second component parameter = PHP_URL_HOST to parse_url and it will return a string instead of an array