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 !

2

3 Answers 3

1

Use $_SERVER['HTTPS']

 $isHttps = (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? true : false;
Sign up to request clarification or add additional context in comments.

Comments

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";

?>

Comments

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://
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.