public static function tempnam($dir, $prefix) {
    // Force $dir into a VFS temp path if it's not already one.
    $temp_root = static::sys_get_temp_dir();
    if (!StringUtil::startsWith($dir, $temp_root)) {
      $dir = $temp_root . '/' . str_replace('\\', '/', $dir);
    }

    // Create all intermediate directories if needed.
    @mkdir($dir, 0777, true);

    // Generate a unique non-existing file name.
    for ($retry = 0; $retry < 10 || file_exists($filename); $retry++) {
      $filename = $dir . '/' . uniqid($prefix, true);
    }
    if (file_exists($filename)) {
      trigger_error('Fail to generate a unique name for the temporary file',
                    E_USER_ERROR);
      return false;
    }

    // tempnam requires the file to be created with permission set to 0600.
    if (touch($filename) === false ||
        chmod($filename, static::DEFAULT_TMPFILE_MODE) === false) {
      trigger_error('Fail to create and change permission of temporary file ' .
                    $filename, E_USER_ERROR);
      return false;
    }

    return $filename;
  }