Replace special characters before the file is uploaded using PHP

125369 picture 125369 · Mar 23, 2012 · Viewed 30.8k times · Source

I was wondering if it is possible to change the name of the file to be uploaded. I mean what I am trying to do is that, the user uploads a file which may have some special characters like special characters in some European languages.

What I am planning to do is that before using the move_uploaded_file command is it possible to change/preg_replace the special characters with normal characters, so that the file is uploaded and stored with the new name which has only normal characters.

Answer

472084 picture 472084 · Mar 23, 2012
// Get the original file name from $_FILES
$file_name= $_FILES['file']['name'];

// Remove any characters you don't want
// The below code will remove anything that is not a-z, 0-9 or a dot.
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file_name);

// Get the location of the folder to upload into
$location = 'path/to/dir/';

// Use move_uploaded_file()
move_uploaded_file($_FILES["file"]["tmp_name"], $location.$file_name);