簡體   English   中英

防止鏈接在 PHP 中被雙重編碼

[英]Prevent an link becoming double encoded in PHP

I have the following URL in a MySQL database for a PHP application - part of our system allows a user to edit their previous post with these links and save - however as the url gets encoded again when a user edits this is then breaks the url as下面顯示。

是否有一種簡單的方法或現有的 PHP function 來確定字符串是否已經被編碼並更改字符串以刪除不需要的字符,使其保留在下面的預期 Z78E6221F6393D1356681DB398F14CED 中。

Expected output url: https://r5uy4lmtdqka6a1rzyexlusfl-902rjcrzfe6k93co7a644-tom.s3.eu-west-2.amazonaws.com/Carbon%20Monoxide/Summer%20CO%20Campaign/CO%20Summer%202022/CO%20Summer%20you%20can% 20smell%20the%20BBQ%20-%20600x600.jpg

Actual output url: https://r5uy4lmtdqka6a1rzyexlusfl-902rjcrzfe6k93co7a644-tom.s3.eu-west-2.amazonaws.com/Carbon%2520Monoxide/Summer%2520CO%2520Campaign/CO%2520Summer%25202022/CO%2520Summer%2520you%2520can% 2520smell%2520the%2520BBQ%2520-%2520600x600.jpg

正如評論中所建議的,雙重解碼,然后編碼(僅查詢字符串部分)。

<?php
$str = "https://r5uy4lmtdqka6a1rzyexlusfl-902rjcrzfe6k93co7a644-tom.s3.eu-west-2.amazonaws.com/Carbon%2520Monoxide/Summer%2520CO%2520Campaign/CO%2520Summer%25202022/CO%2520Summer%2520you%2520can%2520smell%2520the%2520BBQ%2520-%2520600x600.jpg";
$str = "https://r5uy4lmtdqka6a1rzyexlusfl-902rjcrzfe6k93co7a644-tom.s3.eu-west-2.amazonaws.com/Carbon%20Monoxide/Summer%20CO%20Campaign/CO%20Summer%202022/CO%20Summer%20you%20can%20smell%20the%20BBQ%20-%20600x600.jpg";

function fix_url($str)
{
    $arr = explode('/', $str, 4);
    $qs = $arr[3]; // add if at all check?

    while (true) {
        $decoded = urldecode($qs);
        if ($decoded == $qs) {
            break;
        }
        $qs = $decoded;
    }
    $encoded = urlencode($decoded);
    $result = $arr[0] . '//' . $arr[2] . $encoded;
    return $result;
}

echo fix_url($str);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM