I need help regarding translating python code to PHP. The script is setup that way so it communicates with API server,logging in using POST in this part of code.
Python code is tested and working, however I can't manage to tell in which way should it exactly be translated to PHP, since I'm getting empty response from API, which would mean - error. I suspect use of wrong post parameters or post method.
In the python code, there's a comment that says what success API return should look like.
EDIT:
var_dump($result); is returning bool(false) and after enabling error reports, this warning pops out:
Warning: file_get_contents(https://kodi.titlovi.com/api/subtitles/gettoken): failed 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
My Answer:
The equivalent for Python is "Python". Python is a high-level programming language known for its simplicity and readability.
Rate this post
4 of 5 based on 2368 votesComments