I'm using hook_feeds_after_save and the simpleHTMLdom library to migrate inline images for a feed import. After I detect that an image tag exists and the url is qualified/valid I build a stream wrapper for the image file and call system_retrieve_file.

  $dirPrefix = 'archive';
  $uri = file_build_uri($dirPrefix . '/' . $filepath);

  if (file_prepare_directory($uri, FILE_CREATE_DIRECTORY)) {
    $destination = $uri . '/' . $filename;
    system_retrieve_file($img_url, $destination, TRUE, FILE_EXISTS_REPLACE);

However, I receive 400 errors on each image; HTTP error 400 occurred when trying to fetch http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg.

If I just plop this url into a browser I get a 200 and the image is displayed. Same when I test this in something like the Advanced Rest Client application.

Also, I'm developing this site in a local environment.

Anyone have any clue how to debug this or why I may be receiving a 400 response?

  • It's going to be trial & error really - first check that you can download resources from other domains ok via drupal_http_request, if yes then you can be reasonably sure the server giving a 400 is objecting to something in the request headers and it's not a PHP/local config issue. Do you own the remote server? If so check its config/process for anything suspicious. If not, you'll probably have to experiment with matching the headers that your browser or other client sends. Some people have a whitelist of user agent strings, for example. If that's the case you can just pretend you're Chrome
    – Clive
    Jun 5 '17 at 18:00

In my case, I needed to encode urls, but not how you may expect with PHP's urlencode or rawurlencode. For example, I needed to convert http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg to http://DOMAIN.COM/C8B195/assets/images/01%20Grapes%203.jpg. I'm not sure why system_retrieve_file or drupal_http_request had a problem with the spaces.

  $encodedPath = rawurlencode($path);
  $encodedPath = str_replace('%3A', ':', str_replace('%2F', '/', $encodedPath));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.