1

I am making a json validation that needs to validate url that starts with http:// or https://

  if(preg_match("/^[http://][a-zA-Z -]+$/", $_POST["url"]) === 0)
  if(preg_match("/^[https://][a-zA-Z -]+$/", $_POST["url"]) === 0)

Am I wrong in synatx, and also how should i combine both (http and https) in same statement ?

Thank you !

3 Answers3

1

Use $_SERVER['HTTPS']

 $isHttps = (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? true : false;
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

you can use parse_url

<?php
$url = parse_url($_POST["url"]);

if($url['scheme'] == 'https'){
   // is https;
}else if($url['scheme'] == 'http'){
   // is http;
}
// try to do this, so you can know what is the $url contains 
echo '<pre>';print_r($url);echo '</pre>';
?>

OR

<?php
if (substr($_POST["url"], 0, 7) == "http://")
    $res = "http";

if (substr($_POST["url"], 0, 8) == "https://")
    $res = "https";

?>
Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
0

If you want to check your string starts with http:// or https:// without worrying about the validity of the whole URL, just do that :

<?php
if (preg_match('`^https?://.+`i', $_POST['url'])) {
    // $_POST['url'] starts with http:// or https://
}