Unless you are running suexec, your $upload_dir has to be mode 777 (world writable) because the server runs at the lowest permission possible. You seem to be making your uploaded file 0777, but the directory it goes into must be 0777. It can get tricky. :-)