简体   繁体   中英

Add http or https for user input validation

$xml = $_GET['url']

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

..
..

if the user put without http or https my script will be broken, is concatenation a good way to validation in this case?

The simplest way of doing this is checking for the presence of http:// or https:// at the beginning of the string.

if (preg_match('/^http(s)?:\/\//', $xml, $matches) === 1) {
    if ($matches[1] === 's') {
        // it's https
    } else {
        // it's http
    }
} else {
    // there is neither http nor https at the beginning
}

You are using a get method. Or this is done by AJAX, or the user appends a url in the querystring You are not posting a form?

Concatenation isn't going to cut it, when the url is faulty. You need to check for this.

You can put an input with placeholder on the page, to "force" the user to use http:// . This should be the way to go in HTML5.

 <input type="text" pattern="^(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$" placeholder="http://" title="URLs need to be proceeded by http:// or https://" >

This should check and forgive some errors. If an url isn't up to spec this will return an error, as it should. The user should revise his url.

$xml = $_GET['url']

$xmlDoc = new DOMDocument();
if (!preg_match(/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/, $xml ) )
{
    echo 'This url is not valid.';
    exit;
}
else if (!preg_match(/^http(s)?:\/\/, $xml))
{
    //no http present
    $orgUrl = $xml;
    $xml = "http://".$orgUrl; 
    //extended to cope with https://
    $loaded = loadXML();
    if (substr($loaded, 0, 5) == "false")
    {
        //this attempt failed.
        $xml = "https://".$orgUrl;
        $loaded = loadXML();
        if (substr($loaded, 0, 5) == "false")
        {
             echo substr($loaded, 6);
             exit;
        }

    }
}
else
{  
    $loaded = loadXML();
}

function loadXML()
{
  try {
     return $xmlDoc->load($xml);
  }
  catch($Ex)
  {
     return echo 'false Your url could\'t be retrieved. Are you sure you\'ve entered it correctly?';
  }
}

You can also use curl to check the url before loading xml:

$ch = curl_init($xml);

// Send request
curl_exec($ch);

// Check for errors and display the error message
if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "$error_message :: while loading url";
}

// Close the handle
curl_close($ch);

Important side-note : Using this methods to check if the url is available and than take the appropriate action can take a very long time, since the server response can take a while to return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM