How to attach files to Atlassian Confluence page using PHP - php

I'm working on attaching files via PHP to confluence (version 5.9.10)
Here is my code
$ch=curl_init();
$headers = array(
'X-Atlassian-Token: no-check'
);
$data = array('file' => '#test.txt');
curl_setopt_array(
$ch,
array(
CURLOPT_URL=>'https://<path_to_confluence>/rest/api/content/<page_id>/child/attachment',
CURLOPT_POST=>true,
CURLOPT_VERBOSE=>1,
CURLOPT_POSTFIELDS=>$data,
CURLOPT_SSL_VERIFYHOST=> 0,
CURLOPT_SSL_VERIFYPEER=> 0,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_HEADER=>false,
CURLOPT_HTTPHEADER=> $headers,
CURLOPT_USERPWD=>C_USERNAME.":".C_PASSWORD
)
);
$result=curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
var_dump($result);
}
curl_close($ch);
But after running script I've next error:
>
HTTP/1.1 500 Internal Server Error
Server: nginx/1.5.12
Date: Thu, 03 Nov 2016 10:12:44 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
X-ASEN: SEN-2160053
Set-Cookie: JSESSIONID=EE3116DFC552C7D4571608BFCF410559; Path=/; HttpOnly
X-Seraph-LoginReason: OK
X-AUSERNAME: user
Cache-Control: no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
X-Content-Type-Options: nosniff
HTTP error before end of send, stop sending
Closing connection 0
string(93) "statusCode":500,"message":"java.lang.IllegalArgumentException:File name must not be null"
What I'm doing wrong? What have I missed?

Try this:
$data = array('file' => '#' . realpath('test.txt'));
...
CURLOPT_POSTFIELDS=>$data
If the filename is required, you can try this instead:
$data = array('file' => '#' . realpath('test.txt') . ';filename=test.txt'));
...
CURLOPT_POSTFIELDS=>$data

I encountered this error when I was using the lib cURL and was doing it the old way, like:
CURLOPT_POSTFIELDS => [
'file' => '#/pathToFile'
]
But since it's deprecated from PHP 5.5, you need to use it the new way:
Imperative way:
CURLOPT_POSTFIELDS => [
'file' => curl_file_create($filePath)
]
Object way:
CURLOPT_POSTFIELDS => [
'file' => new CurlFile($filePath)
]

Related

How to get data from third party api with PHP cURL?

I want to fetch json data from one API but I am getting following error
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/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 27 Mar 2019 06:07:40 GMT
Content-Length: 36
{"Message":"An error has occurred."}
Its works with postman.Is there any syntax error while sending request?
This is my code
<?php
// Initiate curl
//$post = "NoofAdult=1&NoofChild=1&NoofInfant=1&FromAirportCode=AMD&ToAirportCode=BOM&DepartureDate=21/06/2019&ReturnDate&TripType=1&FlightClass=Y&SpecialFare=0&AirlineType=A";
$postData = array(
'NoofAdult' => '1',
'NoofChild' => '1',
'NoofInfant' => '1',
'FromAirportCode' => 'AMD',
'ToAirportCode' => 'BOM',
'DepartureDate' => '21/06/2019',
'ReturnDate' => '',
'TripType' => '1',
'FlightClass' => 'Y',
'SpecialFare' => '0',
'AirlineType' => 'A'
);
$header_data = array(
"Content-Type: application/json",
"Accept-Encoding: gzip, deflate",
"InterfaceCode:1",
"InterfaceAuthKey:1",
"AgentCode:",
"Password:"
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'http://stagingv2.flightmyweb.com/API/FlightAvailibility',
//CURLOPT_URL => 'http://localhost/akshay/sampleapi.php',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header_data,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch, $curlOpts);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: 0'));
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) {
die(curl_error($ch));
}
curl_close($ch);
echo '<pre>';
print_r($answer);
echo '</pre>';
// Will dump a beauty json :3
//var_dump(json_decode($result, true));
//echo json_encode($outp);
?>
I need json output:

