You need to change this to take the file descriptor mkstemp() returned, not the path it munged (which is still vulnerable to the same race condition as tempnam).  You should not use tmp again, aside from the unlink below.