How to convert curl call with “-i --upload-file” into PHP? - linkedin

This call is referenced in step 2 of the docs here
I am following the docs to create an image and text share in LinkedIn through the version 2 API. Following the steps in the docs, I completed each step with a successful response. However, my post does not exist in LinkedIn, and cannot be viewed by direct link based on the ID returned by the API request
In debuging I made a get request to https://api.linkedin.com/v2/assets/C5622AQFbyxMfU2b9zg. This is to retrieve the media asset (docs here) created in the first step. It returned the following json with the 'CLIENT_ERROR' status. If you look at the docs though, this status is not one of those listed for the field
{
"serviceRelationships": [
{
"identifier": "urn:li:userGeneratedContent",
"relationshipType": "OWNER"
}
],
"recipes": [
{
"recipe": "urn:li:digitalmediaRecipe:feedshare-image",
"status": "CLIENT_ERROR"
}
],
"mediaTypeFamily": "STILLIMAGE",
"created": 1550875198973,
"lastModified": 1550875199857,
"id": "C5622AQFbyxMfU2b9zg",
"status": "ALLOWED"
}
I was able to successfully upload the file using the command line curl. It seems the issue is with my PHP implementation. Specifically the upload of the binary file is not working right. Here is a simplified representation of my php code.
$ch = curl_init();
$headers = [
'Authorization: Bearer ' . $this->accessToken->access_token,
'Cache-Control: no-cache',
'X-RestLi-Protocol-Version: 2.0.0',
'x-li-format: json',
'Content-Type: ' . $this->mimetype
];
$data = [
'file' => curl_file_create($filename, $this->mimetype);
];
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, 'https://api.linkedin.com/mediaUpload/C5622AQHSLBWkZeg-gQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJIFvVUxXl7yAAAAWkwjT0kEPKHY5BnAgXETcVQ3AbsxmvaGl6hnuECwA&app=22961836&sync=0&v=beta&ut=2RaKRdHD_OwUE1');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
print_r($result);

I ran into this same issue recently and linkedin's documents were not very helpful.
Create an Image Share.
The first thing to understand is that "curl --upload-file" uses a PUT request method. Here is what I used using dummy data.
$file = "/storage/media/testimg.jpg";
$uploadurl = "https://api.linkedin.com/mediaUpload/C5622AQHSLBWkZeg-gQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJIFvVUxXl7yAAAAWkwjT0kEPKHY5BnAgXETcVQ3AbsxmvaGl6hnuECwA&app=22961836&sync=0&v=beta&ut=2RaKRdHD_OwUE1";
$accesstoken = "acacdsv13rv31bv13b1cf13cf13rv13rv13vr13tb5dxvghn";
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $uploadurl);
curl_setopt($curl_handle, CURLOPT_PUT, 1);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
$fh_res = fopen($file, 'r');
curl_setopt($curl_handle, CURLOPT_INFILE, $fh_res);
curl_setopt($curl_handle, CURLOPT_INFILESIZE, filesize($file));
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$headers[] = "Authorization: Bearer $accesstoken"; //linkedin says to add 'redacted' instead of access token (that's bullshit)
$headers[] = 'Connection: Keep-Alive';
$headers[] = "X-RestLi-Protocol-Version:2.0.0";
curl_setopt($curl_handle,CURLOPT_HTTPHEADER,$headers);
$rcurl = curl_exec($curl_handle);
curl_close($curl_handle);
If you dump the response $rcurl you only get an empty string. So the next step is to check the status of the upload, something they completely forgot to mention as part of the image share documentation but can be found here Check Status of Uphold
Using the asset variable from the initial image register call, you check the upload's status until the status check returns AVAILABLE.
$asset = "urn:li:digitalmediaAsset:C4asdfvqqrv3";
$a = explode("digitalmediaAsset:", $asset);
$statuscheck = make a GET curl call to the url: "/assets/" . $a[1]
$uploadstat = $statuscheck['recipes'][0]['status'];
do{
$statuscheck = make a GET curl call to the url: "/assets/" . $a[1];
$uploadstat = $statuscheck['recipes'][0]['status'];
}while($uploadstat != 'AVAILABLE');
Once AVAILABLE is returned, you can now proceed to the next step of creating the image share. Hope this helps.

Related

Get data to Patch API