Google safe browsing API doesn't work for me

I started using Google Console API and I want to try Google safe browsing to check if a website contain a malware or no but it doesn't working for me this is my code:
public function check(){
$url = 'http://www.facebokk.com';
$apiKey = 'AI6k8kgflsgjhajjfldsjqldskqO2Iq5Ou0PE';
$apiUrl = 'https://safebrowsing.googleapis.com/v4/threatMatches:find?key='.$apiKey;
$params = [
'client' => [
'clientId' => 'foobar',
'clientVersion' => '1.2.3'
],
'threatInfo' => [
"threatTypes" =>["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes" => ["WINDOWS"],
'threatEntryTypes' => ['URL'],
'threatEntries' => [
[ 'url' => $url ]
]
]
];
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_HTTPHEADER => [
'Content-Type: text/json'
]
]);
$res = curl_exec($ch);
print_r($res, true);
}
This is the result :
HTTP/1.1 200 OK Content-Type: application/json; charset=UTF-8 Date: Thu, 27 Sep 2018 15:13:54 GMT Server: ESF Cache-Control: private X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35" Accept-Ranges: none Vary: Accept-Encoding Transfer-Encoding: chunked {}

file_get_contents: get full response (PHP)

I'm using the following code to post information to a URL.
$query = http_build_query($myvars);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
"Content-Length: ".strlen($query)."\r\n".
"User-Agent:MyAgent/1.0\r\n",
'method' => "POST",
'content' => $query,
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Is it possible to show the complete header information of the response.
First I used curl, but this took to much cpu.
With curl I used the following option:
curl_setopt($ch, CURLOPT_HEADER, 1);
And I received the following header information:
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Mon, 21 Sep 2015 07:06:35 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.11
Content-Description: File Transfer
Content-Disposition: attachment; filename=File.txt
Content-Transfer-Encoding: binary
Content-Length: 333
Cache-Control: must-revalidate, post-check=0, pre-check=0
Expires: 0
Pragma: public
Vary: Accept-Encoding
Content-Type: text/plain
Is the with file_get_contents also possible?
file_get_contents("http://example.com");
var_dump($http_response_header);
http://php.net/manual/en/reserved.variables.httpresponseheader.php

php get location header after post request

