Curl returning null value in JSON with PHP

Asked

Viewed 419 times

0

Well I’m studying cURL, because I want to make an application with Twitter using login form and password... yesterday I did this question and was very well answered, based on this I am studying cURL, then I have the following code:

<?php
if (isset($_POST['ttrSignin'])) {
  $ttrUsername = trim(filter_input(INPUT_POST, 'ttrUsername'));
  $ttrPassword = trim(filter_input(INPUT_POST, 'ttrPassword'));
  $ttrTweet = trim(filter_input(INPUT_POST, 'ttrTweet'));

  if (empty($ttrUsername)) {
    $error[] = 'Insira seu nome de usuário do Twitter.';
  } elseif (empty($ttrPassword)) {
    $error[] = 'Insira sua senha do Twitter.';
  } elseif (empty($ttrTweet)) {
    $error[] = 'Insira seu Tweet.';
  } else {
    # The Twitter API Address
    $url = 'https://api.twitter.com/1.1/statuses/update.json';

    # Versão alternativa do JSON
    # $url = 'https://api.twitter.com/1.1/statuses/update.json'
    # Configure e execute o processo de curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'status=' . $ttrTweet);
    curl_setopt($ch, CURLOPT_USERPWD, $ttrUsername . ':' . $ttrPassword);

    $buffer = curl_exec($ch);
    curl_close($ch);

    //var_dump($buffer);

  }

  # Verifique o sucesso ou o fracasso
  if (empty($buffer)) {
    $error[] = 'Não foi possível conectar-se ao Twitter.'; 
  } else {
    $success[] = 'Tweet postado via Twitter API.';
  }
}
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Follow</title>

    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/css/main.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <section class="section">
      <div class="container">
        <div class="row">
          <div class="row">
              <div class="col-md-4 col-md-offset-4">
                <div class="panel panel-default">
                  <div class="panel-heading">
                    <i class="fa fa-sign-in"></i> Entrar para ganhar seguidores
                  </div>

                  <div class="panel-body">
                    <form method="post">
                      <div class="form-group">
                        <input type="text" name="ttrUsername" placeholder="Usuário do Twitter" value="<?php if (isset($error)) {echo $ttrUsername;} ?>" class="form-control">
                      </div>
                      <div class="form-group">
                        <input type="password" name="ttrPassword" placeholder="Senha do Twitter" class="form-control">
                      </div>

                      <div class="form-group">
                        <input type="text" name="ttrTweet" placeholder="Digite seu Tweet" value="<?php if (isset($error)) {echo $ttrTweet;} ?>" class="form-control">
                      </div>

                      <button type="submit" name="ttrSignin" class="btn btn-primary btn-block">
                        <i class="fa fa-twitter"></i> Entrar agora
                      </button>
                    </form>
                  </div>

                  <div class="panel-footer">
                    <div class="text-center">
                      <small>
                        Ao entrar você estará concordando com os <a href="#">Termos de Uso</a>.
                      </small>
                    </div>
                  </div>
                </div>
                <?php if (isset($error)): ?>
                    <?php foreach ($error as $e): ?>
                      <div class="alert alert-danger">
                        <i class="fa fa-warning"></i> <?php echo $e; ?>
                      </div>
                    <?php endforeach ?>
                  <?php endif ?>

                  <?php if (isset($success)): ?>
                    <?php foreach ($success as $s): ?>
                      <div class="alert alert-success">
                        <i class="fa fa-check"></i> <?php echo $s; ?>
                      </div>
                    <?php endforeach ?>
                  <?php endif ?>

                  <?php if (isset($ttrTweet)): ?>
                    <?php echo $ttrTweet; ?>
                  <?php endif ?>
              </div>
          </div>
        </div>
      </div>
    </section>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
  </body>
</html>

When executed it shows the message:

Unable to connect to Twitter.

When giving a var_dump($buffer);, he returns me the following:

C: wamp64 www twitterlogin index.php:31:Boolean false

What is wrong?

  • 1

    I think that for security reasons Twitter no longer allows this. I think

1 answer

2


There are several possible problems:

  1. This endpoint (https://api.twitter.com/1.1/statuses/update.json) expects you to send the access_token, obtained using the Oauth.

    Solution: Inform the access_token.

  2. If you have not configured the CABundle and is using PHP 7.1 the Curl will check the emitter of the certificate with the authorities you trust, automatically. One of the principles of SSL is trust, if you trust the one who issued the certificate it will be safe, I won’t go into details here.

    Solution:

    1. Set the public keys of the issuers you trust, or a generic.
    2. Define where it is stored:

      curl_setopt($ch, CURLOPT_CAINFO, 'C:\local\do\ca-bundle.pem');
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
      
  3. The CURLOPT_USERPWD is for HTTP Authentication, in this case and which by default is the Basic Access Authentication, if you don’t use the CURLOPT_HTTPAUTH. Usually this data is sent in those little boxes of Alert requesting login/password, by browser, Twitter parenta not use this, since it uses Oauth.

  • I’m trying to do this without using Oauth as mentioned by you in another question of mine.

  • Okay now I don’t understand, you want to authenticate the user without using Oauth? Impossible my son, have to make form using login/ password with Oauth yes.

  • @Guilhermealves has no, does not say things, that you do not know.

  • I haven’t solved the @Inkeliz issue yet added the code you mentioned and still get errors.

  • What error? Did you download the CA-Bundle correctly specify the location? CURLOPT_CAINFO should be accurate, for example __DIR__ . '\cacert-2017-06-07.pem' if you download here. You will probably get another error, but the JSON will be shown and written the reason for the error, which is by not having the access_token.

  • It worked out arranged the directory, passed on all, showed the message that the tweet was posted, but I went to look there has nothing posted. :(

  • Note: I realized that even typing incorrect user and/ or password, the success message appears also, now I need to implode it to get the access token as said in my other question you answered.

  • Yes, because the existing JSON does not indicate that it is valid. Give a var_dump() and you will see that there is an error, now reported directly by Twitter.

  • C:\wamp64\www\twitterlogin\index.php:33:string '{"errors":[{"code":215,"message":"Bad Authentication data."}]}' (length=62) ok I’m one step away now from getting what I want... I need just oauth_token and get sessions and cookies.

  • @Inkeliz, in that case I can use the twitterOAuth to generate the token I can’t? I have already obtained information, I have compared login and password, only the token is missing and so I can generate my cookies and access sessions to the site...

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.