preg_match: ensure the start and the end contains something - php

I want to have the regular expression that makes sure the beginning of the string contains 'http://' and '/' and the end.
This is a longer version I came up with,
if(!preg_match("/(^http:\/\//", $site_http))
{
$error = true;
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start."/>';
}
elseif (!preg_match("/\/$/", $site_http))
{
$error = true;
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link has ended with a /."/>';
}
but I thought these two expressions can put together like below, but it wont work,
if(!preg_match("/(^http:\/\/)&(\/$)/", $site_http))
{
$error = true;
echo '<error elementid="site_http" message="site_http - Your link appears to be invalid. Please confirm that your link contains http:// at the start and a / at the end."/>';
}
the multiple expressions that I try to combine must be wrong! any idea?
thanks,
Lau

if(preg_match('/^http:\/\/.*\/$/', $site_http))
{
...
}
The ^http:\/\/ forces http:// at the front, the \/$ forces a slash at the end, and .* allows everything (and possibly nothing) between.
For example:
<?php
foreach (array("http://site.com.invalid/", "http://") as $site_http) {
echo "$site_http - ";
if (preg_match('/^http:\/\/.*\/$/', $site_http)) {
echo "match\n";
}
else {
echo "no match\n";
}
}
?>
generates the following output:
http://site.com.invalid/ - match
http:// - no match

Related

PHP Check for HTTP and HTTPS in the submitted URL through FORM

