HaschekSolutions / pictshare

:camera: PictShare is an open source image, mp4, pastebin hosting service with a simple resizing and upload API that you can host yourself. :rice_scene:
https://www.pictshare.net
Apache License 2.0
819 stars 123 forks source link

Can't access to json Obj when uploading an image #105

Closed vitalijalbu closed 4 years ago

vitalijalbu commented 4 years ago

When i try to upload an image i would like to get only hash ID and save it into DB. But response object can't be accessible.

geek-at commented 4 years ago

what do you mean you can't access the json object? When you upload an image

eg via curl: curl -s -F "file=@/path/to/your/image.jpg" https://pictshare.net/api/upload.php you get the answer in form of a JSON object that defines the hash and path.

{
  "status": "ok",
  "hash": "e17o3a.jpg",
  "filetype": "jpeg",
  "url": "https://pictshare.net/e17o3a.jpg"
}
vitalijalbu commented 4 years ago

yes right, i get that json response but i can't access to hash and then save into DB. for example i have this global function that helps me to upload an image: public function upload_img($file) {

    $ch = curl_init();
    $cfile = new CURLFile($file);

    $data = array("file"=>$cfile);

    $url = "http://cdn.ceebo.com/api/upload.php";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    $response = curl_exec($ch);
    print_r($response['url']);
    if($response === true)
    {
        $output = $response['hash'];
    }
    else
    {
        $output = "error occured";
    }

  return $output;
}

Now i'd like to get only hash ID from $output, but is returns NULL

geek-at commented 4 years ago

To get the response using the curl php extension you need to set returntransfer to true.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

Also, because the answer from the server is a JSON object you'll have to parse it first before being able to use it as an array

Try this

$ch = curl_init();
$cfile = new CURLFile($file);

$data = array("file"=>$cfile);

$url = "http://cdn.ceebo.com/api/upload.php";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch),true);
var_dump($response]);
vitalijalbu commented 4 years ago

thanks it's working :D