Uploading a file to a cck file field using PHP and cURL
Last modified: November 17, 2008 - 16:08
This tutorial explains how to upload a local file to a Drupal site using cURL.
Anonymous user upload:
- Install filefield module.
- Goto story content type 'Manage fields'(
admin/content/node-type/story/fields). - Add a new file field to story content by the name field_file.
- Grant anonymous users the permission to create a story content and to view/ edit field_file (
admin/user/permissions). - Execute the following PHP (after changing the $file name):
<?php
global $base_url;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$content_type = 'story';
$url = "$base_url/node/add/$content_type";
curl_setopt($ch, CURLOPT_URL, $url);
$file = ""; // Enter the full path of your local file.
$post_data = array(
'title' => 'cURL title',
'body' => 'cURL Body',
'files[field_file_0]' => "@$file", // Always use the @ sign before the file name, when posting a file.
'field_file[0][fid]' => 0, // This is required.
'field_file[0][list]' => 1, // This is required as well.
'form_id' => $content_type .'_node_form',
'op' => 'Save',
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
// We assume that if the url didn't change then the form submit failed.
if ($headers['url'] == $url) {
drupal_set_message("Cannot add $content_type.");
}
else {
drupal_set_message("$content_type content created.");
}
curl_close ($ch);
?>
A new story node should have been created authored by anonymous user.
Note: a nice tip on how to figure Out What A POST Looks Like can be found under section 4.5.
