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".
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 am exporting some invoices in json in my XmlController.php and converting them in xml in my xml_export.php
In my XmlController.php:
private function exportBills() {
$bill_ids = $this->_getParam('bill_ids');
$bill_model = new Model_Bills();
$bills = $bill_model->findByIds($bill_ids);
$data = array('bills' => array());
$extract = array();
foreach($bills as $bill) {
$data['bills'][] = $bill->getJsonView();
$extract[$bill->bill_reference_number] = $bill;
}
try {
$response = $this->post('xml_export.php', $data);
$this->getResponse()->setHttpResponseCode(200);
return;
} catch (Exception $e) {
$this->view->error = 'Unknown Error';
$this->view->description = $e->getMessage();
$this->getResponse()->setHttpResponseCode(500);
return;
}
}
private function post($url, $data) {
$data = json_encode($data);
$headers = array_merge(
array(
'Accept: application/xml',
'Content-Length: ' . strlen($data),
'Origin: ' . get_base_url()));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$xml = curl_exec($curl);
curl_close($curl);
if(false === $xml) {
throw new Exception('cURL failed! URL was: ' . $url);
}
}
And in my xml_export.php:
require_once('../library/functions.php');
$json = file_get_contents('php://input');
$date = date('Y-m-d H:i:s');
try{
$input = json_decode($json, true);
$response = array();
$xml_string = null;
$xml_concat = null;
if(implode('', array_keys($input)) === 'invoices') {
foreach ($input['invoices'] as $invoice) {
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($invoice, $xml_data);
$xml = $xml_data->asXML();
$xml = preg_replace('~<(\d)~', '<number$1', $xml);
$xml = preg_replace('~<\/(\d)~', '</number$1', $xml);
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml);
$xml_string = $domxml->saveXML();
$xml_concat .= $xml_string;
}
}elseif(implode('', array_keys($input)) === 'bills') {
foreach ($input['bills'] as $bill) {
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($bill, $xml_data);
$xml = $xml_data->asXML();
$xml = preg_replace('~<(\d)~', '<number$1', $xml);
$xml = preg_replace('~<\/(\d)~', '</number$1', $xml);
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml);
$xml_string = $domxml->saveXML();
$xml_concat .= $xml_string;
}
}
file_put_contents('/tmp/report.xml', print_r(htmlspecialchars($xml_concat), true));
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="report.xml"');
echo $xml_concat;
readfile('/tmp/report.xml');
exit;
}catch(OAuthException $e){
die('Unable to export. Please contact support for assistance');
}
My $xml_concat definitely has output and my /tmp/report.xml also exists and has output but the download was not triggered.
Below is my reponse header:
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre- check=0
Content-Type: application/json
Date: Sat, 26 Mar 2016 14:47:22 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: nginx
Vary: Accept
X-Powered-By: PHP/5.6.16-1+deb.sury.org~trusty+1
Content-Length: 0
Connection: keep-alive
and my request header:
POST /v1/xml HTTP/1.1
Connection: keep-alive
Content-Length: 81
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36
Content-Type: application/json
Accept: application/json
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
I am not exactly sure why it is in application/json when I specified in application/xml in my controller and the headers did not pick up the content-disposition.
So far I manage to get HTTP response header from this
$ch = curl_init();<br/>
$url="http://localhost/PHP_Projects/Test/response.php";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$headers = get_headers_from_curl_response($response);
foreach($headers as $x => $x_value){<br/>
print $x.": ".$x_value;<br/>
}
function get_headers_from_curl_response($response)
{<br/>
$headers = array();
$header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
foreach (explode("\r\n", $header_text) as $i => $line)
if ($i === 0)
$headers['http_code'] = $line;
else
{
list ($key, $value) = explode(': ', $line);
$headers[$key] = $value;
}
return $headers;
}
The out put from this is like
HTTP/1.1 200 OK
Date: Thu, 07 May 2015 03:26:26 GMT
Server: Apache/2.4.12 (Win32) OpenSSL/1.0.1l PHP/5.6.8
X-Powered-By: PHP/5.6.8
Content-Length: 128
Content-Type: text/html; charset=UTF-8
but I want to add some more to this like
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Path=/application_uri
Freeflow: FC
charge: Y
amount: 100
Expires: -1
Pragma: no-cache
Cache-Control: max-age=0
Content-Type: UTF-8
Content-Length: 20
$headers = array( 'Path: application_uri',
'Freeflow: FC',
'charge: Y',
'amount: 100',
);
curl_setopt ($ch, CURLOPT_HTTPHEADER,$headers);
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);
?>
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!