Drupal form api file upload using drupal_http_request - forms

I am trying to post a file uploaded in drupal form to another server through a post request using drupal_http_request.
I am not sure where am I making a mistake but the file doesnot seem to get posted. What should I be doing.?
I use the following code.
$options = array(
'method' => 'POST',
'data' => drupal_http_build_query($data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => 'multipart/form-data'),
);
$response = drupal_http_request($url, $options);
multipart/form-data doesnot seem to work.

Source: https://drupal.org/user/194073
<?php
$boundary = md5(uniqid());
$post_data = array(
'name' => 'Ayesh',
'file' => '/var/www/test/test.png',
);
$options = array(
'method' => 'POST',
'data' => multipart_encode($boundary, $post_data),
'timeout' => $connect_ariba_values['timeout'],
'headers' => array('Content-Type' => "multipart/form-data; boundary=$boundary"),
);
$response = drupal_http_request($url, $options);
// Function to encode text data.
function multipart_enc_text($name, $value){
return "Content-Disposition: form-data; name=\"$name\"\r\n\r\n$value\r\n";
}
// Function to multipart encode a file from a give path.
function multipart_enc_file($path){
if (substr($path, 0, 1) == "#") $path = substr($path, 1);
$filename = basename($path);
$mimetype = "application/octet-stream";
$data = "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\r\n"; // "file" key.
$data .= "Content-Transfer-Encoding: binary\r\n";
$data .= "Content-Type: $mimetype\r\n\r\n";
$data .= file_get_contents($path) . "\r\n";
return $data;
}
// base function to encode a data array.
function multipart_encode($boundary, $params){
$output = "";
foreach ($params as $key => $value){
$output .= "--$boundary\r\n";
if ($key == 'file'){
$output .= multipart_enc_file($value);
} else $output .= multipart_enc_text ($key, $value);
}
$output .="--$boundary--";
return $output;
}
In the server, file will be available in $_FILES['file'], and other POST data will be available in their relevant keys.
I didn't test the code. I just found the code in drupal forum, changed it to work with Drupal 6 and 7.

Related

Paragraph breaks missing from shortcode output

I created a shortcode in Wordpress to perform a query and display the content, but the content line breaks are being removed.
add_shortcode( 'resource' , 'Resource' );
function Resource($atts) {
$atts = shortcode_atts( array(
'category' => ''
), $atts );
$categories = explode(',' , $atts['category']);
$args = array(
'post_type' => 'resource',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page'=> -1,
'tax_query' => array( array(
'taxonomy' => 'category',
'field' => 'term_id',
'operator' => 'AND',
'terms' => $categories
) )
);
$string = '';
$query = new WP_Query( $args );
if( ! $query->have_posts() ) {
$string .= '<p>no listings at this time...</p>';
}
while( $query->have_posts() ){
$query->the_post();
$string .= '<div id="links"><div id="linksImage">' . get_the_post_thumbnail() . '</div>
<div id="linksDetails"><h1>'. get_the_title() .'</h1><p>' . get_the_content() . '</p>
<p>for more information CLICK HERE</div></div>';
}
wp_reset_postdata();
$output = '<div id="linksWrapper">' . $string . '</div>';
return $output;
}
Any suggestion on why this is happening and what to do to fix it. This is only happening on the shortcode output. On regular pages - the content displays correctly.
found a solution through more searches:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
works perfect, so I thought I would share..

Set header fields for HTTP::Request::Common

