php: filter double dot und double slash from String

2018-04-15 2019-12-30 00:25:08 PHP,EN,string

Code

/**
 * @param string $sAbsoluteFilePath
 * @return string
 */
function secureFilePath($sAbsoluteFilePath = '')
{
    $sAbsoluteFilePath = removeDoubleDotSlashesFromString($sAbsoluteFilePath);
    $sAbsoluteFilePath = replaceMultipleForwardSlashesByOneFromString($sAbsoluteFilePath);

    /**@var string */
    return $sAbsoluteFilePath;
}

/**
 * @param string $sString
 * @return string
 */
function removeDoubleDotSlashesFromString($sString = '')
{
    // removes any "../"
    $sString = (string) preg_replace('#(\.\.\/)+#', '', trim($sString));

    /**@var string */
    return $sString;
}

/**
 * replaces multiple // in a string by a single /
 * @param string $sString
 * @return string
 */
function replaceMultipleForwardSlashesByOneFromString($sString = '')
{
    // removes multiple "/" [e.g.: //, ///, ////, etc.]
    $sString = (string) preg_replace('#/+#', '/', trim($sString));

    /**@var string */
    return $sString;
}

Usage

$sSecure = secureFilePath('//media/457.9/home/foo/htdocs/bar.2019-10-04///../../..//foo.txt')

converts

//media/457.9/home/foo/htdocs/bar.2019-10-04///../../..//foo.txt

into:

/media/457.9/home/foo/htdocs/bar.2019-10-04/foo.txt

This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".