Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save MuhammadReda/e2fee99a2469bc324f38 to your computer and use it in GitHub Desktop.
Save MuhammadReda/e2fee99a2469bc324f38 to your computer and use it in GitHub Desktop.
Drupal 7 and Services 3 - How to Upload file / image
<?php
/**
* This is a code sample for how to upload file to drupal services.
*
* This code sample focuses on uploading files and assumes that you are successfully autheticated.
*/
$httpMethod = 'POST';
$resourceUrl = 'http://example.com/api/file';
$headers = array(
'Content-Type: application/json',
'X-CSRF-TOKEN: ABC-MNO-XYZ',
);
$filePath = "/path/to/file.txt";
$requestFields = array(
'filename' => basename($filePath),
'filesize' => filesize($filePath),
'file' => base64_encode(file_get_contents($filePath)),
);
$curl = curl_init($resourceUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $httpMethod);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($requestFields));
$response = curl_exec($curl);
curl_close($curl);
$result = json_decode($response);
$newFileId = $result->fid;
$newFileUri = $result->uri;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment