prepare("SELECT id, user_id FROM connections WHERE alias_id = ? AND platform = 'twitch'"); $stmt->execute([$twitch_user["id"]]); $user_id = ""; $user_secret_key = ""; $user_name = ""; if ($row = $stmt->fetch()) { $id = $row["id"]; $user_id = $row["user_id"]; $stmt = $db->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$user_id]); if ($row = $stmt->fetch()) { $user_name = $row["username"]; $user_secret_key = $row["secret_key"]; $user_id = $row["id"]; } else { $db = null; echo "Connection found, but not user?"; exit; } } else { $user_secret_key = generate_random_string(32); $user_name = $twitch_user["login"]; $stmt = $db->prepare("INSERT INTO users(username, secret_key) VALUES (?, ?)"); if (!$stmt->execute([$user_name, $user_secret_key])) { $db = null; echo "Failed to create a user"; exit; } $user_id = $db->lastInsertId(); $stmt = $db->prepare("INSERT INTO connections(user_id, alias_id, platform, data) VALUES (?, ?, 'twitch', ?)"); $stmt->execute([ $user_id, $twitch_user["id"], $_SESSION["twitch_access_token"] . ":" . $_SESSION["twitch_refresh_token"] . ":" . $_SESSION["twitch_expires_on"] ]); } $_SESSION["user_id"] = $user_id; $_SESSION["user_name"] = $user_name; setcookie("secret_key", $user_secret_key, time() + 86400 * 30, "/"); $db = null; // downloading profile picture $path = "../../static/userdata/avatars"; if (!is_dir($path)) { mkdir($path, 0777, true); } $fp = fopen("$path/$user_id", "wb"); $request = curl_init(); curl_setopt($request, CURLOPT_URL, $twitch_user["profile_image_url"]); curl_setopt($request, CURLOPT_FILE, $fp); curl_setopt($request, CURLOPT_HEADER, 0); curl_exec($request); curl_close($request); fclose($fp); header("Location: /account");