How can I add http:// to a URL if it doesn't already include a protocol (e.g. http://, https:// or ftp://)?
Example:
addhttp("google.com"); // http://google.com
addhttp("www.google.com"); // http://www.google.com
addhttp("google.com"); // http://google.com
addhttp("ftp://google.com"); // ftp://google.com
addhttp("https://google.com"); // https://google.com
addhttp("http://google.com"); // http://google.com
addhttp("rubbish"); // http://rubbish
A modified version of #nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://, ftps://, http:// and https:// in a case insensitive way.
At the time of writing, none of the answers used a built-in function for this:
function addScheme($url, $scheme = 'http://')
{
return parse_url($url, PHP_URL_SCHEME) === null ?
$scheme . $url : $url;
}
echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"
See also: parse_url()
Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.
if (false === strpos($url, '://')) {
$url = 'http://' . $url;
}
Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.
The best answer for this would be something like this:
function addhttp($url, $scheme="http://" )
{
return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}
The protocol flexible, so the same function can be used with ftp, https, etc.
Scan the string for ://. If it does not have it, prepend http:// to the string... Everything else just use the string as is.
This will work unless you have a rubbish input string.
Try this. It is not watertight1, but it might be good enough:
function addhttp($url) {
if (!preg_match("#^[hf]tt?ps?://#", $url)) {
$url = "http://" . $url;
}
return $url;
}
1. That is, prefixes like "fttps://" are treated as valid.
nickf's solution modified:
function addhttp($url) {
if (!preg_match("#^https?://#i", $url) && !preg_match("#^ftps?://#i", $url)) {
$url = "http://" . $url;
}
return $url;
}
<?php
if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];
}
$url = $_POST['url'];
?>
This code will add http:// to the URL if it’s not there.
Related
I have a problem with checking the URI. I would like to create a pattern that will accept such a URI:
?name=key&name=key
#anchor
foo?name=key&name=key
foo#anchor
foo/bar/*
foo/bar?name=key&name=key
foo/bar#anchor
At the moment I have something like this:
$path = 'foo';
$uri = 'foo/bar/bb';
preg_match('/^('.$path.'[^\w])[\/\w\S]+$/i', $uri);
// OR
preg_match('/^('.$path.'|'.$path.'(\?|#)[\w\S\=\.&%-]+)$/i', $uri);
I would like to simplify it somehow. Thank you in advance for your help.
If you getting full url then it'll work.
You can use filter_var with FILTER_VALIDATE_URL
Snippet
$url = "https://stackoverflow.com/questions/53304342/checking-the-uri-php";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "$url is a valid URL";
} else {
echo"$url is not a valid URL";
}
Live demo
filter_var
I'm getting a url from a form, this way:
$input_website = isset($_POST['website']) ? check_plain($_POST['website']) : 'None';
I need to get back a naked domain name(for some API integration), for example: http://www.example.com will return as example.com
and www.example.com will return example.com etc.
I have this code now, that returns the correct url for the first case http://www.example.com but returns nothing for www.example.com or even example.com:
function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
}
return false;
}
Can you please advice on the matter?
As per discussion with you:
$url = 'www.noamddd.com';
$arrUrl = explode("/", $url);
echo $arrUrl[0];
Old Answer:
Make a function with the following code block and get the domain names.
Try this
more about parse_url
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
print $parse['host']; //google.com
Also you can do this in another way:
echo $domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));//google.com
If you just have the URL (and not want the current domain name like frayne-konok suggests) and want to extract the server name, you can use a regular expression like this:
$serverName = preg_replace('|.*?://(.*?)/.*|', '$1', $url);
I ended up doing something a bit different - checking if there is http and if not, i'm adding it using this function:
function addHttp($website) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $website;
}
and only then i'm sending it to my other function that return the domain.
For sure not the best way, but it works.
I have a function which is used to add an http:// to a url,which do not have a http:// like as below
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
My problem is ,
If i pass a url with &,the string after the & will skipped,
eg:
https://www.example.com/Welcome/Default.aspx?scenarioID=360&pid=3308&treeid=1000
Returns
https://www.example.com/Welcome/Default.aspx?scenarioID=360
I lose &pid=3308&treeid=1000 this part,How to fix this error??
I am unable to reproduce the error using PHP 5.5. However, personally I don't like to use a regular expression when there are built in functions that do the job. The following should work just fine as a replacement for the regular expression ~^(?:f|ht)tps?://~i:
<?php
function addhttp($url, $https=false) {
$protocols = ['https://', 'http://', 'ftps://', 'ftp://'];
$heystack = strtolower(substr($url, 0, 8));
foreach ($protocols as $protocol) {
if (strpos($heystack, $protocol) === 0) {
return $url;
}
}
return ($https ? 'https://' : 'http://') . $url;
}
$url = 'www.example.com/Welcome/Default.aspx?scenarioID=360&pid=3308&treeid=1000';
// for http://
echo addhttp($url);
// for https://
echo addhttp($url, true);
I added an optional parameter here, if you don't like it just take it out and remove the ternary expression (<expression> ? true : false).
If you need to get the value of the URL see this question
Note: I'm using an older PHP version so FILTER_VALIDATE_URL is not available at this time.
After many many searches I am still unable to find the exact answer that can cover all URL structure possibilities but at the end I'm gonna use this way:
I'm using the following function
1) Function to get proper scheme
function convertUrl ($url){
$pattern = '#^http[s]?://#i';
if(preg_match($pattern, $url) == 1) { // this url has proper scheme
return $url;
} else {
return 'http://' . $url;
}
}
2) Conditional to check if it is a URL or not
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i", $url)) {
echo "URL is valid";
}else {
echo "URL is invalid<br>";
}
Guess What!? It works so perfect for all of these possibilities:
$url = "google.com";
$url = "www.google.com";
$url = "http://google.com";
$url = "http://www.google.com";
$url = "https://google.com";
$url = "https://www.codgoogleekarate.com";
$url = "subdomain.google.com";
$url = "https://subdomain.google.com";
But still have this edge case
$url = "blahblahblahblah";
The function convertUrl($url) will convert this to $url = "http://blahblahblahblah";
then the regex will consider it as valid URL while it isn't!!
How can I edit it so that it won't pass a URL with this structure http://blahblahblahblah
If you want to validate internet url's, add a check for including a dot (.) character in your reg-ex.
Note: http://blahblahblah is a valid url as is http://localhost
Try this:
if (preg_match("/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?#)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/", $url)) {
echo "URL is valid";
}else {
echo "URL is invalid<br>";
}
I have a input that you enter a URL, i basically want to write some php that says if the domain containts "http://" then leave it be, else if not then add it to the beginning.
This is what I have so far...
$domain = $_POST["domain"];
if (strpos($domain, "http://")) {
return $domain;
} else {
$domain = "http://" . $domain;
}
This doesnt seem to work..
it doesnt add the http:// on if it doesnt contain http://.
you forgot to return $domain.
$domain = $_POST["domain"];
if (strpos($domain, "http://") !== false) {
return $domain;
} else {
return "http://" . $domain;
}
Since the string starts with http://, strpos will return 0, which will evaluate to false.
Change the if statement to:
if(strpos($domain, "http://") !== FALSE){
"http://" then leave it be, else if not then add it to the beginning.
How about adding adding it regardless? I find that to be easier:
<?php
$url = 'http://www.google.com';
echo 'http://' . preg_replace( '~^http://~', '', $url );
read manual:
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please read
the section on Booleans for more
information. Use the === operator for
testing the return value of this
function.
That is because strpos will return the location of the string, within the string.
In your url, that is 0. Which equals to false. Make it a strict check - add === false.
if (strpos($domain, "http://") !== false) {
//return substr($domain,7); Thanks Rocket.
return $domain;
} else {
return "http://" . $domain;
}
I know this is a bit late to the party, but I prefer this approach:
if (!preg_match('#^http[s]{0,1}://#', $input)) {
$input = 'http://' . $input;
}
This will preserve a https:// address, and not have you ending up with http://https://www.mysite.com. You could also further edit it to strip out https:// if you had a rule for not using https addresses.
I know the original question didn't ask for this, but I think it's important to consider in most situations, and will hopefully help someone else who comes looking.
Use caution when using strpos(). It will return 0 when 'http://' is found at the beginning of the string, causing your if statement to fail unexpectedly. You will want to check the type of the return to be sure:
$domain = $_POST["domain"];
if (FALSE !== strpos($domain, "http://")) {
return $domain;
} else {
return "http://" . $domain;
}