Permalink
Browse files

Use file_put_contents() because it's sexier and stuff. Improve check …

…to make sure script is running locally. Turn off curl verbosity. Add comments. Die if twitter doesn't respond with a 200 so we don't write garbage data.
  • Loading branch information...
1 parent 8367a9c commit 1d0ef9a88fef7628dfaa0f1f5137e2081cdb23e4 @pifantastic pifantastic committed Dec 11, 2011
Showing with 12 additions and 6 deletions.
  1. +12 −6 avatars.php
View
@@ -1,12 +1,15 @@
<?php
+// Enable errors for easy debugging.
error_reporting(E_ALL);
ini_set('display_errors', '1');
+// Configurable stuff.
define('URL', 'http://search.twitter.com/search.json');
define('SEARCH_PREFIX', '(ivegotmybluebeanieonnowwhat.com OR movethewebforward.com OR movethewebforward.org) AND ');
define('RPP', 100);
+// Hashtags to search twitter for.
$queries = array(
"#learn",
"#ask4help",
@@ -18,9 +21,11 @@
"#hack"
);
-if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1')
+// Don't let random scallywags run this script.
+if ((isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') || PHP_SAPI !== 'cli')
die('');
+// Search twitter, return full json_decode()'d response.
function search($query, $page = 1) {
$url = URL . '?' . http_build_query(array(
'q' => SEARCH_PREFIX . $query,
@@ -29,7 +34,6 @@ function search($query, $page = 1) {
));
$ch = curl_init($url);
- curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'movethewebforward.org');
@@ -43,9 +47,12 @@ function search($query, $page = 1) {
if ($status == 200) {
return json_decode($response);
}
- return FALSE;
+ else {
+ die("Twitter error: " . $status);
+ }
}
+// Get all results for a query.
function getAll($query) {
$page = 0;
$avatars = array();
@@ -62,12 +69,11 @@ function getAll($query) {
return $avatars;
}
+// Merge new avatars into our file of existing avatars.
$avatars = json_decode(file_get_contents('avatars.json'));
foreach ($queries as $query) {
$avatars->$query = array_merge((array)$avatars->$query, getAll($query));
}
-$fp = fopen('avatars.json', 'w');
-fwrite($fp, json_encode($avatars));
-fclose($fp);
+file_put_contents('avatars.json', json_encode($avatars));

0 comments on commit 1d0ef9a

Please sign in to comment.