Полная инструкция по использованию защищенного API радиостанций
API для получения списка радиостанций из базы данных MySQL с полной защитой от атак. Для получения данных о радиостанциях вам доступен специальный API-эндпоинт. Все запросы к нему выполняются методом GET и возвращают информацию в удобном формате JSON. Базовый адрес для всех обращений: https://durcoinradio.ru/api_channels_secure.php В строке запроса вы можете передавать различные параметры для настройки выдаваемых данных. Чтобы получить конкретную станцию, используйте параметр id с её номером. Для фильтрации по стране применяйте параметр country, а для отбора по категории — category. Если нужно найти станцию по названию или описанию, воспользуйтесь параметром search. Параметр status позволяет отфильтровать только активные станции, передав значение 1, или только офлайн-станции со значением 0. Для управления пагинацией предусмотрены параметры limit и offset. Первый задаёт количество записей на одной странице (не более 100), а второй указывает смещение, то есть с какой записи начинать вывод. Сортировка результатов выполняется с помощью параметров sort и order: первый определяет поле для сортировки, например, по просмотрам или названию, а второй задаёт направление — по возрастанию или убыванию. Все параметры можно комбинировать между собой в любых сочетаниях, разделяя их символом &. Это позволяет гибко настраивать запрос под ваши задачи, получая ровно те данные, которые нужны в данный момент.
Поддержка MySQL 5.7+ с подготовленными запросами
Rate limiting, валидация, санитизация, подготовленные запросы
Пагинация, фильтрация, сортировка, поиск
/var/www/html/
├── api_channels_secure.php # Главный API эндпоинт
├── config.php # Конфигурация
├── .htaccess # Настройки сервера
├── index.html # Эта инструкция (необязательно)
└── logs/
└── api_errors.log # Лог ошибок (создается автоматически)
Отредактируйте config.php:
<?php
// config.php
return [
'database' => [
'host' => 'localhost',
'username' => 'mysql', // Ваш пользователь БД
'password' => 'mysql', // Ваш пароль
'database' => 'radio_base', // Название вашей БД
'charset' => 'utf8mb4'
],
'security' => [
'rate_limit' => 100, // Максимум запросов
'rate_limit_window' => 3600, // За 1 час
'max_limit' => 100,
'default_limit' => 20
]
];
-- Ваша таблица channel должна содержать эти поля:
CREATE TABLE channel (
channel_id INT PRIMARY KEY,
channel_name VARCHAR(255),
channel_image VARCHAR(255),
channel_banner VARCHAR(255),
status TINYINT(1),
channel_category VARCHAR(255),
country VARCHAR(100),
state VARCHAR(100),
city VARCHAR(100),
streaming_link VARCHAR(500),
streaming_link_type VARCHAR(50),
twitter_page VARCHAR(100),
facebook_page VARCHAR(100),
description TEXT,
category_id VARCHAR(50),
language VARCHAR(50),
contact_details VARCHAR(100),
slug VARCHAR(255),
user_id INT,
playedtime INT,
view INT,
created_at DATETIME
);
# Для Linux
chmod 755 /var/www/html/api_channels_secure.php
chmod 777 /var/www/html/logs/ # Для записи логов
chown www-data:www-data /var/www/html/logs/
https://durcoinradio.ru/api_channels_secure.php
| Метод | Эндпоинт | Описание | Параметры |
|---|---|---|---|
| GET | /api_channels_secure.php |
Получить все станции | — |
| GET | /api_channels_secure.php?id=35 |
Получить станцию по ID | id - ID станции |
| GET | /api_channels_secure.php?country=USA |
Фильтр по стране | country - название страны |
| GET | /api_channels_secure.php?category=Αθλητικά |
Фильтр по категории | category - категория |
| GET | /api_channels_secure.php?search=Vibe |
Поиск по названию/описанию | search - поисковый запрос |
| GET | /api_channels_secure.php?status=1 |
Только активные станции | status - 1 (активен) или 0 |
| GET | /api_channels_secure.php?limit=10&offset=20 |
Пагинация | limit - количествоoffset - смещение |
| GET | /api_channels_secure.php?sort=view&order=desc |
Сортировка | sort - полеorder - ASC/DESC |
GET /api_channels_secure.php?country=USA&category=Αθλητικά&search=Vibe&limit=5&sort=view&order=desc
// ============================================================
// 1. Получение всех станций с пагинацией
// ============================================================
async function getStations() {
try {
const response = await fetch('https://durcoinradio.ru/api_channels_secure.php?limit=10&offset=0');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
console.log('Всего станций:', data.pagination.total);
console.log('Текущая страница:', data.pagination.current_page);
console.log('Данные:', data.data);
// Отображаем станции
data.data.forEach(station => {
console.log(`${station.channel_name} - ${station.country}`);
});
} else {
console.error('Ошибка:', data.error);
}
} catch (error) {
console.error('Ошибка запроса:', error);
}
}
// ============================================================
// 2. Поиск станций
// ============================================================
async function searchStations(query) {
const response = await fetch(
`https://durcoinradio.ru/api_channels_secure.php?search=${encodeURIComponent(query)}`
);
const data = await response.json();
return data.data;
}
// ============================================================
// 3. Получение станции по ID
// ============================================================
async function getStationById(id) {
const response = await fetch(
`https://durcoinradio.ru/api_channels_secure.php?id=${id}`
);
const data = await response.json();
return data.data[0] || null;
}
// ============================================================
// 4. Фильтрация по стране и категории
// ============================================================
async function filterStations(country, category) {
const url = new URL('https://durcoinradio.ru/api_channels_secure.php');
if (country) url.searchParams.append('country', country);
if (category) url.searchParams.append('category', category);
const response = await fetch(url);
const data = await response.json();
return data.data;
}
// ============================================================
// 5. Использование в HTML
// ============================================================
// Смотрите вкладку "HTML + JS" для полного примера
// Вызов функций
getStations();
searchStations('Vibe').then(stations => console.log(stations));
getStationById(35).then(station => console.log(station));
filterStations('USA', 'Αθλητικά').then(stations => console.log(stations));
<?php
// ============================================================
// 1. Получение всех станций через cURL
// ============================================================
function getStations($limit = 20, $offset = 0) {
$url = "https://durcoinradio.ru/api_channels_secure.php?limit=$limit&offset=$offset";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
return json_decode($response, true);
}
return null;
}
// ============================================================
// 2. Поиск станций
// ============================================================
function searchStations($query) {
$url = "https://durcoinradio.ru/api_channels_secure.php?search=" . urlencode($query);
$response = file_get_contents($url);
return json_decode($response, true);
}
// ============================================================
// 3. Получение станции по ID
// ============================================================
function getStationById($id) {
$url = "https://durcoinradio.ru/api_channels_secure.php?id=" . (int)$id;
$response = file_get_contents($url);
$data = json_decode($response, true);
return $data['data'][0] ?? null;
}
// ============================================================
// 4. Фильтрация с несколькими параметрами
// ============================================================
function getFilteredStations($filters) {
$params = http_build_query($filters);
$url = "https://durcoinradio.ru/api_channels_secure.php?$params";
$response = file_get_contents($url);
return json_decode($response, true);
}
// ============================================================
// 5. Использование функций
// ============================================================
$stations = getStations(10, 0);
print_r($stations);
$searchResult = searchStations('Vibe');
print_r($searchResult);
$station = getStationById(35);
echo $station['channel_name'] ?? 'Станция не найдена';
$filtered = getFilteredStations([
'country' => 'USA',
'category' => 'Αθλητικά',
'status' => 1
]);
print_r($filtered);
?>
# ============================================================
# 1. Получить все станции
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php"
# ============================================================
# 2. Получить станцию по ID
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?id=35"
# ============================================================
# 3. Поиск по названию
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?search=Vibe"
# ============================================================
# 4. Фильтр по стране и категории
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?country=USA&category=Αθλητικά"
# ============================================================
# 5. Пагинация с сортировкой
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?limit=5&offset=10&sort=view&order=desc"
# ============================================================
# 6. Только активные станции (статус = 1)
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?status=1"
# ============================================================
# 7. Комбинированный запрос с выводом в красивом формате
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php?country=USA&search=Radio&limit=3" | jq '.'
# ============================================================
# 8. Сохранить ответ в файл
# ============================================================
curl -X GET "https://durcoinradio.ru/api_channels_secure.php" -o stations.json
import requests
import json
# ============================================================
# 1. Получение всех станций
# ============================================================
def get_stations(limit=20, offset=0):
url = "https://durcoinradio.ru/api_channels_secure.php"
params = {
'limit': limit,
'offset': offset
}
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
# ============================================================
# 2. Поиск станций
# ============================================================
def search_stations(query):
url = "https://durcoinradio.ru/api_channels_secure.php"
params = {'search': query}
response = requests.get(url, params=params)
return response.json()
# ============================================================
# 3. Фильтрация
# ============================================================
def filter_stations(country=None, category=None, status=None):
url = "https://durcoinradio.ru/api_channels_secure.php"
params = {}
if country:
params['country'] = country
if category:
params['category'] = category
if status is not None:
params['status'] = status
response = requests.get(url, params=params)
return response.json()
# ============================================================
# 4. Получение всех станций с пагинацией
# ============================================================
def get_all_stations():
all_stations = []
offset = 0
limit = 50
while True:
data = get_stations(limit, offset)
stations = data['data']
if not stations:
break
all_stations.extend(stations)
offset += limit
if offset >= data['pagination']['total']:
break
return all_stations
# ============================================================
# 5. Использование
# ============================================================
if __name__ == "__main__":
# Получить все станции
data = get_stations(10, 0)
print(f"Всего: {data['pagination']['total']}")
# Поиск
result = search_stations('Vibe')
for station in result['data']:
print(f"{station['channel_name']} - {station['country']}")
# Фильтр
filtered = filter_stations(country='USA', status=1)
print(f"Найдено станций в USA: {filtered['pagination']['count']}")
# Получить все станции с пагинацией
all_stations = get_all_stations()
print(f"Всего станций в БД: {len(all_stations)}")
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Радиостанции</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-5">
<h1>📻 Радиостанции</h1>
<div class="row mb-4">
<div class="col-md-6">
<input type="text" id="searchInput" class="form-control"
placeholder="Поиск станций...">
</div>
<div class="col-md-3">
<select id="countryFilter" class="form-select">
<option value="">Все страны</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select>
</div>
<div class="col-md-3">
<button class="btn btn-primary w-100" onclick="loadStations()">
Загрузить
</button>
</div>
</div>
<div id="stationsList" class="row">
<!-- Станции будут здесь -->
</div>
<div id="pagination" class="d-flex justify-content-center mt-4">
<!-- Пагинация -->
</div>
</div>
<script>
const API_URL = 'https://durcoinradio.ru/api_channels_secure.php';
let currentPage = 1;
const limit = 12;
// ============================================================
// Загрузка станций
// ============================================================
async function loadStations(page = 1) {
const offset = (page - 1) * limit;
const search = document.getElementById('searchInput').value.trim();
const country = document.getElementById('countryFilter').value;
const params = new URLSearchParams({
limit: limit,
offset: offset
});
if (search) params.append('search', search);
if (country) params.append('country', country);
try {
const response = await fetch(`${API_URL}?${params}`);
const data = await response.json();
if (data.success) {
renderStations(data.data);
renderPagination(data.pagination);
}
} catch (error) {
console.error('Ошибка загрузки:', error);
}
}
// ============================================================
// Отрисовка станций
// ============================================================
function renderStations(stations) {
const container = document.getElementById('stationsList');
container.innerHTML = '';
if (stations.length === 0) {
container.innerHTML = `
<div class="col-12 text-center py-5">
<i class="bi bi-exclamation-circle" style="font-size: 3rem;"></i>
<p>Станции не найдены</p>
</div>
`;
return;
}
stations.forEach(station => {
const col = document.createElement('div');
col.className = 'col-md-4 mb-4';
col.innerHTML = `
<div class="card h-100">
<div class="card-body">
<h5>${station.channel_name}</h5>
<p class="text-muted">${station.country || 'Не указана'}</p>
<p>${station.description || 'Без описания'}</p>
<audio controls class="w-100">
<source src="${station.streaming_link}">
</audio>
</div>
<div class="card-footer">
<small class="text-muted">
👁️ ${station.view || 0} просмотров
</small>
</div>
</div>
`;
container.appendChild(col);
});
}
// ============================================================
// Пагинация
// ============================================================
function renderPagination(pagination) {
const container = document.getElementById('pagination');
const totalPages = pagination.total_pages;
if (totalPages <= 1) {
container.innerHTML = '';
return;
}
let html = '<nav><ul class="pagination">';
for (let i = 1; i <= totalPages; i++) {
const active = i === pagination.current_page ? 'active' : '';
html += `
<li class="page-item ${active}">
<a class="page-link" href="#" onclick="loadStations(${i}); return false;">
${i}
</a>
</li>
`;
}
html += '</ul></nav>';
container.innerHTML = html;
}
// ============================================================
// Обработчики событий
// ============================================================
let searchTimeout;
document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => loadStations(1), 500);
});
document.getElementById('countryFilter').addEventListener('change', () => {
loadStations(1);
});
// ============================================================
// Загрузка при открытии
// ============================================================
loadStations(1);
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
# Проверка rate limiting (быстро)
for i in {1..101}; do
curl -s -o /dev/null -w "%{http_code}\n" "https://durcoinradio.ru/api_channels_secure.php"
done
# Ожидаемый результат: первые 100 запросов - 200, 101-й - 429