Im using api-platform to host my api. What is the proper way to fill form with data before PATCH it using symfony forms?
Is this a good way to use curl and then send edited form?
// getting data to fill form to know which one currently you're updading
$preClient = new CurlHttpClient();
$preFetch = $preClient->request('GET', 'myapiendpoint'.$id.'');
$preContent = $preFetch->toArray();
$form = $this->createForm(ProductType::class, $preContent);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$requestData = $form->getData();
$requestJson = json_encode($requestData, JSON_THROW_ON_ERROR);
$this->client->request('PUT', 'myapiendpoint'.$id.'', [
'headers' => [
'Content-Type: application/json',
'Accept: application/json'
],
'body' => $requestJson
]);
$this->addFlash('success', 'Success');
return $this->redirectToRoute('index');
}

Am I generating the OAuth signature incorrectly or is there another issue with this Perl / OAuth client code?

OK, I'm going nuts here. I've spent the better part of a week working on this with Fiddler, Rest API Log, Apache logs, Postman, etc. and am no closer to a solution. Hopefully this will provide someone with a good laugh (as it's easy) and me with a solution (for my sanity).
I have a Wordpress 4.9.8 install hosted on hostgator. I have the WP REST API - OAuth 1.0a Server plugin installed and am attempting to authenticate with OAuth from a Perl script. I've been successful connecting with Postman using the credential generated by registering an application in the UI (Wordpress > Users > Applications) but cannot seem to crack the code using curl or a perl script (or php or anything else I've tried). As Postman works (whenever it does not generate a space in the OAuth signature) I believe the plugin does, in fact, work. Below is my code where I've attempted to follow the spec regarding parameters, sorting, URI encoding, utf8 encoding, etc. Everything 'looks' ok when examining headers/query params in either Fiddle or the REST API Log plugin (pretty great little tool, that) and yet, no love.
Thanks for any advice or direction.
Client code:
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use JSON;
use URI::Escape;
use Digest::HMAC_SHA1 qw( hmac_sha1 );
use MIME::Base64 qw( encode_base64 );
use Encode;
use Data::Dumper;
my $timestamp = time();
my $method = 'GET';
my $url = "https://hoppingmadmonkey.com/wp-json/myapiplugin/v2/greeting";
my $client_secret = "GelrnAAr1nCe5fzmTqzrU82PsfKCmKlDOZrLPakQRkH4sizJ";
my $token_secret = "mdeVuJnrs8VSDJNJfMNPQRqBkG8xadfK0jAYjDGhmKOeaY7O";
#my $nonce = $ARGV[0]; # test with Postman generated parameters
#$timestamp = $ARGV[1]; # test with Postman generated parameters
#my $signature = $ARGV[2]; # test with Postman generated parameters
my %params = (
oauth_consumer_key => "NCo8bflKU9LI",
oauth_signature_method => "HMAC-SHA1",
oauth_realm => "https://hoppingmadmonkey.com",
oauth_timestamp => $timestamp,
oauth_token => "2GeFG7MkXliq2OBOSSCSRBPX",
oauth_version => "1.0",
);
$params{oauth_nonce} = create_nonce();
#$params{oauth_nonce} = $nonce; # test with Postman generated parameters
$params{oauth_timestamp} = $timestamp;
my $key = create_key($client_secret,$token_secret);
my ($params,$base) = build_base_string($method, $url, \%params);
my $signature = create_signature($base, $key);
#for (sort keys %params) { print "$_=$params{$_}", "\n"; }
print "params: $params\n\n";
print "basestring: $base\n\n";
print "key: $key\n\n";
print "signature [$signature]\n\n";
$params{oauth_signature} = $signature; # -- set signature for GET query string
my $request_string = build_request_string($url,\%params);
print "\nrequest_string [$request_string]\n\n";
my $ua = LWP::UserAgent->new();
$ua->default_header("Authorization", "Basic user:pass");
my $response = $ua->get($request_string);
print Dumper $response, "\n";
exit;
my $curlcmd = qq{/usr/bin/curl -i -X GET "$request_string"};
#`$curlcmd 2>&1`;
sub create_signature {
my ($t,$k) = #_;
my $str = encode_base64(hmac_sha1($t,$k));
chomp $str;
return $str;
}
# Create unique nonce
#
sub create_nonce {
my $str = `/bin/cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 11 | head -n 1`;
chomp $str;
return $str;
}
# Create oauth key for generating hmac-sha1 signature
#
sub create_key {
my ($cs,$ts) = #_;
$cs = encode('utf8',uri_escape($cs));
$ts = encode('utf8',uri_escape($ts));
return "$cs&$ts";
}
# Build basestring for generating hmac-sha1 signature
#
sub build_request_string {
my ($u,$p) = #_;
my %params = %$p;
my $str = $u . '?';
my #tmp;
for (sort keys %params) {
$p = uri_escape($_) . '=' . uri_escape($params{$_});
push #tmp, $p;
}
$str .= join '&', #tmp;
return $str;
}
# build the base string parameter for creating the signature
#
sub build_base_string {
my ($m,$u,$phash) = #_;
my %params = %$phash;
my $str = $method;
$str .= '&' . uri_escape($u) . '&';
my #tmp;
for (sort keys %params) {
push #tmp, uri_escape("$_=$params{$_}");
}
$params = join '&', #tmp;
$str .= join '&', #tmp;
return $params,$str;
}
1;
The result of running this from the command line is:
dnu [test] ::>./oauth-perl.pl
params: oauth_consumer_key%3DNCo8bflKU9LI&oauth_nonce%3DJrGdlVLXpB4&oauth_realm%3Dhttps%3A%2F%2Fhoppingmadmonkey.com&oauth_signature_method%3DHMAC-SHA1&oauth_timestamp%3D1542134239&oauth_token%3D2GeFG7MkXliq2OBOSSCSRBPX&oauth_version%3D1.0
basestring: GET&https%3A%2F%2Fhoppingmadmonkey.com%2Fwp-json%2Fmyapiplugin%2Fv2%2Fgreeting&oauth_consumer_key%3DNCo8bflKU9LI&oauth_nonce%3DJrGdlVLXpB4&oauth_realm%3Dhttps%3A%2F%2Fhoppingmadmonkey.com&oauth_signature_method%3DHMAC-SHA1&oauth_timestamp%3D1542134239&oauth_token%3D2GeFG7MkXliq2OBOSSCSRBPX&oauth_version%3D1.0
key: GelrnAAr1nCe5fzmTqzrU82PsfKCmKlDOZrLPakQRkH4sizJ&mdeVuJnrs8VSDJNJfMNPQRqBkG8xadfK0jAYjDGhmKOeaY7O
signature [2pJRR1fz0uUdUWHlUjHFWlXFbL4=]
request_string [https://hoppingmadmonkey.com/wp-json/myapiplugin/v2/greeting?oauth_consumer_key=NCo8bflKU9LI&oauth_nonce=JrGdlVLXpB4&oauth_realm=https%3A%2F%2Fhoppingmadmonkey.com&oauth_signature=2pJRR1fz0uUdUWHlUjHFWlXFbL4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1542134239&oauth_token=2GeFG7MkXliq2OBOSSCSRBPX&oauth_version=1.0]
$VAR1 = bless( {
'_protocol' => 'HTTP/1.1',
'_content' => '
{"code":"json_oauth1_signature_mismatch","message":"OAuth signature does not match","data":{"status":401}}',
'_rc' => '401',
'_headers' => bless( {
'connection' => 'close',
'cache-control' => 'no-cache, must-revalidate, max-age=0',
'date' => 'Tue, 13 Nov 2018 18:37:19 GMT',
'client-ssl-cert-issuer' => '/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA',
'client-ssl-cipher' => 'ECDHE-RSA-AES256-GCM-SHA384',
'client-peer' => '192.185.236.193:443',
'access-control-expose-headers' => 'X-WP-Total, X-WP-TotalPages',
'x-robots-tag' => 'noindex',
'client-warning' => 'Missing Authenticate header',
'client-date' => 'Tue, 13 Nov 2018 18:37:22 GMT',
'client-ssl-warning' => 'Peer certificate not verified',
'content-type' => 'application/json; charset=UTF-8',
'client-transfer-encoding' => [
'chunked'
],
'server' => 'Apache',
'x-endurance-cache-level' => '2',
'client-ssl-socket-class' => 'IO::Socket::SSL',
'link' => '<https://hoppingmadmonkey.com/index.php/wp-json/>; rel="https://api.w.org/"',
'access-control-allow-headers' => 'Authorization, Content-Type',
'client-response-num' => 1,
'x-content-type-options' => 'nosniff',
'client-ssl-cert-subject' => '/OU=Domain Control Validated/OU=Hosted by HostGator.com, LLC./OU=PositiveSSL Wildcard/CN=*.hostgator.com',
'expires' => 'Wed, 11 Jan 1984 05:00:00 GMT'
}, 'HTTP::Headers' ),
'_msg' => 'Unauthorized',
'_request' => bless( {
'_content' => '',
'_uri' => bless( do{\(my $o = 'https://hoppingmadmonkey.com/wp-json/myapiplugin/v2/greeting?oauth_consumer_key=NCo8bflKU9LI&oauth_nonce=JrGdlVLXpB4&oauth_realm=https%3A%2F%2Fhoppingmadmonkey.com&oauth_signature=2pJRR1fz0uUdUWHlUjHFWlXFbL4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1542134239&oauth_token=2GeFG7MkXliq2OBOSSCSRBPX&oauth_version=1.0')}, 'URI::https' ),
'_headers' => bless( {
'user-agent' => 'libwww-perl/5.833',
'authorization' => 'Basic user:pass'
}, 'HTTP::Headers' ),
'_method' => 'GET',
'_uri_canonical' => bless( do{\(my $o = 'https://hoppingmadmonkey.com/wp-json/myapiplugin/v2/greeting?oauth_consumer_key=NCo8bflKU9LI&oauth_nonce=JrGdlVLXpB4&oauth_realm=https%3A%2F%2Fhoppingmadmonkey.com&oauth_signature=2pJRR1fz0uUdUWHlUjHFWlXFbL4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1542134239&oauth_token=2GeFG7MkXliq2OBOSSCSRBPX&oauth_version=1.0')}, 'URI::https' )
}, 'HTTP::Request' )
}, 'HTTP::Response' );
$VAR2 = '
';
In the interests of expedience, I've included my real secrets and website. It's all test at the moment. Feel free to try a solution if you have that kind of time on your hands. I can always invalidate the tokens if/when they get abused and will obviously change once/if I can understand the problem.
The obvious thought is that I am not generating the signature correctly (Big Hint:
{"code":"json_oauth1_signature_mismatch","message":"OAuth signature does not match","data":{"status":401}}',
)
I think I've ready everything on the entire Internet to no avail. Thanks in advance for any thoughts. And if you are near Atlanta, GA and help me out, the beer's on me.
Cheers.
Try using Net::OAuth
If you really need to fix your implementation then try removing all uri_escape and testing with data that doesn't require any escaping.
It looks like you have some unnecessary or double escaping. Start with build_base_string function.
I thinks that = sign should be unescaped.
I could not get things working with Net::OAuth so I tried writing my code again from scratch and explicitly following the guidelines at http://lti.tools/oauth/ until my code output matched theirs. Hallelujah! It's now working.
One thing I had to add, and Postman fails to do this as well, is to url encode the signature. Makes sense, of course, but odd that Postman misses it and sends an occasional unescaped '+'.

How do i add a lead (email, name) against a list in Marketo via API

Marketo API is so confusing for a new user like myself. I have an email and name and would love to pass that to marketo. How do I do that?
To push a lead record to Marketo via the REST API, there are a couple of endpoints you can choose from:
Sync Leads at POST /rest/v1/leads.json
Push Lead at POST /rest/v1/leads/push.json
Import Leads at POST /bulk/v1/leads.json
Out of these three, the Sync Leads might be the easiest to use, as that requires the least amout of additional parameters.
Basically, you have to make a POST request to the
https://<MUNCHKIN_ID>.mktorest.com/rest/v1/leads.json?access_token=<ACCESS_TOKEN> url with your data sent in the body of the request.
You will find your MUNCHKIN_ID under Admin > Integration > Munchkin tab in your instance. While still in the admin area, you should also create an API user (or allow API access for your own user), set up a LaunchPoint service with that user for the REST API and finally request an –temporary, valid for 1 hour– access token to test the connection. The whole process is described in detail under the Authentication chapter of the REST API documentation.
Once you have a –still valid– access token, you can make the call above with your lead information provided in the following data structure:
{
"action":"createOrUpdate",
"lookupField":"email",
"input":[
{
"email":"collizo#4sky.com",
"firstName":"Collizo4sky"
},
// …more leads (up to 300) if needed
]
}
In case you use php, here is an example code:
$munchkinId = '123-ABC-456';
$accessToken = 'abcdefgh-1234-5678-abcd-12345678abcd:lon';
$url = "https://{$munchkinId}.mktorest.com/rest/v1/leads.json?access_token={$accessToken}";
$dataJSON = [
'action' => 'createOrUpdate',
'lookupField' => 'email',
'input' => [
[
'email' => 'collizo#4sky.com',
'firstName' => 'Collizo4sky',
],
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataJSON));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
/**
* Which should result in a response like this:
* /
{
"requestId":"4033#16612d185ad",
"result":[
{
"id":1042016,
"status":"created"
}
],
"success":true
}
/**/

How to send batch request in measurement protocol

I'm using measurement protocol for my desktop application.
With this following URL I able send single request to Google Analytics(GA).
https://www.google-analytics.com/collect?v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0
But I want to send multiple request to GA.
According to the documentation, with /batch we can send multiple requests.
I have tried this URL,
https://www.google-analytics.com/batch?
v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test1&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0
&v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test2&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0
&v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test3&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0
But in report only 3rd event getting recorded.
Please help me to fix this issue.
You should send the payload/data in the body as raw text and on separate lines. Also, make sure you make a POST request. That worked for me. Here is an image showing how this looks in Postman:
From Postman you can then generate the code for the language you use. E.g for PHP Curl it looks like this.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google-analytics.com/batch",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test1&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test2&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test3&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: text/html",
"postman-token: de143f21-c12e-d268-32a0-9e5101541a07"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Useful post from #Søren about Postman, which I've never used before. Unfortunately, it still took me some time to figure out why my call to https://www.google-analytics.com/batch wasn't working in Javascript, citing a CORS 403 error as the issue. In Postman it was working fine, but the JS output from Postman wasn't.
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.google-analytics.com/batch",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "bec425da-11af-ec17-f702-fd7d01133ee4"
},
"data": "v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test1&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test2&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test3&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
So using Fiddler and comparing the call Postman makes, the only real difference I could see in Raw view was Postman was using POST https://www.google-analytics.com/batch where as JS was using OPTIONS https://www.google-analytics.com/batch. By executing the raw script and changing it from OPTIONS to POST it worked fine. So why wasn't mine sending as POST? I then read something about the headers need to match otherwise it won't be executed as POST. So the solution? Remove the headers...
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.google-analytics.com/batch",
"method": "POST",
"data": "v=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test1&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test2&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0\r\nv=1&tid=UA-XXXXXX-1&cid=754654B98786B&t=event&ec=Test3&ea=click&cd=XYZ&an=XYZ&aid=123&av=3.0&aiid=1.0"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
It took me a considerable amount if time to get this to work, for something so simple, and hope this will help someone else out.

