Community Documentation

Uploading a file to a cck file field using PHP and cURL

Last updated November 17, 2008. Created by Amitaibu on November 17, 2008.
Edited by VM. Log in to edit this page.

This tutorial explains how to upload a local file to a Drupal site using cURL.

Anonymous user upload:

  1. Install filefield module.
  2. Goto story content type 'Manage fields'(admin/content/node-type/story/fields).
  3. Add a new file field to story content by the name field_file.
  4. Grant anonymous users the permission to create a story content and to view/ edit field_file (admin/user/permissions).
  5. 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.

About this page

Drupal version
Drupal 6.x

Reference

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.
nobody click here