Skip to content

Commit

Permalink
UPLOAD_URL is now a constant. handle file_get_contents() returning FA…
Browse files Browse the repository at this point in the history
…LSE. merge curlQuery function with curlUpload function. handle imgur's response status.
  • Loading branch information
pkrumins committed Jul 19, 2015
1 parent 41bd337 commit 3c40a73
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions index.php
Expand Up @@ -5,6 +5,7 @@ class ImgurUploader {
private $error;

const TIMEOUT = 30;
const UPLOAD_URL = 'https://api.imgur.com/3/image.json';

public function setClientId($clientId) {
$this->clientId = $clientId;
Expand Down Expand Up @@ -36,17 +37,15 @@ public function uploadImage($filename) {
return FALSE;
}

$data = file_get_contents($filename);
if (!$data) {
$image = file_get_contents($filename);
if ($image === FALSE) {
fclose($handle);
$this->setError("Failed reading contents of '$filename'");
return FALSE;
}
fclose($handle);

return $this->curlUpload([
'image' => base64_encode($data)
]);
return $this->curlUpload(base64_encode($image));
}

public function uploadImageBase64($imageBase64) {
Expand All @@ -55,25 +54,18 @@ public function uploadImageBase64($imageBase64) {
return FALSE;
}

return $this->curlUpload([
'image' => $imageBase64
]);
return $this->curlUpload($imageBase64);
}

private function curlUpload($params) {
$url = 'https://api.imgur.com/3/image.json';
return $this->curlQuery($params, $url);
}

private function curlQuery($params, $url) {
private function curlUpload($imageBase64) {
$curl = curl_init();
if (!$curl) {
$errstr = $this->getCurlStrError($curl);
$this->setError("Failed initializing curl: $errstr");
return FALSE;
}

$ret = curl_setopt($curl, CURLOPT_URL, $url);
$ret = curl_setopt($curl, CURLOPT_URL, self::UPLOAD_URL);
if (!$ret) {
$errstr = $this->getCurlStrError($curl);
$this->setError("Failed setting CURLOPT_URL: $errstr");
Expand Down Expand Up @@ -108,7 +100,9 @@ private function curlQuery($params, $url) {
return FALSE;
}

$ret = curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$ret = curl_setopt($curl, CURLOPT_POSTFIELDS, [
'image' => $imageBase64
]);
if (!$ret) {
$errstr = $this->getCurlStrError($curl);
$this->setError("Failed setting CURLOPT_POSTFIELDS: $errstr");
Expand Down Expand Up @@ -142,10 +136,16 @@ private function setError($error) {
$result = $imgur->uploadImage('browserling.png');
if (!$result) {
$error = $imgur->getError();
print "Error: $error";
print "Upload failed. Error: $error";
}
else if ($result['status'] != 200) {
print "Upload failed. Error: " . $result['data']['error'];
print_r($result);
}
else {
print "Upload successful!";
print_r($result);
}

print_r($result);

?>

0 comments on commit 3c40a73

Please sign in to comment.