为用户输入验证添加 http 或 https

Add http or https for user input validation

$xml = $_GET['url']

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

..
..

如果用户在没有 http 或 https 的情况下输入,我的脚本将被破坏,在这种情况下串联是否是验证的好方法?

最简单的方法是检查字符串开头是否存在 http://https://

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
}

您正在使用 get 方法。或者这是由 AJAX 完成的,或者用户在 querystring 中附加了一个 url 您没有发布表单?

当 url 出现故障时,串联不会解决问题。你需要检查一下。

您可以在页面上放置一个带占位符的输入,以供 "force" 用户使用 http://。这应该是 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://" >

这应该检查并原谅一些错误。如果 url 不符合规范,这将 return 一个错误,这是应该的。用户应该修改他的 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?';
  }
}

您也可以在加载前使用curl检查url 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);

重要旁注:使用此方法检查 url 是否可用并采取适当的操作可能需要很长时间,因为服务器return.

的回复可能需要一段时间