How to paste data to pastebin using the api in php? - php

<?php
/* gets the data from a URL */
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$paste_data=""; if(isset($_POST["paste_code"])) { $paste_data = $_POST["paste_code"]; }
echo $paste_data;
$returned_content = get_data('http://pastebin.com/api_public.php/paste_code(paste_data)');
echo $returned_content;
?>
This is my php code . where $paste_data contains the data to be pasted in a new page . How do I paste it using the function paste_code(String) ?

The documentation says that you need to submit a POST request to
http://pastebin.com/api_public.php
and the only mandatory parameter is paste_code, of type string is the paste that you want to make.
On success a new pastebin URL will be returned.
Bare bone example:
$ch = curl_init("http://pastebin.com/api_public.php");
curl_setopt ($ch, CURLOPT_POST, true);
// A new paste with the string "hello there SO"
curl_setopt ($ch, CURLOPT_POSTFIELDS, "paste_code=hello there SO");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
$response = curl_exec($ch);
echo $response;
and on running I get:
> POST http://pastebin.com/api_public.php HTTP/1.1
Host: pastebin.com
Accept: */*
Proxy-Connection: Keep-Alive
Content-Length: 25
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Date: Mon, 13 Dec 2010 07:51:12 GMT
< Content-Type: text/plain
< Server: nginx/0.8.52
< Vary: Accept-Encoding
< X-Powered-By: PHP/5.3.4-dev
< Via: 1.1 apac-nc06 (NetCache NetApp/6.0.6)
<
http://pastebin.com/Lc7kAw8Z* Closing connection #0
Clearly the response has the URL http://pastebin.com/Lc7kAw8Z
Visit it and you'll see a new paste containing hello there SO

FYI for others looking at this "post 2013", the api_public.php POST has been discontinued.

For those who stumple upon this thread via seach, here is a code that works in 2013:
<?php
$data = 'Hello World!';
$apiKey = 'xxxxxxx'; // get it from pastebin.com
$postData = array(
'api_dev_key' => $apiKey, // your dev key
'api_option' => 'paste', // action to perform
'api_paste_code' => utf8_decode($data), // the paste text
'api_paste_private' => '1', // 0=public 1=unlisted 2=private
'api_paste_expire_date' => '1D', // paste expires in 1 day
);
$ch = curl_init('http://pastebin.com/api/api_post.php');
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($postData),
CURLOPT_RETURNTRANSFER => 1,
));
$re = curl_exec($ch);
curl_close($ch);
$pasteId = end(explode('/', $re));
echo "Created new paste.\r\n Link:\t{$re}\r\n Raw:\t" . sprintf('http://pastebin.com/raw.php?i=%s', $pasteId) . "\r\n";

Related

PHP - curl post view request body (parameters)

I get an error response for missing parameter when posting cURL POST method,
I'm adding an array of parameters to CURLOPT_POSTFIELDS the following way:
$service = "AutoInsuranceFormPostService";
$method = "autoInsurancePublisherFormPost";
$userAgent = "Mozilla%2F5.0+%28Linux%3B+Android+4.4.4%3B+Z752C+Build%2FKTU84P%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.135+Mobile+Safari%2F537.36";
$payload = $encodedPayLoad;
$parameters = array (
'service' => $service,
'method' => $method,
'UserAgent' => $userAgent,
'payload' => $payload
);
With:
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
Since the response is saying missing parameter "service", I figured I need to debug the request body.
I managed to get the headers with:
curl_getinfo($ch)
I also attempted to use:
curl_setopt($ch, CURLOPT_VERBOSE, true);
But unfortunately in both cases I only got the headers and not the body (the parameters values).
Full curl execution function:
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
return $result;
}
Verbos information:
Content-Length: 6659
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded; boundary=------------------------45b2d9f6776306b0
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Thu, 12 Jul 2018 16:32:52 GMT
< Server: Apache
< Cache-Control: public
< ORIGIN: S_CACHE
< Vary: User-Agent,Accept-Encoding
< Set-Cookie: _qs_origin=s-cache; path=/;
< Set-Cookie: _qs_deviceType=; path=/;
< Content-Length: 141
< Content-Type: application/json;charset=ISO-8859-1
<
This output is useless for me since I cannot see how the parameters were sent and those cannot fix their format.
The response I get is:
{"Status":"Fail","StatusCode":"400","ResponseMessage":"\"service\" parameter empty! || \"method\" parameter empty! ","SkipMatchingFlag":"No"}
I have been searching for a solution all day long, I've seen a ton of answers on "How to see the RESPONSE body", and "How to see the request HEADERS".
But none for "How to see the request body", so any help would be much appreciated,
Best regards.

Subscribe using Superfeedr PubSubHubbub generating error hub.topic not found

I want to integrate Superfeedr API using PubSubHubbub in PHP. I am following this and my code is:
<?php
require_once('Superfeedr.class.php')
$superfeedr = new Superfeedr('http://push-pub.appspot.com/feed',
'http://mycallback.tld/push?feed=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed',
'http://wallabee.superfeedr.com');
$superfeedr->verbose = true;
$superfeedr->subscribe();
?>
And my subscribe() function is
public function subscribe()
{
$this->request('subscribe');
}
private function request($mode)
{
$data = array();
$data['topic'] = $this->topic;
$data['callback'] = $this->callback;
$post_data = array (
"hub.mode" => 'subscribe',
"hub.verify" => "sync",
"hub.callback" => urlencode($this->callback),
"hub.topic" => urlencode($this->topic),
"hub.verify_token" => "26550615cbbed86df28847cec06d3769",
);
//echo "<pre>"; print_r($post_data); exit;
// url-ify the data for the POST
foreach ($post_data as $key=>$value) {
$post_data_string .= $key.'='. $value.'&';
}
rtrim($fields_string,'&');
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->hub);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
$output = curl_exec($ch);
if ($this->verbose) {
print('<pre>');
print_r($output);
print('</pre>');
}
}
But after execution I am getting this error
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: The force, Luke
Vary: X-HTTP-Method-Override, Accept-Encoding
Content-Type: text/plain; charset=utf-8
X-Superfeedr-Host: supernoder16.superfeedr.com
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Content-Length: 97
ETag: W/"61-db6269b5"
Date: Wed, 24 Aug 2016 14:01:47 GMT
Connection: close
Please provide a valid hub.topic (feed) URL that is accepted on this hub. The hub does not match.
Same data (topic and callback etc..) requesting from https://superfeedr.com/users/testdata/push_console
is working fine. But I don't know why I am getting this error on my local. If anyone has any experienced with same problom then please help me. Thanks.
You are using a strange hub URL. You should use HTTPS://push.superfeedr.com in the last param of your class constructor.

PHP curl() get all header at one time

<?php
$url = 'http://fb.com';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
));
$header = explode("\n", curl_exec($curl));
curl_close($curl);
print_r($header);
Result
HTTP/1.1 301 Moved Permanently
Location: http://www.facebook.com/?_rdr
Vary: Accept-Encoding
Content-Type: text/html
X-FB-Debug: rVg0o+qDt9z/zJu7jTW1gi1WSRC8YIMu3e6XnPagx39zZ4pbV0k2yrNfZmkdTLZyfzg713X+M0Lr2jS2P018xA==
Date: Thu, 25 Feb 2016 08:48:08 GMT
Connection: keep-alive
Content-Length: 0
But I want to get all Location at one time
I enter > http://fb.com
then 301 redirect: http://www.facebook.com/?_rdr
then 302 redirect: https://www.facebook.com/
I want to get All this link at one time with status 301 302
or any better idea to get redirect location url . THANKS
You can get all headers from every request made until no Location header is sent using this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$headers = curl_exec($ch);
curl_close($ch);
But then, you'll have to extract the information yourself because $headers is only a string, not an array.
If you only need the last location, simply do curl_getinfo($ch,CURLINFO_EFFECTIVE_URL).
Use curl_getinfo() to check if you got a 301 or 302 response and then repeat the same code again as long as that's the case. So, put your code in a function like:
$headers = array();
function getHeaders($url) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
));
$header = explode("\n", curl_exec($curl));
if (in_array(curl_getinfo($curl, CURLINFO_HTTP_CODE), array(301, 302))) {
// Got a 301 or 302, store this stuff and do it again
$headers[] = $header;
curl_close($curl);
return getHeaders($url);
}
$headers[] = $header;
curl_close($curl);
}
Then $headers will hold all the headers encountered up until the first non-301/302 response.

curl fails to correctly send headers

My initial project was of checking whether a certain Apple ID exists or not, I have proceeded doing this in php by navigating to apppleid.apple.com/account/ and pretending to register an account with all the fields blank except the account field, and if I got an error it meant the account existed, otherwise If I got other errors but not an "account exists" error I would return false. However I have encountered a few problems on the way. The first was that you need to preserve all the headers/cookies on the way (which I did) but it still does not work, and apparently always answers with "1". The code can be found here : PASTEBIN. Please follow the link and try to solve this problem, I really need this done. Thank you very much whoever got some time to read this post.
EDIT
code:
<?php
require("simplehtmldom_1_5/simple_html_dom.php");
$input = get_data('https://appleid.apple.com/account');
$html = new simple_html_dom();
$html->load($input);
//echo $input;
$table = array();
foreach($html->find('input') as $inn)
{
$val = "";
try
{
$val = $inn->getAttribute('value');
}
catch (Exception $e)
{
$val = "";
}
//echo $inn->getAttribute('name') . $val . "\n";
if($inn->getAttribute('name') != "" && $inn->getAttribute('name') != "account.name")
{
$table[$inn->getAttribute("name")] = $val;
}
if($inn->getAttribute('name') == "account.name")
{
$table[$inn->getAttribute("name")] = "naclo3samuel#gmail.com";
}
}
$NIX = http_build_query($table);
//set the url, number of POST vars, POST data
$ch = curl_init();
$hs = get_headers("https://appleid.apple.com/account", 0);
$headers = $hs;
curl_setopt($ch,CURLOPT_URL, "https://appleid.apple.com/account/");
curl_setopt($ch,CURLOPT_POST, count($NIX));
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch,CURLOPT_POSTFIELDS, $NIX);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
/* gets the data from a URL */
function get_data($url) {
$ch = curl_init();
$timeout = 5000;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>
One of the problems is right here: get_headers("https://appleid.apple.com/account", 0);
This will return something like:
[0] => HTTP/1.1 200 OK
[1] => Date: Sat, 29 May 2004 12:28:13 GMT
[2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
[3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
[4] => ETag: "3f80f-1b6-3e1cb03b"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 438
[7] => Connection: close
[8] => Content-Type: text/html
What is cURL supposed to do with that? This is not in a format acceptable by CURLOPT_HTTPHEADER and neither headers a Server would expect from a Client request.
I suppose you are trying to stablish Cookie session. I recommend you do all that without use of get_headers() or putting your finger in the headers at all.
Enable cURL's Cookie support by setting the options CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE, make a call to https://appleid.apple.com/account to initialize your Cookies, and then do the rest.
Example:
$cookies = tmpfile();
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://appleid.apple.com/account/",
CURLOPT_COOKIEJAR => $cookies,
CURLOPT_COOKIEFILE => $cookies,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true
]);
curl_exec();
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $NIX
]);
$result = curl_exec($ch);
$hsize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = explode("\r\n", substr($result, 0, $hsize));
$result = substr($result, $hsize);

How to perform a PUT operation using CURL in PHP?

I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);

Categories