0

職場のクライアントのために、Web サイトを構築しました。Web サイトには、同じタイプ/ビルドのバリアントを含めることができる提供ページがあるため、二重のクリーン URL で問題が発生しました。

ちょうど今、URLに数字を追加することでそれが起こらないようにする関数を書きました。そのクリーンな URL も存在する場合はカウントアップします。

例えば

domain.nl/product/machine

domain.nl/product/machine-1

domain.nl/product/machine-2

更新しました!$clean_url を返します。再帰時と戻り時

私が書いた関数は正常に動作しますが、正しいアプローチをとったかどうか、改善できるかどうか疑問に思っていました。コードは次のとおりです。

public function prevent_double_cleanurl($cleanurl)
{

    // makes sure it doesnt check against itself
            if($this->ID!=NULL) $and = " AND product_ID <> ".$this->ID;

    $sql = "SELECT product_ID, titel_url FROM " . $this->_table . " WHERE titel_url='".$cleanurl."' " . $and. " LIMIT 1";

    $result = $this->query($sql);

            // if a matching url is found
    if(!empty($result))
    {
        $url_parts = explode("-", $result[0]['titel_url']);
        $last_part = end($url_parts);

        // maximum of 2 digits
        if((int)$last_part && strlen($last_part)<3)
        {
            // if a 1 or 2 digit number is found - add to it
                            array_pop($url_parts);
            $cleanurl = implode("-", $url_parts);

            (int)$last_part++;
        }
        else
        {
            // add a suffix starting at 1
                            $last_part='1';
        }
                    // recursive check
        $cleanurl = $this->prevent_double_cleanurl($cleanurl.'-'.$last_part);
    }

    return $cleanurl; 
}
4

2 に答える 2

1

「クリーンURL」が複数回使用される可能性によっては、あなたのアプローチが最適ではない場合があります。データベースを10回呼び出す「foo」から「foo-10」があったとします。

また、SQL クエリに押し込んだデータをサニタイズしていないようです。mysql_real_escape_string (またはその mysqli、PDO、その他の兄弟)を使用していますか?

改訂されたコード:

public function prevent_double_cleanurl($cleanurl) {
    $cleanurl_pattern = '#^(?<base>.*?)(-(?<num>\d+))?$#S';

    if (preg_match($cleanurl_pattern, $base, $matches)) {
        $base = $matches['base'];
        $num = $matches['num'] ? $matches['num'] : 0;
    } else {
        $base = $cleanurl;
        $num = 0;
    }

    // makes sure it doesnt check against itself
    if ($this->ID != null) {
        $and = " AND product_ID <> " . $this->ID;
    }

    $sql = "SELECT product_ID, titel_url FROM " . $this->_table . " WHERE titel_url LIKE '" . $base . "-%' LIMIT 1";
    $result = $this->query($sql);

    foreach ($result as $row) {
        if ($this->ID && $row['product_ID'] == $this->ID) {
            // the given cleanurl already has an ID,
            // so we better not touch it
            return $cleanurl;
        }

        if (preg_match($cleanurl_pattern, $row['titel_url'], $matches)) {
            $_base = $matches['base'];
            $_num = $matches['num'] ? $matches['num'] : 0;
        } else {
            $_base = $row['titel_url'];
            $_num = 0;
        }

        if ($base != $_base) {
            // make sure we're not accidentally comparing "foo-123" and "foo-bar-123"
            continue;
        }

        if ($_num > $num) {
            $num = $_num;
        }
    }

    // next free number
    $num++;
    return $base . '-' . $num;
}

clean-urls の可能な値についてはわかりません。前回このようなことをしたとき、私のベースはsome-article-revision-5. それ5は重複インデックスではなく、実際の箇条書きの一部です。それらを区別する (および がLIKE誤検知を除外できるようにする) ために、クリーン URL を次のようにし$base--$numました。二重ダッシュは、ベースと重複インデックスの間でのみ発生する可能性があり、物事が少し簡単になります…</p>

于 2012-06-26T13:50:47.090 に答える
0

私にはこれをテストする方法がないので、それはあなたにありますが、これが私がそれを行う方法です。私はそこに私の推論とコードの流れを説明するたくさんのコメントを入れました。

基本的に、再帰は不要であり、必要以上のデータベースクエリが発生します。

<?
public function prevent_double_cleanurl($cleanurl)
{
    $sql = sprintf("SELECT product_ID, titel_url FROM %s WHERE titel_url LIKE '%s%%'", 
        $this->_table, $cleanurl);
    if($this->ID != NULL){ $sql.= sprintf(" AND product_ID <> %d", $this->ID); }

    $results = $this->query($sql);

    $suffix = 0;
    $baseurl = true;
    foreach($results as $row)
    {
        // Consider the case when we get to the "first" row added to the db:
        //  For example: $row['titel_url'] == $cleanurl == 'domain.nl/product/machine'
        if($row['title_url'] == $cleanurl)
        {
            $baseurl = false;   // The $cleanurl is already in the db, "this" is not a base URL
            continue;           // Continue with the next iteration of the foreach loop
        }

        // This could be done using regex, but if this works its fine.
        // Make sure to test for the case when you have both of the following pages in your db:
        //
        //  some-hyphenated-page
        //  some-hyphenated-page-name
        //
        // You don't want the counters to get mixed up
        $url_parts = explode("-", $row['titel_url']);
        $last_part = array_pop($url_parts);
        $cleanrow = implode("-", $url_parts);

        // To get into this block, three things need to be true
        //  1. $last_part must be a numeric string (PHP Duck Typing bleh)
        //  2. When represented as a string, $last_part must not be longer than 2 digits
        //  3. The string passed to this function must match the string resulting from the (n-1) 
        //      leading parts of the result of exploding the table row
        if((is_numeric($last_part)) && (strlen($last_part)<=2) && ($cleanrow == $cleanurl))
        {
            $baseurl = false;                           // If there are records in the database, the 
                                                        //  passed $cleanurl isn't the first, so it 
                                                        //  will need a suffix
            $suffix = max($suffix, (int)$last_part);    // After this foreach loop is done, $suffix 
                                                        //  will contain the highest suffix in the 
                                                        //  database we'll need to add 1 to this to 
                                                        //  get the result url
        }
    }

    // If $baseurl is still true, then we never got into the 3-condition block above, so we never 
    //  a matching record in the database -> return the cleanurl that was passed here, no need
    //  to add a suffix
    if($baseurl)
    {
        return $cleanurl;
    }
    // At least one database record exists, so we need to add a suffix.  The suffix we add will be
    //  the higgest we found in the database plus 1.
    else
    {
        return sprintf("%s-%d", $cleanurl, ($suffix + 1));
    }
}

私のソリューションでは、SQLワイルドカード(%)を利用して、クエリの数をnから1に減らしています。

14〜20行目で説明した問題のあるケースが期待どおりに機能することを確認してください。マシン名(またはそれが何であれ)のハイフンは、予期しないことをする可能性があります。

sprintfまた、クエリのフォーマットにも使用しました。文字列として渡される文字列をサニタイズするようにしてください(例$cleanurl)。

@rodneyrehmが指摘しているように、PHPは数値文字列と見なすものに非常に柔軟性があります。に切り替えてis_numeric()ctype_digit()それがどのように機能するかを確認することを検討してください。

于 2012-06-26T13:53:42.080 に答える