What it does: reads channels from a database table and prints a valid M3U playlist. Works as a web page and from the command line. Optional filter by group.
Requirements: PHP 8.0 or newer with PDO and the driver for your database (MySQL, MariaDB or SQLite).
Licence: free to use and change.
The table
CREATE TABLE channels (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(120) NOT NULL,
tvg_id VARCHAR(80) NOT NULL DEFAULT '',
logo VARCHAR(255) NOT NULL DEFAULT '',
group_title VARCHAR(80) NOT NULL DEFAULT '',
url VARCHAR(500) NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
enabled TINYINT NOT NULL DEFAULT 1
);
The script
<?php
declare(strict_types=1);
// playlist.php - build an M3U playlist from the channels table
$dsn = getenv('PLAYLIST_DSN') ?: 'mysql:host=127.0.0.1;dbname=tv;charset=utf8mb4';
$user = getenv('PLAYLIST_USER') ?: 'tv_reader';
$pass = getenv('PLAYLIST_PASS') ?: '';
$cli = PHP_SAPI === 'cli';
$group = $cli ? ($argv[1] ?? '') : trim((string) ($_GET['group'] ?? ''));
/** Make a value safe inside key="value". */
function attr(string $v): string
{
return str_replace(['"', "\r", "\n"], ["'", ' ', ' '], $v);
}
try {
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$sql = 'SELECT name, tvg_id, logo, group_title, url FROM channels WHERE enabled = 1';
$params = [];
if ($group !== '') {
$sql .= ' AND group_title = :g';
$params[':g'] = $group;
}
$sql .= ' ORDER BY group_title, sort_order, name';
$st = $pdo->prepare($sql);
$st->execute($params);
} catch (PDOException $e) {
error_log('playlist: ' . $e->getMessage());
if (!$cli) {
http_response_code(500);
}
exit("playlist unavailable\n");
}
if (!$cli) {
header('Content-Type: audio/x-mpegurl; charset=utf-8');
header('Content-Disposition: inline; filename="playlist.m3u"');
}
echo "#EXTM3U\n";
while ($row = $st->fetch()) {
$name = str_replace(["\r", "\n", ','], [' ', ' ', ' '], (string) $row['name']);
printf(
"#EXTINF:-1 tvg-id=\"%s\" tvg-logo=\"%s\" group-title=\"%s\",%s\n%s\n",
attr((string) $row['tvg_id']),
attr((string) $row['logo']),
attr((string) $row['group_title']),
$name,
trim((string) $row['url'])
);
}
How to use it
From the command line:
php playlist.php # everything
php playlist.php News # one group
As a web page, call playlist.php or playlist.php?group=News.
The connection settings come from environment variables, so no password sits in the file:
PLAYLIST_DSN="mysql:host=127.0.0.1;dbname=tv;charset=utf8mb4"
PLAYLIST_USER=tv_reader
PLAYLIST_PASS=...
Notes on how it works
- Prepared statement. The group name from the address is bound as a parameter and never pasted into the SQL text, so it cannot be used for SQL injection.
- Read-only database user. Create a user that can only
SELECTfrom this one table. If the page is ever abused, nothing can be changed or deleted. attr()replaces double quotes and line breaks. A stray quote in a channel name would otherwise break every attribute after it.- Errors go to the log, not to the visitor. The database message can contain host names and user names.
- Rows are streamed one by one with
fetch(), so a playlist with tens of thousands of entries does not need to fit in memory.
Before you put it on the internet
As written, anyone who knows the address can download the playlist. Add your own access check at the top, for example a per-user token that you look up in the database with another prepared statement, and answer 403 when it does not match.
Suggestions and improvements are welcome in the replies.