Home > Back-end >  Prevent an link becoming double encoded in PHP
Prevent an link becoming double encoded in PHP

Time:08-04

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 displayed below.

Is there an easy way or existing PHP function to determine if the string already has been encoded and to alter the string to remove the unwanted characters so it remains in the expected output below.

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

Actual 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

CodePudding user response:

As suggested in comments, double decode, then encode (only the query string part).

<?php
$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";
$str = "https://r5uy4lmtdqka6a1rzyexlusfl-902rjcrzfe6k93co7a644-tom.s3.eu-west-2.amazonaws.com/Carbon Monoxide/Summer CO Campaign/CO Summer 2022/CO Summer you can smell the BBQ - 600x600.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);
  • Related