'The file you uploaded exceeds ' . ini_get('upload_max_filesize') . ' and cannot be uploaded. Please reduce the file size and try again.', UPLOAD_ERR_FORM_SIZE => 'The file you uploaded exceeds ' . round($_POST['MAX_FILE_SIZE'] / 1024) . ' KB and cannot be uploaded. Please reduce the file size and try again.', UPLOAD_ERR_PARTIAL => 'Your file only uploaded partially. Please try again.', UPLOAD_ERR_NO_TMP_DIR => 'There was an internal upload error. Please contact the system administrator with the error number #' . UPLOAD_ERR_NO_TMP_DIR, ); die( "Error: " . $errorMessages[$_FILES['file']['error']]); } if ( !isset( $_REQUEST['dir'] ) ) { die( "Error: you must provide a destination directory with the \"dir\" parameter." ); } $destDir = $_REQUEST['dir']; if ( !is_writable( $destDir ) ) { die( "Error: you do not have write permissions on directory $destDir. File could not be copied." ); } if ( !is_uploaded_file( $_FILES['file']['tmp_name'] ) ) { die( "Error: the uploaded file at " . $_FILES['file']['tmp_name'] . " is not a valid file. Some error must have occurred during the upload process." ); } // get the base name of the file $baseName = basename( $_FILES['file']['name'] ); // replace any potentially problematic characters with an underscore $baseName = preg_replace( '/[^a-z0-9_\-\.]/i', '_', $baseName ); // separate the file's extension from the rest of its basename, then // remove it from the basename itself, splitting the basename into two // variables. $lastDotIndex = strrpos( $baseName, '.' ); $firstIndex = $lastDotIndex + 1; $lastIndex = strlen( $baseName ) - 1; $fileExtension = substr( $baseName, $firstIndex, $lastIndex ); $baseName = substr( $baseName, 0, $lastDotIndex ); // make sure the extension is entirely lowercase $fileExtension = strtolower($fileExtension); // build our new path from the user-supplied destDir and our new file baseName $newfile = $destDir; if ( $destDir[strlen($destDir)-1] != "/" ) { $newfile .= '/'; } $newfile .= $baseName . '.' . $fileExtension; // if the name we've generated thus far already exists, generate a unique name // for the new file $version = 1; while ( file_exists( $newfile ) ) { $version++; $newfile = $destDir; if ( $destDir[strlen($destDir)-1] != "/" ) { $newfile .= '/'; } $newfile .= $baseName . '.' . $version . '.' . $fileExtension; } // move the file to the requested directory, and quit if there's any error doing this. if ( !move_uploaded_file( $_FILES['file']['tmp_name'], $newfile ) ) { die( "Error: could not move temp file " . $_FILES['file']['tmp_name'] . " to the requested directory $newfile" ); } chmod( $newfile, 0640 ); echo $newfile;