cURL / wp_remote_post: won't work in wordpress plugin

I'm working on a wordpress plugin, which pull data from another site via a cURL post call. I've tested the same code in i wordpress plugin and outsite of wordpress.
Outsite of wordpress the script works fine, but inside a wordpress plugin, the script just wont work:
Wordpress plugin:
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_POST, true );
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($handle, CURLOPT_POSTFIELDS, array('postfield' => 'postfieldcontent'));
$result = curl_exec($handle);
Main site:
mysql_query("INSERT INTO table (q, w, e, r, t, y, u) VALUES ('', '".$_POST[postfield]."', '', '', '', '', '')");
I've removed all database security for debugging purpose. I have also tried the wp_remote_post function, that doesn't work either. I've even triede the the wp_remote_get function, but i can access the get variable:
$result = wp_remote_get( 'http://qwerty.dk/folder/filename.php?getfield=qwertrert' );
I've given up - please help :)
Best regards
Kim
You will need to enable cURL in your php.ini file. See #1347146
wp_remote_post() uses a class called WP_Http that in turn can use one of three transport classes (see file class-http.php function _get_first_available_transport).
POST method will work with class WP_Http_Curl, but will not work with class WP_Http_Streams (the cURL fallback).
The alternative is to use wp_remote_get()

Resources