Search code examples
phpregexfile-uploaduploadify

Upload files to server with PHP friendly names and parse them


I'm trying to upload files to server using Uploadify script and then show them using PHP on the website, in the form of "www.example.com/directory-of-upload/file.mp3".

It works fine, until i upload files that contain characters such as commas,quotes etc. Then the php code breaks.

For instance, when i try to parse the file URL as a parameter in a flash player, it looks like this:

<param name="flashvars" value="soundFile=http://localhost/public_html/content/plugins/post_audio/uploadi‌​fy-local/uploads/song,+one.dad'a;[email protected]&amp;titles=song,+one.dad'a;-A.b!@&amp;playerID=audioplayer_song,+one.dad'a;-A.b!@">

and the file doesn't play. I guess it has something to do with these characters (commas,quotes..)

How should i fix this issue? Is reg ex the only solution?

Thanks in advance.


Solution

  • $fArr=explode('.',$_FILES['fname']['name']);
    $fname=clean(implode('',array_slice($fArr,0,-1,false)));
    $ex=clean(implode('',array_slice($fArr,-1,1)));
    $file_name=$fname.".".$ex;
    
    function clean($str) {
        $strArr=array();
        $strArr=explode(' ',$str);
        foreach ($strArr as $key=>$val) {
            if (strlen($strArr[$key])==0) {
            unset($strArr[$key]);
            }
        }
        $strArr=array_map('strtolower',$strArr);
        $str=implode(' ',$strArr);
        $str=preg_replace("/\W+/i","",$str);
    
        return $str;
    }