简体   繁体   English

如何使用html或php使用“ http://”预填充type =“ url”表单字段?

[英]How to pre-fill a type=“url” form field with “http://” using html or php?

Problem : on a form asking for the user's website, a type="url" form field returns an error unless "http://" precedes the domain name (there's even an error with "www."). 问题 :在要求用户访问网站的表单上,除非域名前面有“ http://”,否则type =“ url”表单字段将返回错误(甚至“ www。”也有错误)。

Outcome I am seeking : a PHP/HTML* method of partly pre-filling the type="url" field with "http://" so it's more user-friendly for users to type "companywebsite.com" into the field and submit without the error. 我正在寻找的结果 :一种PHP / HTML *方法,部分用“ http://”预填充type =“ url”字段,因此用户在该字段中键入“ companywebsite.com”并提交更方便没有错误。

In other words, a user just fills in companywebsite.com and I want to pre-fill that with http:// so the end result is http://companywebsite.com 换句话说,用户只填写了companywebsite.com,而我想用http://预先填写,因此最终结果是http://companywebsite.com

<h5>Website</h5>
<input type="url" name="company_website" id="company_website" value="" />


Image below is a screenshot of a form entry that has returned an error (because "http://" does not precede the stackoverflow.com domain). 下图是返回错误的表单条目的屏幕截图(因为“ http://”不在stackoverflow.com域之前)。

形式错误的图像,因为“ http://”不在链接前面

* I did find a .js method ( https://gist.github.com/cvan/117bc1f88e4dfca6dba7 ) but I'm a novice and just learning php *我确实找到了.js方法( https://gist.github.com/cvan/117bc1f88e4dfca6dba7 ),但是我是新手,只是学习php

There are a couple of ways you could go about this: 有两种方法可以解决此问题:

<input type="url" name="company_website" id="company_website" value="http://" />

However, I would advise against this because you can never trust the user to input correctly. 但是,我建议您不要这样做,因为您永远不会信任用户正确输入。 Instead, assuming you are submitting your form via the POST method, in your php code, 相反,假设您要通过POST方法在php代码中提交表单,

<?php

    if(isset($_POST['company_website'])){
        $pos = strpos($_POST['company_website'], "http://");
        if($pos != 0){
            $website = "http://".$_POST['company_website'];
        }
        // do the rest
    }
?>

Well then. 好吧。 For the purpose of learning something about security, I'll write this answer with some example code, so you know how to do this kind of stuff safely in the future. 为了学习有关安全性的知识,我将用一些示例代码来编写此答案,以便您知道将来如何安全地进行此类操作。

First, lets write a small form: 首先,让我们写一个小表格:

<form method="POST" action="your_php_file.php" accept-charset="utf-8">
    <input type="url" name="company_website" id="company_website" value="" />
    <input type="submit" value="Update website" />
</form>

Now lets start writing our PHP file based on this. 现在开始基于此编写我们的PHP文件。 First we need to be sure the user is submitting new data and not an empty string: 首先,我们需要确保用户提交的是新数据,而不是空字符串:

if(isset($_POST['company_website']) && !empty($_POST['company_website'])){

Next we'll write a function that checks if the string is a website or not: 接下来,我们将编写一个函数来检查字符串是否是网站:

function isWebsite($url){

To see if a string matches a website, we'll be using regular expressions. 要查看字符串是否与网站匹配,我们将使用正则表达式。 Regex can be quite complicated, so at the end of this answer, I'll post a link to learn more about them. 正则表达式可能非常复杂,因此在此答案的结尾,我将发布一个链接以了解有关它们的更多信息。

    $pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';

Now lets write a simple if statement that returns us true or false. 现在让我们编写一个简单的if语句,该语句返回true或false。 To keep it simple, this statement compares the variable $url (which contains the user data) with the above regular expression pattern in $pattern . 为简单起见,此语句将变量$url (包含用户数据)与$pattern的上述正则表达式模式进行比较。 It will return true if $url contains a valid website, or false if it doesn't. 如果$url包含有效的网站,它将返回true;否则,将返回false。

    if(preg_match($pattern, $url)){
        return true;
    } else {
        return false;
    }
}

Next we'll write a function that adds 'http://' in front of the data send by the user: 接下来,我们将编写一个函数,在用户发送的数据之前添加“ http://”:

function addHttp($url){
    $url = "http://". $url;
    return $url;
}

Now that our functions are complete, all we have to do is use them. 现在我们的功能已经完成,我们所要做的就是使用它们。 First we'll check if the user already sent a valid website: 首先,我们将检查用户是否已经发送了有效的网站:

if(isWebsite($_POST['company_website'])){
    //The website is valid, so you can safely add it your database here
    } else {
        //The website is not valid, but the user might simply have forgotten
        //to add http:// in front of it. So lets do it for him:
        $website = addHttp($_POST['company_website']);

        //Still we can't be sure if it's a valid website. It might be a string
        //that will try to mess with your database. So lets verify it again:
        if(isWebsite($website)){
            //The website is now valid, so you can safely add it your database here
        } else {
            //The website is still not valid, so we need to return an error
            //to your user:
            echo "It seems you didn't enter a valid website. Please try again!";
            exit;
        }
    }
}

As you might have noticed, we have 2 places in our code where we need to write the same code to insert everything in the database. 您可能已经注意到,我们的代码中有2个地方需要编写相同的代码才能将所有内容插入数据库。 You could use a function for that as well: 您也可以使用一个函数:

function addToDatabase($url){
    //Write your code to add everything to database here. $url will contain the website
}

So the complete code would become as follows: 因此完整的代码将如下所示:

<?php

if(isset($_POST['company_website']) && !empty($_POST['company_website'])){

    function isWebsite($url){
        $pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';

        if(preg_match($pattern, $url)){
            return true;
        } else {
            return false;
        }
    }

    function addHttp($url){
        $url = "http://". $url;
        return $url;
    }

    function addToDatabase($url){
        //Write your code to add everything to database here. $url will contain the website
    }

    if(isWebsite($_POST['company_website'])){
        addToDatabase($_POST['company_website']);
    } else {
        //The website is not valid, try adding 'http://'
        $website = addHttp($_POST['company_website']);

        if(isWebsite($website)){
            addToDatabase($website);
        } else {
            //The website is still not valid, return error
            echo "It seems you didn't enter a valid website. Please try again!";
            exit;
        }
    }
}

?>

I should add that it still might not be safe to just blindly add the website to your database. 我应该补充一点,只是盲目地将网站添加到您的数据库中可能仍然不安全。 To make it absolutely secure, you'll need to use PDO() or MySQLi() in combination with Prepared Statements. 为了使其绝对安全,您需要结合使用PDO()MySQLi()和Prepared Statements。 But explaining that in this answer would turn this into a book. 但是,如果在此答案中加以说明,则会将其变成一本书。 So make sure to learn about it! 因此,请务必了解它!

Lastly I promissed to give a resource to learn more about Regular Expressions. 最后,我不允许提供资源来学习更多有关正则表达式的信息。 The best and safest resource would be from the official PHP website itself. 最好和最安全的资源将来自PHP官方网站本身。 You can find it here: PHP: Pattern Syntax 您可以在这里找到它: PHP:模式语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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