Home » Php » php – Get Youtube Live Chat URL and then redirect to that URL

php – Get Youtube Live Chat URL and then redirect to that URL

Posted by: admin February 25, 2020 Leave a comment


I have been trying to find a solution to easily manage youtube live chat. I have managed to retrieve the link for my youtube livestream chat using this code.
Is it possible to redirect the page to the generated link?

  <title>YT Live Chat Test</title>

try {
    $videoId = getLiveVideoID('UCSJ4gkVC6NrvII8umztf0Ow');

    // Output the Chat URL
    echo "The Chat URL is https://www.youtube.com/live_chat?v=".$videoId;
} catch(Exception $e) {
    // Echo the generated error
    echo "ERROR: ".$e->getMessage();

// The method which finds the video ID
function getLiveVideoID($channelId)
    $videoId = null;

    // Fetch the livestream page
    if($data = file_get_contents('https://www.youtube.com/embed/live_stream?channel='.$channelId))
        // Find the video ID in there
        if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
            $videoId = $matches[1];
            throw new Exception('Couldn\'t find video ID');
        throw new Exception('Couldn\'t fetch data');

    return $videoId;
} ?> 
How to&Answers:

Do you mean to just redirect the current page to another by using PHP? If that’s the case, you can set a header and change the location like:

header('Location: https://www.google.com/');

But you have to set headers before producing any output on your page such as your <html> and <head> tags. You should set the header before any html code on top of your page or alternatively you can use JavaScript to redirect the page.

Examples from w3schools.com:

// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";

// Simulate an HTTP redirect:

Hope this helps.