12

i am using this code to save the uploaded file but the problem is it is allowing the file with name with special character and space. for example it is allowing

hi how are you

but i dont want to allow any space ,special charater etc. here is my code .i tried with preg_replace in uri but after that i tried to upload file but nothing got uploaded.

function save_file($file) {
    $allowed_ext = array('jpg','png','gif','jpeg');
    $ext = $file['name'];
    $ext = strtolower($ext);

    if (in_array($ext, $allowed_ext)) {
        die('Sorry, the file type is incorrect:'.$file['name']);
    }

    $fname = date("H_i",time()).'_'.get_rand(5);
    $dir = date("Ym",time());
    $folder = 'uploads/userfiles/'.$dir;
    $uri = $folder.'/'.$fname.'.'.$ext;

    if (!is_dir($folder))
        mkdir($folder, 0777);

    if (copy($file['tmp_name'],$uri))
        return $uri;
    else {
        return false;
    }
}
Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69
raju
  • 277
  • 1
  • 4
  • 12
  • possible duplicate of [How to strip all spaces out of a string in php?](http://stackoverflow.com/questions/2109325/how-to-strip-all-spaces-out-of-a-string-in-php) – Michael Berkowski Jun 10 '12 at 18:28
  • Try to clearly indent your code and avoid using if statements without brackets. Make it easy on us and you get more code quality. – Ricardo Souza Jun 10 '12 at 18:30
  • 1
    See also [this one](http://stackoverflow.com/questions/7032331/in-php-how-to-remove-all-special-characters-uppercase-letters-numbers-and-spac) and extend the expression to permit uppercase chars. `/[^a-z]/i` – Michael Berkowski Jun 10 '12 at 18:31

1 Answers1

37

To strip non letters out of a string you can use the following regular expression

$input = preg_replace("/[^a-zA-Z]+/", "", $input);
John
  • 5,942
  • 3
  • 42
  • 79
  • can you please tell where in my code . i tried but it did not worked.please tell where in my code – raju Jun 10 '12 at 18:37
  • 4
    @raju This single line is self explanatory. Make an effort. – John Jun 10 '12 at 18:39
  • i tried this but nothing got uploaded $uri = $folder.'/'.$fname.'.'.$ext; $uri = preg_replace("/[^a-zA-Z]+/", "", $uri); there are several dependency on $uri so i have not changed the name in next line as php will execute from top to bottom – raju Jun 10 '12 at 18:41
  • @raju It seems to me that you have lot more than this one question you asked above. For example, why is the input filename used as file-extension and why are the extensions from `$allowed_ext` not allowed? Have you ever run that piece of code you've posted in your question? – feeela Jun 10 '12 at 20:20
  • 1
    This will remove digits as well. Digits are not whitespace or special character. – rineez Jul 13 '17 at 10:41
  • 4
    For allowing the numbers you can update it with - $input = preg_replace("/[^a-zA-Z0-9]+/", "", $input); – Vivek Oct 07 '17 at 10:45