I am using Jira's API to add an attachment file to a case. My issue is after my code attaches a file, and I go to the JIRA case to confirm, I see two things. First, if it is an image, I can see a thumbnail of the image. If I click it, though, I get an error saying "The requested content cannot be loaded. Please try again." Second, under the thumbnail, instead of showing the name of the file, it has the path that the file was originally uploaded from (id: c:/wamp/www/...." Is there a reason this is happening? Here is my code:
$ch = curl_init();
$header = array(
'Content-Type: multipart/form-data',
'X-Atlassian-Token: no-check'
);
$attachmentPath = $this->get_file_uploads();
//$attachmentPath comes out to be something like:
//c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG
$data = array('file'=>"#". $attachmentPath, 'filename'=>'DSC_0344_3.JPG');
$url= 'https://mysite.atlassian.net/rest/api/2/issue/20612/attachments/';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
Once the file gets added to Jira, when I log into jira, I can see the thumbnail but the title under the file is something like: c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG instead of the file name.
thanks
You need to use:
$data = array('file'=>"#". $attachmentPath . ';filename=DSC_0344_3.JPG');
It is an issue in PHP cURL <5.5.0 but > 5.2.10, see JIRA API attachment names contain the whole paths of the posted files
When using PHP >= 5.5.0 it is better to switch to the CURLFile approach as also documented in that link.
$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename('DSC_0344_3.JPG');
$data = array('file'=>$cfile);
For anybody in the future: here's a function i wrote that works on php 7
function attachFileToIssue($issueURL, $attachmentURL) {
// issueURL will be something like this: http://{yourdomainforjira}.com/rest/api/2/issue/{key}/attachments
// $attachmentURL will be real path to file (i.e. C:\hereswheremyfilelives\fileName.jpg) NOTE: Local paths ("./fileName.jpg") does not work!
$ch = curl_init();
$headers = array(
'X-Atlassian-Token: nocheck',
'Content-type: multipart/form-data'
);
$cfile = new CURLFile($attachmentURL);
$cfile->setPostFilename(basename($attachmentURL));
$data = array("file" => $cfile);
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $issueURL,
CURLOPT_VERBOSE => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => "{username}:{password}"
)
);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error)
echo "cURL Error: " . $ch_error;
curl_close($ch);
}
Related
I'm in the process of testing the new Bing Custom Search using below PHP code. The result is a blank white screen with no errors. Is it because this service is still in beta mode?
<?php
$sURL = "https://api.cognitive.microsoft.com/bingcustomsearch/v5.0/search?q=dogs&customconfig=[mycustomconfigvalue]&responseFilter=Webpages&mkt=en-us&safesearch=Moderate";
$key = "[myPrimaryKey]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
?>
When I try to verify if API keys are working for me using Postman, I get an error saying "Could n ot get any response".
However, if I try the same values in https://customsearch.ai under endpoint section, it works perfectly by displaying the response.
Can anyone please let me know I can't run the code using my own PHP code?
Thanks
3 Errors:
1 - CURLOPT_HEADER is different from CURLOPT_HTTPHEADER.
2 - CURLOPT_HTTPHEADER takes an array as argument, not a string.
3 - Variables ($key) only expand inside double quotes.
Try:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, 1); # you may want increase this value
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["ocp-apim-subscription-key:$key"]);
$content = curl_exec($ch);
I replied this somewhere. Here is a working php snippet. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG.
$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);
I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}
I'm using an API that wants me to send a POST with the binary data from a file as the body of the request. How can I accomplish this using PHP cURL?
The command line equivalent of what I'm trying to achieve is:
curl --request POST --data-binary "#myimage.jpg" https://myapiurl
You can just set your body in CURLOPT_POSTFIELDS.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Taken from here
Of course, set your own header type, and just do file_get_contents('/path/to/file') for body.
This can be done through CURLFile instance:
$uploadFilePath = __DIR__ . '/resource/file.txt';
if (!file_exists($uploadFilePath)) {
throw new Exception('File not found: ' . $uploadFilePath);
}
$uploadFileMimeType = mime_content_type($uploadFilePath);
$uploadFilePostKey = 'file';
$uploadFile = new CURLFile(
$uploadFilePath,
$uploadFileMimeType,
$uploadFilePostKey
);
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify array of form fields
*/
CURLOPT_POSTFIELDS => [
$uploadFilePostKey => $uploadFile,
],
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
See - https://github.com/andriichuk/php-curl-cookbook#upload-file
to set body to binary data and upload without multipart/form-data, the key is to cheat curl, first we tell him to PUT, then to POST:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);
credits: How to POST a large amount of data within PHP curl without memory overhead?
Try this:
$postfields = array(
'upload_file' => '#'.$tmpFile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url.'/instances');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);//require php 5.6^
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
if (curl_errno($ch)) {
print curl_error($ch);
}
curl_close($ch);
Below solution worked fine for me.
$ch = curl_init();
$post_url = "https://api_url/"
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$post = array(
'file' => '#' .realpath('PATH_TO_DOWNLOADED_ZIP_FILE')
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$headers[] = 'Authorization: Bearer YOUR_ACCESS_TOKEN';
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
refered: curl to php-curl
You need to provide appropriate header to send a POST with the binary data.
$header = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_POSTFIELDS, $arr_containing_file);
Your $arr_containing_file can for example contain file as expected (I mean, you need to provide appropriate expected field by the API service).
$arr_containing_file = array('datafile' => '#inputfile.ext');
I just want to use "file_get_html" to get content of specific pages, but this content just avaiable for loggin user, is there any way to send cookie to let target site know that the page is accessed by logged in user.
require_once 'simple_html_dom.php';
$opts = array("Cookie: __qca=P0-1170249003-1395413811270"); //__qca=P0-1170249003-1395413811270
$current_url = 'http://abc.xyz';
// But it will be redirect to
$url = 'http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz'
$context = stream_context_create($opts);
$html = file_get_html($url, FALSE, $context);
echo $html;
I do something like this, but it doesn't work.
How Can I do this with Curl?
Thanks.
$ch = curl_init(); // your curl instance
curl_setopt_array($ch, [CURLOPT_URL => "http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz", CURLOPT_COOKIE => "__qca=P0-1170249003-1395413811270"], CURLOPT_RETURNTRANSFER => true]);
$result = curl_exec($ch); // request's result
$html = new simple_html_dom(); // create new parser instance
$html->load($result); // load and parse previous result
In this example I used curl_setopt_array() to set the various CURL parameters instead of calling curl_setopt() for each one of them.
CURLOPT_URL sets the target URL, CURLOPT_COOKIE sets the cookies to send, if there are multiple cookies then they must be separated with a semicolon followed by a space, finally the CURLOPT_RETURNTRANSFER tells CURL to return the server's response as a string.
curl_exec() executes the request and returns its result.
Then we create an instance of simple_html_dom and load that previous result into it.
Thank you so much #andre, I spent all evening yesterday to find the solution :
The first we make curl exe to login to google account.
and save cookie to a text file (exam : "/tmp/cookie.txt")
and the next time everything we have to do is only take cookie content in this file to get remote content.
<?php
require_once 'simple_html_dom.php';
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "youracc#gmail.com",
"Passwd" => "yourpasswd",
"service" => "blogger",
"source" => "your application name"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
// Execute
$response = curl_exec($curl);
echo $response;
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth;
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$url = 'http://testlink.html';
$curl = curl_init();
// Make the request
curl_setopt($curl, CURLOPT_URL, $url );
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$html = new simple_html_dom(); // Create new parser instance
$html->load($response);
foreach($html->find('img') as $img) {
//echo $img->src . '</br>';
}
I'm working on Flight API of arzoo. The server must receive the posted data in simple POST Request. To achieve this i'm using PHP cURL. In the API Document it is clearly mention that the data should be sent in the following format:
<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>NYC</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<Preferredclass>E</Preferredclass>
<Eticket>true</Eticket>
<Clientid>77752369</Clientid>
<Clientpassword>*AB424E52FB5ASD23YN63A099A7B747A9BAF61F8E</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>
I've taken the above code in a variable $xml. My PHP cURL code is as follows:
$URL = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
if (curl_errno($ch))
{
// moving to display page to display curl errors
echo curl_errno($ch) ;
echo curl_error($ch);
}
else
{
//getting response from server
$response = curl_exec($ch);
print_r($response);
curl_close($ch);
}
I'm not getting anything in response. I've spoken about the same with the API Provider but they found empty request in their log. Am i missing something from my end. Your reply will be appreciated. Thank You.
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:
//Store your XML Request in a variable
$input_xml = '<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>JFK</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<PreferredClass>E</PreferredClass>
<Eticket>true</Eticket>
<Clientid>777ClientID</Clientid>
<Clientpassword>*Your API Password</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>';
Now I've made a little changes in the above curl_setopt declaration as follows:
$url = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
That's it the code works absolutely fine for me. I really appreciate #hakre & #Lucas For their wonderful support.
Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.
Check this one. It will work.
function fetch($i1,$i2,$i3,$i4)
{
$input_data = '<I>
<i1>'.$i1.'</i1>
<i2>'.$i2.'</i2>
<i3>'.$i2.'</i3>
<i4>'.$i3.'</i4>
</I>';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8080",
CURLOPT_URL => "http://192.168.1.100:8080/avaliablity",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $input_data,
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache",
"Content-Type: application/xml"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
fetch('i1','i2','i3','i4');
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you