-1

I am using move_uploaded_file to upload a file, but when I upload a file with spaces it does not replace is with %20 and then I am stuck with the file name with spaces, how do I fix this?

Here is my code:

$target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));


        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["logoHeader"]["tmp_name"]);
            if($check === false) {

                $error = 'File is not an image.';

                include('views/logos/index.php');

                break;

            }
        }

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {

            $error = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';

            include('views/logos/index.php');

            break;

        }

        if (move_uploaded_file($_FILES["logoHeader"]["tmp_name"], $target_file)) {

            $error = 'Image has been uploaded.';

        }
        else
        {
            $error = 'Sorry, there was an error uploading your file.';

            include('views/logos/index.php');

            break;
        }
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

0
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logoHeader"]["name"]);
//new line
$target_file = checkName($target_file);
//end new line
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//your code

and add checkName function

function checkName($name){
    if(preg_match("`^[-0-9A-Z_\.]+$`i",$name)){
        return $name;
    }else{
        $name = str_replace(' ', '%20', $name);
        return $name;
    }

But you are still not spared from other "incomprehensible" characters. How will you give the file if its name contains characters that are not allowed for URL? For example: ÆÞΔΦÜЩЫž.jpg

Try to find more information about URL slug ;)

Tig
  • 38
  • 4