I have a piece of code that trying to call Cloudstack REST API :
function file_get_header($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
$datas = curl_exec($ch);
curl_close($ch);
return $datas;
}
$url = "http://10.151.32.51:8080/client/api?" . $command . "&" . $signature . "&" . $response;
echo $test = file_get_header($url);
And the output is like this :
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT
What I am trying to do is how to print JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1 only and assign it into variable? Thankss,
Here's a method that will parse all your headers into a nice associative array, so you can get any header value by requesting $dictionary['header-name']
$url = 'http://www.google.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$datas = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($datas, 0, $header_size);
curl_close($ch);
echo ($header);
$arr = explode("\r\n", $header);
$dictionary = array();
foreach ($arr as $a) {
echo "$a\n\n";
$key_value = explode(":", $a, 2);
if (count($key_value) == 2) {
list($key, $value) = $key_value;
$dictionary[$key] = $value;
}
}
//uncomment the following line to see $dictionary is an associative-array of Header keys to Header values
//var_dump($dictionary);
Simple, just match the part of the string you want with preg_match:
<?php
$text = "HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=74A5104C625549EB4F1E8690C9FC8FC1; Path=/client Content-Type: text/javascript;charset=UTF-8 Content-Length: 323 Date: Sun, 01 Jun 2014 20:08:36 GMT";
preg_match("/JSESSIONID=\\w{32}/u", $text, $match);
echo $result = implode($match);
?>
Related
I'm not able to Create an Image Share, can you put some example code please or check my code.
I've already tried "Create a Text Share", "Create an Article or URL Share" on this link : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin (it work's)
I need to show if my code is good
I have create register_image() which work's well
Now I want to upload_image
public function upload_image($src_path, $image_request) {
if(!file_exists($src_path)) return -1;
$ch = curl_init();
if ($ch === false) {
throw new Exception('failed to initialize');
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $image_request['value']['uploadMechanism']['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest']['uploadUrl'] . "&oauth2_access_token=" . $this->_access_token);
$postData = array(
'upload-file' => $src_path,
);
$str = http_build_query($postData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
if ($response === false)
$response = curl_error($ch);
return $this->share_v3($image_request);
}
I get this error :
string(493) "HTTP/1.1 400 Bad Request Server: Play Set-Cookie: lang=v=2&lang=en-us; Path=/; Domain=api.linkedin.com Date: Fri, 10 May 2019 14:44:21 GMT Content-Length: 0 X-Li-Fabric: prod-lva1 Connection: keep-alive X-Li-Pop: prod-tln1 X-LI-Proto: http/1.1 X-LI-UUID: K6iDroJZnRXA+wxRVysAAA== Set-Cookie: lidc="b=VB41:g=2116:u=177:i=1557499460:t=1557553413:s=AQGsGR5wiWjwizsvGJEYdFeoQj-7IVF1" X-LI-Route-Key: "b=VB41:g=2116:u=177:i=1557499460:t=1557553413:s=AQGsGR5wiWjwizsvGJEYdFeoQj-7IVF1" "
I'm trying to get server redirect url. I have tried
function http_head_curl($url,$timeout=10)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); // in seconds
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
if ($res === false) {
throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
}
return trim($res);
}
echo http_head_curl("http://www.site.com",$timeout=10);
Result is;
HTTP/1.1 301 Moved Permanently Date: Sun, 12 May 2013 23:34:22 GMT
Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.23
Set-Cookie: PHPSESSID=0d4b28dd02bd3d8413c92f71253e8b31; path=/;
HttpOnly X-Pingback: http://site.com/xmlrpc.php Content-Type:
text/html; charset=UTF-8 Location: http://site.com/ HTTP/1.1 200 OK
Date: Sun, 12 May 2013 23:34:23 GMT Server: LiteSpeed Connection:
close X-Powered-By: PHP/5.3.23 Set-Cookie:
PHPSESSID=630ed27f107c07d25ee6dbfcb02e8dec; path=/; HttpOnly
X-Pingback: http://site.com/xmlrpc.php Content-Type: text/html;
charset=UTF-8
It shows almost all header information, but not showing where it redirects. How do I get the redirected page url ?
It's the Location header.
$headers = array();
$lines = explode("\n", http_head_curl('http://www.site.com', $timeout = 10));
list($protocol, $statusCode, $statusMsg) = explode(' ', array_shift($lines), 3);
foreach($lines as $line){
$line = explode(':', $line, 2);
$headers[trim($line[0])] = isset($line[1]) ? trim($line[1]) : '';
}
// 3xx = redirect
if(floor($statusCode / 100) === 3)
print $headers['Location'];
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$response_header = substr($response, 0, $info['header_size']);
$response_header = parseHeaders($response_header, 'Status');
$content = substr(response, $info['header_size']);
$url_redirect = (isset($response_header['Location'])) ? $response_header['Location'] : null;
var_dump($url_redirect);
/*
* or you can use http://php.net/http-parse-headers,
* but then need to install http://php.net/manual/en/book.http.php
*/
function parseHeaders($headers, $request_line)
{
$results = array();
$lines = array_filter(explode("\r\n", $headers));
foreach ($lines as $line) {
$name_value = explode(':', $line, 2);
if (isset($name_value[1])) {
$name = $name_value[0];
$value = $name_value[1];
} else {
$name = $request_line;
$value = $name_value[0];
}
$results[$name] = trim($value);
}
return $results;
}
After your CURL request is done, use curl_getinfo with the CURLINFO_EFFECTIVE_URL option. Done.
Compared to the other (complicated) answers, this will provide you the full URL that your request "ended up on".
In PHP what would the regex be to extract "taken" from below, considering that it is dynamic and is always after status:
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}
The following shows that I should be using json decoded. How would one achieve this?
The above in generated using:
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
Remove the header from the response by changing:
curl_setopt($process, CURLOPT_HEADER, false);
And then decode the JSON string with:
$data = json_decode($curlResponse, true);
If you discard headers from the response, you can use:
$json = '{"service":"availability","domain":"","timestamp":1360451229,
"content":{"domainList":[{"status":"taken","name":""}]}}';
$data = json_decode($json, TRUE);
echo $data['content']['domainList'][0]['status'];
Why care about the header? That's a JSON string, just decode it and you'll have an object that you can access easily
in php:
$jsonobj = json_decode('{"service":"availability","domain":"","timestamp":1360451229, "content":{"domainList":[{"status":"taken","name":""}]}}');
in javascript:
var jsonobj = JSON.parse('{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}');
$string = '
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}';
$parts = explode("\n", $string);
$json = end($parts);
$data = json_decode($json);
$status = $data->content->domainList[0]->status; die;
echo $status;
Edit (based on the question update):
Remove the CURLOPT_HEADER line from your cURL request. This would simplify the response and make it easier to parse.
If you need to work with headers, you have two options;
// first: regex
preg_match('~"status":"(.*?)"~i', $return, $match);
// print_r($match);
echo $match[1]; // taken
// second: json encode
$response = explode("\r\n\r\n", $return, 3);
// print_r($response);
$json_object = json_decode($response[2]);
$json_array = json_decode($response[2], true); // toArray
// echo $json_object->content->domainList[0]->status;
echo $json_array['content']['domainList'][0]['status'];
I have a php script that returns just plain text without any html. Now I want to make a cURL request to that script and I get the following response:
HTTP/1.1 200 OK
Date: Mon, 28 Feb 2011 14:21:51 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.2.12-nmm2
Vary: Accept-Encoding
Content-Length: 6
Content-Type: text/html
6.8320
The actuall response is just 6.8320 as text without any html. I want to retrieve it from the response above by just removing the header information.
I already minified the script a bit:
$url = $_GET['url'];
if ( !$url ) {
// Passed url not specified.
$contents = 'ERROR: url not specified';
$status = array( 'http_code' => 'ERROR' );
} else if ( !preg_match( $valid_url_regex, $url ) ) {
// Passed url doesn't match $valid_url_regex.
$contents = 'ERROR: invalid url';
$status = array( 'http_code' => 'ERROR' );
} else {
$ch = curl_init( $url );
if ( strtolower($_SERVER['REQUEST_METHOD']) == 'post' ) {
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $_POST );
}
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT'] );
list( $header, $contents ) = preg_split( '/([\r\n][\r\n])\\1/', curl_exec( $ch ), 2 );
$status = curl_getinfo( $ch );
curl_close( $ch );
}
// Split header text into an array.
$header_text = preg_split( '/[\r\n]+/', $header );
if ( true ) {
if ( !$enable_native ) {
$contents = 'ERROR: invalid mode';
$status = array( 'http_code' => 'ERROR' );
}
// Propagate headers to response.
foreach ( $header_text as $header ) {
if ( preg_match( '/^(?:Content-Type|Content-Language|Set-Cookie):/i', $header ) ) {
header( $header );
}
}
print $contents;
}
Any idea what I need to change to remove the header information from the response?
Just set CURLOPT_HEADER to false.
Make sure you put set the header flag:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true );
curl_setopt($ch, CURLOPT_TIMEOUT, Constants::HTTP_TIMEOUT);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, Constants::HTTP_TIMEOUT);
$response = curl_exec($ch);
Do this after your curl call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headerstring = substr($response, 0, $header_size);
$body = substr($response, $header_size);
EDIT:
If you'd like to have header in assoc array, add something like this:
$headerArr = explode(PHP_EOL, $headerstring);
foreach ($headerArr as $headerRow) {
preg_match('/([a-zA-Z\-]+):\s(.+)$/',$headerRow, $matches);
if (!isset($matches[0])) {
continue;
}
$header[$matches[1]] = $matches[2];
}
Result print_r($header):
(
[content-type] => application/json
[content-length] => 2848
[date] => Tue, 06 Oct 2020 10:29:33 GMT
[last-modified] => Tue, 06 Oct 2020 10:17:17 GMT
)
Don't forget to close connection curl_close($ch);
Update the value of CURLOPT_HEADER to 0 for false
curl_setopt($ch, CURLOPT_HEADER, 0);
Just for a later use if anyone else needs. I was into same situation, but just need to remove header text, not content. The response i was getting in the header was (including white space):
HTTP/1.1 200 OK
Cache-Control: private, no-cache, no-store, must-revalidate
Content-Language: en
Content-Type: text/html
Date: Tue, 25 Feb 2014 20:59:29 GMT
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Pragma: no-cache
Server: nginx
Vary: Cookie, Accept-Language, Accept-Encoding
transfer-encoding: chunked
Connection: keep-alive
I wanted to remove starting from HTTP till keep-alive with white space:
$contents = preg_replace('/HTTP(.*)alive/s',"",$contents);
that did for me.
If you are using nuSoap, you can access data without headers with $nsoap->responseData or $nsoap->response, if you want the full headers.
Just in case someone needs that.
If for some reason you have to curl_setopt($ch, CURLOPT_HEADER, 1); to get cookies for example, the following worked for me. Not sure if it's 100% reliable but worth a try
$foo = preg_replace('/HTTP(.*)html/s',"",$curlresult);
$content = null;
$ch = curl_init();
$rs = curl_exec($ch);
if (CURLE_OK == curl_errno($ch)) {
$content = substr($rs, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
}
curl_close($ch);
echo $content;
If someone already saved the curl response to a file (like me) and therefore don't know how big the header was to use substr, try:
$file = '/path/to/file/with/headers';
file_put_contents($file, preg_replace('~.*\r\n\r\n~s', '', file_get_contents($file)));
Just do not set the curl_header in the curl request or set it to z or false
like this
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
Just don't set CURLOPT_HEADER!
<?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";