I have this code which checks for http:// in the URL submitted. But I want it to also check for https://. So I tried with an or in the if condition but it still checks only for http:// and not https://.
Here is my code.
if(!preg_match("#^http://#i",$turl) or !preg_match("#^https://#i",$turl)){
$msg = "<div class='alert alert-danger'>Invalid Target URL! Please input a standard URL with <span class='text-info'>http://</span> for example <span class='text-info'>http://www.kreatusweb.com</span> </div>";
}
If I now put https:// in the URL and submit, it still returns this error message as now http:// is false here. What logic or code should I use here to check for both. I just don't want users to submit www.somewebsite.com. I want them to submit full URL using either http:// or https://. If either of these two exists in the URL then only the form will be processed further.
You can simplify the regex so the s is optional by just adding a ? after it.
if(!preg_match("#^https?://#i",$turl)){
replace the or with &&
if(!preg_match("#^http://#i",$turl) && !preg_match("#^https://#i",$turl))
I used to do this logic mistake when I started to code because you think like this if (not something or not somethingelse)
but doing if (!http || !https) will return true in both http and https because
1- if it is http, then the !https part will return true
2- if it is https, then the !http part will return true too
Check out the PHP validate filters at http://php.net/manual/en/filter.filters.validate.php.
<?php
$arr = [ 'http:example.com','https:/example.com','https://www.example.com','http://example.com',
'ftp://example.com','www.example.com','www.example.com/test.php','https://www.example.com/test.php?q=6'];
foreach ($arr as $str) {
$filtered = filter_var($str,FILTER_VALIDATE_URL,FILTER_FLAG_SCHEME_REQUIRED|FILTER_FLAG_HOST_REQUIRED);
if (!empty($filtered)) {
if (stripos($filtered,'http') === 0) {
echo $str.' is valid'.PHP_EOL;
} else {
echo $str.' is a valid URL, but not HTTP'.PHP_EOL;
}
} else {
echo $str.' is not a valid URL'.PHP_EOL;
}
}

I need a regex that would tell me if URL starts with http://i.imgur.com

So I need a regex that I can use in preg_replace that'll tell me if $string starts with http:// (or https) i.imgur.com/
Any help? I'm not that good with regex heh
so far what I have:
<?php
$url = "httPs";
if (preg_match('#^http#i', $url) === 1) {
// Starts with http (case insensitive).
die('ye');
}
else
{die('nop');}
?>
Try /\/\/i\.imgur\.com/
Does that make sense? The double slash after http(s) allows the pattern to only check at the beginning of the domain of the url
So
if (preg_match('\/\/i\.imgur\.com', $url)) { ...
<?php
$url = 'https://i.imgur.com/image';
if (preg_match('/^https?\:\/\/i\.imgur\.com\//', $url)) {
die('yes');
} else {
die('no');
}

Regular expression for validation of a facebook page url

I need to validate the facebook page url which should not consider http/https or www given or not?
I mean the following should be accepted or valid:
www.facebook.com/ABCDE
facebook.com/ABCDE
http://www.facebook.com/ABCDE
https://www.facebook.com/ABCDE
And following should not be accepted or invalid:
http://www.facebook.com/ => User name/page name not given
http://www.facebook.com/ABC => User name/page name should have the minimum length of 5.
For the above requirement I'd made following regular expression, but it is not checking the User Name or Page Name which is the only problem. Rest is working fine:
/^(https?:\/\/)?((w{3}\.)?)facebook.com\/(([a-z\d.]{5,})?)$/
I am very new to Regular Expression, so don't have much idea about it.
Any type of help would be appreciable.
Thanks in advance.
parse_url() can help you with that.
<?php
$array = array(
"www.facebook.com/ABCDE",
"facebook.com/ABCDE",
"http://www.facebook.com/ABCDE",
"https://www.facebook.com/ABCDE",
"http://www.facebook.com/",
"http://www.facebook.com/ABC"
);
foreach ($array as $link) {
if (strpos($link, "http") === false) {
$link = "http://" . $link; //parse_url requires a valid URL. A scheme is needed. Add if not already there.
}
$url = parse_url($link);
if (!preg_match("/(www\.)?facebook\.com/", $url["host"])) {
//Not a facebook URL
echo "FALSE!";
}
elseif (strlen(trim($url["path"], "/")) < 5) {
//Trailing path (slashes not included) is less than 5
echo "FALSE!";
}
else {
//None of the above
echo "TRUE";
}
echo "<br>";
}
Try this one (have not tested it, should work)
'~^(https?://)?(www\.)?facebook\.com/\w{5,}$~i'
\w is like [a-zA-Z0-9_]
Robert

php preg_match multiple urls

I know next to nothing about php so this will make someone laugh probably.
I have this bit of code in index.php which checks a host header and redirects if a match is found.
if (!preg_match("/site1.net.nz/",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
However, I need to make it check on potentially multiple sites. as follows.
if (!preg_match("/site1.net.nz/"|"/site2.net.nz",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
This might actually be the correct syntax for all I know:-)
if (!preg_match("/(site1\.net\.nz|site2\.net\.nz|some\.other\.domain)/",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
Try,
$hosts="/(site1\.com)|(site2\.com)/";
if (!preg_match($hosts,$host)) {
// do something.
}
// [12] to match 1 or 2
// also need to escape . for match real . otherwise . will match any char
if (!preg_match("/site[12]\.net\.nz/",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
Or
if (!preg_match("/site1\.net\.nz|site2\.net\.nz/",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
if (!preg_match("/(site1\.net\.nz|site2\.net\.nz)/",$host)) {
header('Location: http://www.siteblah.net.nz/temp_internet_block.cfm');
}
This would be correct RegEx syntax.
Let's say you have an array of urls.
$array = Array('site1.net.nz', 'site2.net.nz');
foreach($array as &$url) {
// we need to escape the url properly for the regular expression
// eg. 'site1.net.nz' -> 'site1\.net\.nz'
$url = preg_quote($url);
}
if (!preg_match("/(" . implode("|", $array) . ")/",$host)) {
header('Location: http://example.com/');
}

parsing url - php, check if scheme exists, validate url regex

Is this a good way to validate a posted URL?
if (filter_var($_POST['url'], FILTER_VALIDATE_URL)){
echo "valid url";
}else{
echo "invalid url";
}
This is what I wrote to start with, as I could show multiple error messages with it:
function validateURL($url)
{
$pattern = '/^(([\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})*)?$/';
return preg_match($pattern, $url);
}
$result = validateURL($_POST['url']);
if ($result == "1"){
$scheme = parse_url($_POST['url'], PHP_URL_SCHEME);
if (isset($scheme)){
echo $scheme . "://" . parse_url($_POST['url'], PHP_URL_HOST);
}else{
echo "error you did not enter http://";
}
}else{
echo "your url is not a valid format";
}
I'd simply go for the build-in FILTER_VALIDATE_URL and use a generic error message like:
Invalid URL. Please remember to input http:// as well.
If you're nice you could check if the first 7/8 letters are http:// or https:// and prepend them if not.
Coming up with and maintaining such a RegEx is not something you should get into if the problem is already solved. There's also usually no need to be any more detailed in the error message, unless you're in the business of explaining URL formats.
Have you checked this out Kyle, http://phpcentral.com/208-url-validation-in-php.html
I think simple
filter_var($var, FILTER_VALIDATE_URL)
and checking the protocol by strpos() is enough because user can, if wants to, give you the wrong (which does not exists) url.
Of course you can check if domain exists and return valid http status but I think it is little overstatement.

Categories