0

I'm trying to add images to my products using CURL in PHP based on this: https://shopify.dev/api/admin-rest/2022-07/resources/product-image#post-products-product-id-images

This is what it should look like using CURL CLI but I'm trying to use it through PHP:

curl -d '{"image":{"src":"http://example.com/rails_logo.gif"}}' \
-X POST "https://your-development-store.myshopify.com/admin/api/2022-07/products/632910392/images.json" \
-H "X-Shopify-Access-Token: {access_token}" \
-H "Content-Type: application/json"

I've tried a number of different format but keep getting Cloudflare errors with the below format:

$ch = curl_init("https://STORENAME.myshopify.com/admin/api/2022-07/products/632910392/images.json");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Shopify-Access-Token: SECRETTOKEN"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_URL, "http://example.com/rails_logo.gif");
curl_setopt($ch, CURLOPT_INFILE, "http://example.com/rails_logo.gif");
curl_setopt($ch, CURLOPT_POSTFIELDS,'{"image":{"position":'1',"src":"http://example.com/rails_logo.gif"}}');
$responseTmp = curl_exec($ch);

I'm getting "BAD REQUEST" and "1020" errors from Cloudflare, I assume because something in my request isn't formatted correctly.

Would appreciate any advice.

  • Those calls are not equivalent. E.g. `CURLOPT_URL` here you are overriding the url you are PUTing to to be the url of the image. – AD7six Aug 14 '22 at 01:06
  • Thanks @AD7six - how do I specify the PUT URL properly? – user2518193 Aug 14 '22 at 01:14
  • Does this answer your question? [How to POST JSON Data With PHP cURL?](https://stackoverflow.com/questions/11079135/how-to-post-json-data-with-php-curl) – AD7six Aug 14 '22 at 01:21
  • @AD7six I did read through that one earlier but still couldn't make sense of how to deal with the two (-d and -X) post types within the same request. – user2518193 Aug 14 '22 at 01:27
  • It is off from this question. How do you get the access token? I am lost in the documents. – arun kumar Jan 10 '23 at 09:24

1 Answers1

0

In case it helps someone else further down the track - this is how Shopify expects image uploads via php curl:

$image = json_encode(array('image'=> array('src' => $imageUrl)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $image);