I've problems to set header fields for sending requests by Perl modul 'HTTP::Request::Common'.
In subject to the corresponding server I have to set different header fields for my request.
So I want to use a sub 'MakeRequest()'
sub MakeRequest {
my $url = shift;
my $header = shift;
my $content = shift;
my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);
# I tried also my $request = HTTP::Request::Common::POST($url, $header, Content => $content);
my $ua = LWP::UserAgent->new;
my $response = $ua->request($request);
return $response;
}
and pass some informations into it my $response = MakeRequest($url, GetRequestHeader(), $content);
sub GetRequestHeader {
my $header = HTTP::Headers->new;
$header->header('Content-Type' => 'application/json; charset=utf-8');
$header->header('accept' => 'application/json');
$header->authorization_basic($username, $password);
return $header;
# I tried this first, but got the same result as shown below
#
# my %header = (
# 'content_type' => 'application/json; charset=utf-8',
# 'authorization_basic' => ($username, $password),
# 'accept' => 'application/json'
# );
# return %header;
}
But all I got from the remote server is this
"Content type 'application/x-www-form-urlencoded' is not supported.
Please use 'application/json; charset=utf-8'."
When I made a print Data::Dumper($request); I get
'_headers' => bless( {
'content-length' => 544,
'user-agent' => 'libwww-perl/6.15',
'header' => bless( {
'content-type' => 'application/json; charset=utf-8',
'authorization' => 'Basic Qxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==',
'accept' => 'application/json'
}, 'HTTP::Headers' ),
'::std_case' => {
'header' => 'Header',
'if-ssl-cert-subject' => 'If-SSL-Cert-Subject'
},
'content-type' => 'application/x-www-form-urlencoded'
}, 'HTTP::Headers' ),
What's my mistake that the 'content-type' isn't overwritten by my header field settings?
According to the documentation:
HTTP::Request::Common::GET $url, Header => Value,...
is the same as
HTTP::Request->new(
GET => $url,
HTTP::Headers->new(Header => Value,...),
)
I think your original approach (the commented) is good, but you assign it the wrong way:
my $header = shift;
my $content = shift;
my $request = HTTP::Request::Common::POST($url, Header => $header, Content => $content);
Here, you create only one header, named Header. You can use the following if you have a HTTP::Headers object:
my $request = HTTP::Request::Common::POST($url, $header->flatten, Content => $content);
If you change GetRequestHeader to return a hash reference (as you have commented, but with return \%header instead of return %header), you can use the following:
my $request = HTTP::Request::Common::POST($url, %$hashref, Content => $content);

need to set headers on guzzle request

I need to add the type of headers to the guzzle request below, but cannot figure out how to put it in without getting an error
This is what I want to add :
$command->set('command.headers', array('content-type' => 'application/x-www-form-urlencoded
to this code below:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
When I needed use the Guzzle at D8 to make a POST I passed the Content-Type like this:
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => rawData($post_data),
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
A good idea is use the D8 Dependency Injection to pass the HTTP_CLIENT.

Drupal7 REST: I am not able to perform POST and PUT methods. Error is :Not Acceptable : Node type is required, Code:406?

I'm using drupal7. my drupal_http_request() for get and delete are working fine for authenticated users, but the post and put methods are not working.
The error is :Not Acceptable : Node type is required, and http error code is :406. My code is below:
function ws_form_post_auth() {
$base_url = 'http://localhost/drupalws/api/v1';
$data = array(
'username' => 'student1',
'password' => 'welcome',
);
$data = http_build_query($data, '', '&');
$options = array(
'headers' => array(
'Accept' => 'application/json',
),
'method' => 'POST',
'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$data = array(
'title' => 'First forum post',
'type'=> 'forum',
'body'=> array(
'und'=>array(
0=> array(
'value'=>'This is my first forum post via httprequest.'
)
)
)
);
$data = json_encode($data);
$options['data'] = $data;
$options['method'] = 'POST';
$response = drupal_http_request($base_url . '/node', $options);
return $response->status_message;
}
return $response->status_message;
}
I got the solution for my issue,I just missed a Content-Type in Headers.
[....]
if ($response->code == 200) {
$options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
$options['headers']['X-CSRF-Token'] = $data->token;
$options['headers']['Content-Type'] = 'application/json';
[....]

Is Facebook batch request photo upload with no_story possible?

Is it?
Uploading works like a charm, but I don't want it to show up on timeline or feed.
I've tried adding no_story to each request, and to the $params which is commented out in following code:
foreach ($data['Ad']['Media'] as $medium) {
$file = $medium['tmp_name'];
$req = array(
'method' => 'POST',
'relative_url' => '/me/photos',
'message' => $data['Ad']['title'],
'attached_files' => 'file' . $count,
'no_story' => 1 //Also tried 'true'
);
//add this request to batch
$batch[] = json_encode($req);
$params['file' . $count] = '#' . realpath($file);
$count++;
}//foreach
$params['batch'] = '[' . implode(',', $batch) . ']';
//$params['no_story'] = true;
Edit ##
See comment below.
i know you may not need the answer any more, but i was facing same issue , and after a lot of try and error i figured it out so i will post the answer may be some one face this issue again
$req = array(
'method' => 'POST',
'relative_url' => '/me/photos',
'attached_files' => 'file' . $count,
'body' => 'no_story=1'
);