Karthik Kannan
Karthik Kannan

Reputation: 187

Trying to get profile image from Twitter, what is wrong with this code?

I wrote this code, it runs but doesnt return the profile picture for me. I double checked the url for getting the pic too. Where exactly did I go wrong? I also want the picture that is returned to be of the size 150x150px. How do I get a custom size to be displayed. Thanks!

<?php
define('BASE_URL', 'http://api.twitter.com/1/users/profile_image/screen_name=');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $handle = $_POST['handle'];
  $size = 'bigger';
  if (isset($handle) && isset($size)) {
$twitterURL = BASE_URL . $handle . '&size=' . $size;
 }
}
?>


<!DOCTYPE HTML>
<html lang="it-IT">
<head>
<meta charset="UTF-8">
<title>Get TwitterPic</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:200' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">

</head>
<body>

<div id="wrapper">
<h1>Get image from twitter</h1>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <p><label for="handle">Twitter Handle</label>
        <input type="text" id="twitter" name="handle" placeholder="Twitter Handle"></p>



    <p><input type="submit" value="Get Twitter Pic"></p>
    </form>
  <?php if (isset($size) && isset($twitterURL)): ?>
<img src="<?= $twitterURL ?>">
  <?php endif; ?>
</div>



</body>
</html>

Upvotes: 1

Views: 650

Answers (2)

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

Check out Twitter's API documentation for this method:

This method must not be used as the image source URL presented to users of your application.

This method doesn't return the image data, but rather an HTTP 302 Redirect header, redirecting an HTTP request to a new source. This won't work, and isn't supposed to work.

Also, note that you're using v1 of the Twitter API, which is deprecated and might stop working at any moment. Check out the users/show method of the API v1.1.

Upvotes: 2

zeliboba
zeliboba

Reputation: 46

First i was curious, because it's supposed to work. Then i've discovered multiple issues in your code.

you gotta use https://dev.twitter.com/docs/api/1/get/users/profile_image/:screen_name

And this code had to be changed, you had wrong variable name:

<?php if (isset($size) && isset($twitterURL)): ?>
<img src="<?= $twitterURL ?>">
  <?php endif; ?>

Working with error_level = ALL during the development would help a lot, if you can't use modern IDE which prevent this from happening.

Upvotes: 0

Related Questions