I need help translating python code to PHP. This is how the script is set up to communicate with the API server, using POST login in this part of the code.
The Python code has been tested and works, but I can't figure out exactly which way I should convert it to PHP because I'm getting an empty response from the API, which means - Error. I suspect using wrong post parameters or post method.In the python code, there is a comment explaining what a successful API return should look like.
edit:
var_dump($result); returns bool(false) and when error reporting is enabled, this warning will pop up:
Warning: file_get_contents(https://kodi.titlvi.com/api/subtitles/gettoken): Unable to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false)
PHP - Current Script
<?php error_reporting(-1); ini_set('display_errors', 1); $api_url = "https://kodi.titlovi.com/api/subtitles"; $username = "censored"; $password = "censored"; // sending user login request $parameters = array('username' => $username, 'password' => $password, 'json' => true); $options = array('http' => array( 'header' => 'Content-Type: application/x-www-form-urlencoded\r\n', 'method' => 'POST', 'content' => http_build_query($parameters) )); $context = stream_context_create($options); $result = file_get_contents($api_url.'/gettoken', false, $context); var_dump($result); ?>
Python (working example)
api_url = 'https://kodi.titlovi.com/api/subtitles' def handle_login(self): """ Method used for sending user login request. OK return: { "ExpirationDate": datetime string (format: '%Y-%m-%dT%H:%M:%S.%f'), "Token": string, "UserId": integer, "UserName": string } Error return: None """ logger('starting user login') login_params = dict(username=self.username, password=self.password, json=True) try: response = requests.post('{0}/gettoken'.format(api_url), params=login_params) logger('Response status: {0}'.format(response.status_code)) if response.status_code == requests.codes.ok: resp_json = response.json() logger('login response data: {0}'.format(resp_json)) return resp_json elif response.status_code == requests.codes.unauthorized: show_notification(get_string(32006)) return None else: return None except Exception as e: logger(e) return None
P粉2810894852024-03-29 13:13:59
param=dictionary
Put parameters into URL query parameters, not POST data.
The server requires the Content-length:
header, which PHP does not send by default.
In order to include \r\n
in the header, you must use double quotes, not single quotes.
$username, 'password' => $password, 'json' => True); $options = array('http' => array( 'header' => "Content-Length: 0\r\n", 'method' => 'POST', )); $context = stream_context_create($options); $result = file_get_contents($api_url.'/gettoken?' . http_build_query($parameters), false, $context); var_dump($result); ?>