如何通过preg-match纠正HTTPS输出URL错误?

问题描述 投票:1回答:1

这可能是一个非常基本的问题,我不太确定该怎么问。我有一个热门网站,人们可以从我的网站访问他们的网站,以获得“淘汰”号码。如果用户添加带有“ http://”的网站,则所有方法都可以正常工作,但是,如果用户添加带有“ https://”的网站,则该链接将不起作用。

该链接将简单地以'https //'打开。但冒号不会出现在HTTP的基本URL中。因此,该链接无法正确打开。

有人知道我如何使用如下所示的preg_matches来解决此问题?

if(isset($_GET['action']) && $_GET['action'] == "out" && !empty($_GET['key']))
{
    //echo "<pre>";
    $site = ORM::for_table('topsite')->where_equal('hash_key',$_GET['key'])->find_one();

    //print_r($site);
    //echo $site->url;die();
    $count = ($site->hits_out) + 1;
    //echo $count;

    $query = ORM::get_db()->prepare("update `topsite` set hits_out='".$count."' where id='".$site->id."'");
    if(!preg_match('/http:/',$site->url))
    {
        $site->url = "http://".$site->url;
    }
    if( $query->execute() ) 
    {
        header("Location:$site->url");
    } 
    else
    {
        header("Location: $base_url");
    }
    exit;
php url https preg-match out
1个回答
0
投票

s添加到协议中,并使其与?可选。然后在header中使用找到的匹配项,以便知道要使用的协议。

if(!preg_match('/https?:/', $site->url, $protocol))
    {
        $site->url = $protocol[0] . '//' . $site->url;
    }

((您可能可以更改定界符,并在协议中也包含//,这种方式的连接少一些)

无关,但请注意,您准备的陈述不安全。

$query = ORM::get_db()->prepare("update `topsite` set hits_out='".$count."' where id='".$site->id."'");

应写为:

$query = ORM::get_db()->prepare("update `topsite` set hits_out=? where id= ?");

然后应使用绑定。取决于驱动程序,语法会有所不同,对于PDO而言,它将起作用:

$query->execute(array($count, $site->id))

另一个不相关的点,hits_out的增量应该在SQL中,而不是PHP。多个用户可能会同时访问该页面,并且您将无法使用当前的方法计数。我建议:

set hits_out = hits_out + 1

代替select然后:

$count = ($site->hits_out) + 1;
© www.soinside.com 2019 - 2024. All rights reserved.