Home > Mobile >  What is the equivalent for Python 'requests.post' in PHP?
What is the equivalent for Python 'requests.post' in PHP?

Time:04-26

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

CodePudding user response:

param=dictionary puts the parameters in URL query parameters, not POST data.

The server requires a Content-length: header, which PHP doesn't send by default.

In order to include \r\n in the header, you have to use double quotes, not single quotes.

<?php
    error_reporting(-1);
    ini_set('display_errors', 1);

    $api_url = "https://kodi.titlovi.com/api/subtitles";

    $username = "XXX";
    $password = "YYY";

    // sending user login request
    $parameters = array('username' => $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);
?>
  • Related