I need to get the location header the following request:
This is what the request looks like from the chrome network dev tool when I execute it in chrome.
here is the redirect request in chrome network dev tool, just in case its needed for some reason.
I've tried the following things:
this seems to only give me an empty answer:
<?php
$url = $_GET["url"];
if (0 === preg_match('/form_build_id" value="form-([^"]*)"/', file_get_contents('http://anything2mp3.com/'), $matches)) exit("false");
$id = $matches[1];
$params = array('http' => array(
'method' => 'POST',
'content' => array(
'url' => $url,
'op' => "Convert",
'form_build_id' => "form-" . $id,
'form_id' => "videoconverter_convert_form"
),
'max_redirects' => "0",
'header' => "Content-Type:application/x-www-form-urlencoded"
));
stream_context_set_default($params);
$headers = get_headers("http://anything2mp3.com/?q=&mobile_detect_caching_notmobile&mobile_detect_caching_nottablet", false, $ctx);
echo implode("\n", $headers);
?>
i've also tried this:
<?php
$url = $_GET["url"];
if (0 === preg_match('/form_build_id" value="form-([^"]*)"/', file_get_contents('http://anything2mp3.com/'), $matches)) exit("false");
$id = $matches[1];
$params = array('http' => array(
'method' => 'POST',
'content' => array(
'url' => $url,
'op' => "Convert",
'form_build_id' => "form-" . $id,
'form_id' => "videoconverter_convert_form"
),
'max_redirects' => "0",
'header' => "Content-Type:application/x-www-form-urlencoded"
));
$ctx = stream_context_create($params);
$file = fopen("http://anything2mp3.com/?q=&mobile_detect_caching_notmobile&mobile_detect_caching_nottablet", 'rb', false, $ctx);
$headers = $http_response_header;
echo implode("\n", $headers);
?>
the last one gives me the following result:
HTTP/1.1 200 OK
Date: Sun, 26 Jul 2015 18:20:20 GMT
Content-Type: text/html; charset=utf-8
Connection: close
Set-Cookie: __cfduid=db7807d30a61600d31a18cc1a725150811437934820; expires=Mon, 25-Jul-16 18:20:20 GMT; path=/; domain=.anything2mp3.com; HttpOnly
Vary: Accept-Encoding
X-Cookie-Domain: .anything2mp3.com
Expires: Tue, 24 Jan 1984 08:00:00 GMT
Last-Modified: Sun, 26 Jul 2015 18:20:20 GMT
Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0
ETag: W/"1437934820"
Content-Language: en
X-Device: normal
X-GeoIP-Country-Code: US
X-GeoIP-Country-Name: United States
X-Speed-Cache-Key: /?q=&mobile_detect_caching_notmobile&mobile_detect_caching_nottablet
X-NoCache: Method
X-This-Proto: http
X-Server-Name: anything2mp3.com
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Server: cloudflare-nginx
CF-RAY: 20c21e3333eb23a8-IAD
as you can see, there is no location header.
note that I've seen some similar posts already (like question 6532753, I couldn't link it because I'm already at my 2 link limit), but they don't seem to work for me.
How do I retrieve the location header from request like marked in the original screenshot? What am I missing?
edit: I messed up pretty hard when copying my code, sorry for that
I eventually got it to work using curl like #frz3993 suggested (and after sending in a blank 'cookies' header, the server didn't seem to like it without that)
here is the code that I use now:
<?php
$url = $_GET["url"];
if (0 === preg_match('/form_build_id" value="form-([^"]*)"/', file_get_contents('http://anything2mp3.com/'), $matches)) exit("false");
$longid = $matches[1];
$ch = curl_init("http://anything2mp3.com/?q=&mobile_detect_caching_notmobile&mobile_detect_caching_nottablet");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
'url' => $url,
'op' => "Convert",
'form_build_id' => "form-" . $longid,
'form_id' => "videoconverter_convert_form"
)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:application/x-www-form-urlencoded",
"Cookie:"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$data = curl_exec($ch);
if (0 === preg_match('/Location: (.*id=(\d+))/', $data, $matches)) exit("false");
$redirect = $matches[1];
$id = $matches[2];
echo $redirect;
echo " - ";
echo $longid;
die();
?>
note that even tho the second suggestion from my OP gave me headers, it did not give me the location header which curl does now. (don't ask me why :p)

Command Line curl to PHP cURL issues (500 server error)

I am connecting to an API with multipart/form-data, if I send the request via curl on the command line I have no issues, but when sending it with PHP cURL I get an internal server 500 error.
The command line is
curl -H "Content-Type: multipart/form-data" -H "X-DevKey: XXX" -H "X-AccessToken: XXX" -F "data=#file.json; type=application/json" -X POST https://api.site.com/v1/Items -i -v
Which, give me the following response
> POST /v1/Items HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5
> Host: api.site.com
> Accept: */*
> X-DevKey: XXX
> X-AccessToken: XXX
> Content-Length: 1008
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=----------------------------58bf5d52327e
>
< HTTP/1.1 100 Continue
HTTP/1.1 100 Continue
< Set-Cookie: sto-id=XXX; Expires=Fri, 16-May-2025 15:32:27 GMT; Path=/
Set-Cookie: sto-id=XXX; Expires=Fri, 16-May-2025 15:32:27 GMT; Path=/
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Cache-Control: no-cache
Cache-Control: no-cache
< Pragma: no-cache
Pragma: no-cache
< Content-Type: application/json; charset=utf-8
Content-Type: application/json; charset=utf-8
< Expires: -1
Expires: -1
< X-Powered-By: ASP.NET
X-Powered-By: ASP.NET
< Date: Tue, 19 May 2015 15:32:28 GMT
Date: Tue, 19 May 2015 15:32:28 GMT
< Content-Length: 220
Content-Length: 220
< Set-Cookie: sto-id=XXX; Expires=Fri, 16-May-2025 15:32:28 GMT; Path=/
Set-Cookie: sto-id=XXX; Expires=Fri, 16-May-2025 15:32:28 GMT; Path=/
<
* Connection #0 to host api.site.com left intact
{"userMessage":"Item listed with itemID: 484495200","developerMessage":"Item listed with itemID: 484495200","links":[{"rel":"self","href":"https://api.site.com/v1/items/484495200","verb":"GET","title":"484495200"}]}* Closing connection #0
## Heading ##* SSLv3, TLS alert, Client hello (1):
My current PHP function looks like this
function create_listing($buynow, $startingBid, $category, $description, $picture, $sku, $title)
{
$url = "https://api.site.com/v1/Items";
$token = get_access_token();
$headers = array(
"X-DevKey: XXX",
"X-AccessToken: $token",
"Expect: 100-continue",
"Content-Type: multipart/form-data; Boundary=----WebKitFormBoundaryR7f7XrG1vJhOfHzu"
);
$data = array(
"AutoRelist" => 1,
"AutoRelistFixedCount" => 0,
"BuyNowPrice" => 9.99,
"CategoryID" => 2325,
"Condition" => 1,
"CountryCode" => 'US',
"Description" => $description,
"InspectionPeriod" => 1,
//"FixedPrice" => $fixedprice,
"IsFFLRequired" => true,
"ListingDuration" => 1,
"PaymentMethods" => array(
"Check" => false,
"VisaMastercard" => true,
"COD" => false,
"Escrow" => false,
"Amex" => false,
"PayPal" => false,
"Discover" => true,
"SeeItemDesc" => true,
"CertifiedCheck" => true,
"USPSMoneyOrder" => true,
"MoneyOrder" => false
),
"PostalCode" => '85388',
"Quantity" => 1,
//"ReservePrice" => $reserve,
"SalesTaxes" => array(
array(
"State" => 'AZ',
"TaxRate" => 8.5
)
),
//"SerialNumber" => $serial,
"ShippingClassCosts" => array(
"Ground" => 25.00,
"Priority" => 25.00
),
"ShippingClassesSupported" => array(
"Overnight" => false,
"TwoDay" => false,
"ThreeDay" => false,
"Ground" => true,
"FirstClass" => false,
"Priority" => true,
"Other" => false
),
//"ShippingProfileID" => $shippingProfile,
"SKU" => $sku,
"StartingBid" => 0.99,
"Title" => $title,
//"UPC" => $upc,
//"Weight" => $weight,
//"WeightUnit" => 1,
"WhoPaysForShipping" => 8,
//"ItemPremiumFeatures" => array(
//
//),
"WillShipInternational" => false
);
$boundary = '----WebKitFormBoundaryR7f7XrG1vJhOfHzu';
$request = "$boundary\nContent-Disposition: form-data; name=\"data\"\n";
$request .= json_encode($data) . "\n$boundary--";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
$verbose = fopen('php://temp', 'rw+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
$result = curl_exec($ch);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
htmlspecialchars(curl_error($ch)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
$info = curl_getinfo($ch);
if (!$result) {
echo curl_error($ch);
}
curl_close($ch);
return $result;
}
But I get the following response:
> POST /v1/Items HTTP/1.1
Host: api.site.com
Accept: */*
Cookie: sto-id=JKHHNMED
X-DevKey: XXX
X-AccessToken: XXX
Expect: 100-continue
Content-Type: multipart/form-data; Boundary=----WebKitFormBoundaryR7f7XrG1vJhOfHzu
Content-Length: 939
< HTTP/1.1 100 Continue
< HTTP/1.1 500 Internal Server Error
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json; charset=utf-8
< Expires: -1
< X-Powered-By: ASP.NET
< Date: Tue, 19 May 2015 17:11:40 GMT
< Content-Length: 219
* HTTP error before end of send, stop sending
Any help as to why I'm getting the 500 error would be greatly appreciated.

Categories