in reply to File upload and directory permissions

The proper way to do it would be to have it saving the files to a directory where the user apache (or whatever web server) runs as has write permission. chmoding the directory to 777 is overkill... Ideally, you could use suexec with apache, but that may not be an option depending on who runs the server. Worst case, I'd suggest you create a new directory solely to receive uploads from your script and set its permissions to 733 (anyone can write to the directory, but only you can read it) which will at least prevent people from seeing what's there. .htaccess can probably also be used to help keep prying eyes at bay.

Looking over the code, I see one glaring problem: You're too lax when untainting $file. You also need to check that it doesn't start with a / or contain .. unless you want to let people upload files to /bin/bash or ../../../bin/ls. (If the Apache module is available, you can use server_root_relative($file) to clean up incoming paths.) Also note that the regex you're using to untaint $file will happily accept 'path/to/somewhere/deeper/than/you/want', although I suspect you don't want it to. If you want $2 to end up with only the final component of a path, use /\/([^\/\\]+)^/ instead.

I suppose the big question, though, is "What are you trying to accomplish?" TIMTOWTDI, but the way you've chosen seems a bit awkward. There's probably an easier way to do what you intend.