Премьер-лига Fantasy API PHP cURL - PullRequest
1 голос
/ 04 июля 2019

Мне было интересно, не могли бы вы помочь мне с небольшим количеством кода для запроса cCURL с использованием PHP, я пытаюсь получить данные из API-интерфейса fpl, которые бы отображали мой рейтинг в лиге.URL-адрес api турнирной таблицы лиги - https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/?page_new_entries=1&page_standings=1 Я вижу данные через браузер, но когда я пытаюсь получить их с помощью запроса curl с помощью PHP, возвращается ошибка 403 с сообщением «Учетные данные аутентификации былине предоставлен".Это означало бы, что мне понадобятся учетные данные для входа в систему.

Изучив его с помощью инструментов разработчика и почтальона, я теперь знаю, что мне нужно получить токен csrf, войдя в систему, а затем сохранить токен для использования приЯ делаю запрос на турнирной таблице лиги.Я понятия не имею, как это сделать, я вроде бы так делаю, но я был бы очень признателен, если бы кто-то смог мне помочь.

Что мне нужно сделать, это сделать запрос POST на https://users.premierleague.com/accounts/login/ с данными этой формы -

"login"         => "my_email",
"password"      => "my_password",
"app"           => "plfpl-web",
"redirect_uri"  => "https://fantasy.premierleague.com/",

После выполнения запроса мне потребуется перехватить cookie-файл токена csrf, который, как я полагаю, будет находиться в скрытом вводе с именем - "csrfmiddlewaretoken" и сохранить его.в переменной.

Получив токен и сохранив его, я бы сделал запрос GET на https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/, поместив переменную токена csrf, которую я сохранил, в заголовки, а затем json декодировал эти данные.так что я могу повторить подробности лиги.

Я почти уверен, что это то, как это сделать, но я не настолько хорош в PHP, и мне было интересно, есть ли какой-нибудь запах, который мог бы помочьбрат вышел.Любая помощь будет принята с благодарностью:)

Я начал с первой части, сделал первоначальный пост-запрос, но не смог вернуть токен.Вот мой код до сих пор -

<?php

$cookie = "cookies.txt";
$url = 'https://users.premierleague.com/accounts/login/';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

// var_dump($response);

$dom = new DOMDocument;
@$dom->loadHTML($response);

$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
    $grab = $tags->item($i);
    if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
        $token = $grab->getAttribute('value');
    }
}

echo $token;

?>

1 Ответ

0 голосов
/ 05 июля 2019
<code><?php

// id of the league to show
$league_id  = "your_league_id";

// set the relative path to your txt file to store the csrf token
$cookie_file = realpath('your_folder_dir_to_the_txt_file/cookie.txt');

// login url
$url = 'https://users.premierleague.com/accounts/login/';

// make a get request to the official fantasy league login page first, before we log in, to grab the csrf token from the hidden input that has the name of csrfmiddlewaretoken
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);

$dom = new DOMDocument;
@$dom->loadHTML($response);

// set the csrf here
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
    $grab = $tags->item($i);
    if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
        $token = $grab->getAttribute('value');
    }
}

// now that we have the token, use our login details to make a POST request to log in along with the essential data form header fields
if(!empty($token)) {
    $params = array(
        "csrfmiddlewaretoken"   => $token,
        "login"                 => "your_email_address",
        "password"              => "your_password",
        "app"                   => "plfpl-web",
        "redirect_uri"          => "https://fantasy.premierleague.com/",
    );

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    /**
     * using CURLOPT_SSL_VERIFYPEER below is only for testing on a local server, make sure to remove this before uploading to a live server as it can be a security risk.
     * If you're having trouble with the code after removing this, look at the link that @Dharman provided in the comment section.
     */
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //***********************************************^

    $response = curl_exec($ch);

    // set the header field for the token for our final request
    $headers = array(
        'csrftoken ' . $token,
    );
}

// finally, we now have everything we need to make the GET request to retrieve the league standings data. Enjoy :)
$fplUrl = 'https://fantasy.premierleague.com/api/leagues-classic/' . $league_id . '/standings/';
curl_setopt($ch, CURLOPT_URL, $fplUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);

if(!empty($token)) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}

$response = curl_exec($ch);
$league_data = json_decode($response, true);
curl_close($ch);

echo '<pre class="card">';
    print_r($league_data);
echo '
'; ?>
...