HereToHelpPHP
HereToHelpPHP

Reputation: 189

PHP file upload name change with preg_replace

Im trying to make my file uploades more safe-proof, so that no link will be broken. Ive tried to write a code thats first remove all bad url characters and if the same name exists it should increase a number after the filename.

My code works fine with the increased number on duplicate name, but the string like: hi this is a test - does not change to hithisisatest

The code im trying to run is as followed:

if ($myFile["error"] !== UPLOAD_ERR_OK) {
        CUSTOM HEADER
        exit;
    }

    // ensure a safe filename
    $name = preg_replace("/[^a-z0-9_\.\-[:space:]]/i", "_", $myFile["name"]);

    // don't overwrite an existing file
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // preserve file from temporary directory
    $success = move_uploaded_file($myFile["tmp_name"],
        UPLOAD_DIR . $name);

    if (!$success) { 
        CUSTOM HEADER
        exit;
    }

Upvotes: 1

Views: 1162

Answers (1)

mhall
mhall

Reputation: 3701

The regular expression you are using in preg_replace is designed to keep some selected characters (abc etc.) in $name and replace all other ("bad") characters with an underscore:

$name = preg_replace("/[^a-z0-9_\.\-[:space:]]/i", "_", $myFile["name"]);

As [:space:] is listed among those characters, there should be little surprise that spaces are kept intact for names like hi this is a test.

Remove the [:space:] and you will get hi_this_is_a_test for the filename hi this is a test.

$name = preg_replace("/[^a-z0-9_\.\-]/i", "_", $myFile["name"]);
// hi_this_is_a_test

If you really wanted to plainly remove the "bad" chars, as hinted in your question, you should also set the replacement string to "" instead of "_" in the reg_replace call.

$name = preg_replace("/[^a-z0-9_\.\-]/i", "", $myFile["name"]);
// hithisisatest

Upvotes: 1

Related Questions