• View our reviews on Hot Scripts
  • JS Tutorial

Recent Comments

Powered by Disqus

Back to articles

PHP handling file uploads

Here is a function to handle file upload, by checking it to bad and forbidden characters and renaming it if file already exists on server:

function handle($arr, $dest)
    //list of forbidden characters
    $clist = array("!", "@", "#", "$", "%", "^", 
                    "&", "*", "{", "}", "|", "'", 
                    "?", "/", "<", ">"); 
    //list of good characters to replace to
    $convert_to = array("A", "a", "C", "c", "E", 
                        "e", "G", "g", "I", "i", 
                        "K", "k", "L", "l", "N", 
                        "n", "S", "s", "U", "u", 
                        "Z", "z"); 
    //list of bad characters to be replaced
    $convert_from = array("Ā", "ā", "Č", "č", "Ē", 
                        "ē", "Ģ", "ģ", "Ī", "ī", 
                        "Ķ", "ķ", "Ļ", "ļ", "Ņ", 
                        "ņ", "Š", "š", "Ū", "ū", 
                        "Ž", "ž"); 
    //getting file extension
    $ext = explode(".", $arr["name"]);
    //replacing forbbiden characters
    $name = str_replace($clist, "", $ext[0]);
    //replacing bad characters to good
    $name = str_replace($convert_from, $convert_to, $name); 
    $cntr = 0;
    //creating destination
    $destination = $dest.$name.".".strtolower($ext[sizeof($ext)-1]); 
    //while file exists change file name by including counter
        $destination = $dest.$name."(".$cntr.").".
    //move uploaded file
    move_uploaded_file($arr["tmp_name"], $destination);
    return $destination;

Thens use it like this: $destination = handle($_FILES['name']);

You may also be interested in:

Powered by

blog comments powered by Disqus