Search code examples
phpstringbooleanhrefstrpos

put a http:// on a string if it does not contain it else disregard string in php


i'm trying to put a http:// on a string if it does not contain it and then disregard the string if it already does the problem is it does not disregard the string if it does contain it, here is my code:

if(strpos($_POST['test-website'], "http://") === false || strpos($_POST['test-website'], "https://") === false){
    $url = "http://".$_POST['test-website'];
}else
    $url = $_POST['test-website'];

//Value: test.com
//Result: http://test.com

//Value: http://test.com
//Result: http://http://test.com

//Value: https://test.com
//Result: http://https://test.com

Solution

  • You should use === false instead of !== true, strpos will never return true.

    if(strpos($_POST['test-website'], "http://") === false || strpos($_POST['test-website'], "https://") === false) {