I am trying to call a web service of a shipping company in my php code and get the result xml. I have this sample code and i want to know if there is an alternative using curl.
Code:
function doPost($_postContent) {
$postContent = "xml_in=".$_postContent;
$host="test.company.com";
$contentLen = strlen($postContent);
$httpHeader ="POST /shippergate2.asp HTTP/1.1\r\n"
."Host: $host\r\n"
."User-Agent: PHP Script\r\n"
."Content-Type: application/x-www-form-urlencoded\r\n"
."Content-Length: $contentLen\r\n"
."Connection: close\r\n"
."\r\n";
$httpHeader.=$postContent;
$fp = fsockopen($host, 81);
fputs($fp, $httpHeader);
$result = "";
while(!feof($fp)) {
// receive the results of the request
$result .= fgets($fp, 128);
}
// close the socket connection:
fclose($fp);
$result = explode("\r\n\r\n", $result,3);
}
Can i call it using curl?
You can use the CURLOPT_PORT option to change the port to 81. See http://php.net/manual/en/function.curl-setopt.php
$url = "http://test.company.com/shippergate2.asp";
$ch = curl_init();
curl_setopt($ch, CURLOPT_PORT, 81);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "PHP Script");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postContent);
$data = curl_exec($ch);
I guess a complete solution is needed but I suggest checking this basic CURL wrapper for PHP https://github.com/shuber/curl
Related
I have a PHP script to request JSON data with cURL, PHP and HTTPheader, before it worked but suddenly it is not working, and I got Gateway Timeout 504.
This PHP script run from Linux VPS Hosting, with specs:
OS Debian 11,
Apache/2.4.54 (Debian)
mod_fcgid/2.3.9
OpenSSL/1.1.1n
PHP Version 7.4.30.
curl 7.74.0
And this is my code:
<?php
$consid = "my_id";
$secretKey = "my_secretkey";
date_default_timezone_set('UTC');
$tStamp = strval(time()-strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $consid."&".$tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$ch = curl_init();
$headers = array(
'X-cons-id: '.$consid.'',
'X-timestamp: '.$tStamp.'',
'X-signature: '.$encodedSignature.'',
'Content-Type: Application/JSON',
'Accept: Application/JSON'
);
curl_setopt($ch, CURLOPT_URL, "https://domain.tld/aplicaresws/rest/bed/ref/kelas");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'DEFAULT#SECLEVEL=1');
$content = curl_exec($ch);
$err = curl_error($ch);
$data = json_decode($content,true);
foreach ($data["response"] as $record) {}
$data2 = array( 'data' => $record );
$data3 = json_encode($data2);
$fp = fopen("bedlist.json", "w");
fwrite($fp, $data3);
fclose($fp);
curl_close($ch);
?>
Please help review my script what's wrong with this curl PHP code?
I can view the headers of a request sent using php curl with the following:
curl_getinfo($ch, CURLINFO_HEADER_OUT);
I wish to see the body of what is being sent out as well but cannot for the life of me find any way to do so.
I was unable to find any such option after extensively searching the PHP cURL documentation.
My solution was to use the web proxy tool Charles
Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).
router.php
<?=file_get_contents('php://input');
Start embedded server
php -S 127.0.0.0:8080 ./router.php
Test cURL:
<?php
$ch = curl_init("http://127.0.0.1:8080/");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Expect: 100-Continue"
]);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$fields = ["bri" => 255];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)$fields));
$response = curl_exec($ch);
print curl_getinfo($ch, CURLINFO_HEADER_OUT);
print $response;
Setting CURLOPT_HEADER to true will return the headers with the body of the response, this can then be parsed out of the response and processed seperately. Something like the following should work to print both the in and out headers:
$url = "https://www.example.com";
$ch = curl_init();
// Configure cURL handle
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$x = curl_exec($ch);
print "\nHeaders:\n";
// Get the out headers, explode into an array, and remove any empty string entries
$outHeaders = explode("\n", curl_getinfo($ch, CURLINFO_HEADER_OUT));
$outHeaders = array_filter($outHeaders, function($value) { return $value !== '' && $value !== ' ' && strlen($value) != 1; });
print_r($outHeaders);
// Seperate in headers from body of response
list($inHeaders, $content) = explode("\r\n\r\n", $x, 2);
// Break in headers into array and print_r them
$inHeaders = explode("\n", $inHeaders);
print_r($inHeaders);
Try this function:
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
Using PHP cURL and Symfony 1.4.2
I'm trying to do a PUT request including data (JSON) to modify an object in my REST web services, but can't catch the data on the server side.
It seems that the content is attached successfully when checking at my logs:
PUT to http://localhost:8080/apiapp_test.php/v1/reports/498 with post body content=%7B%22report%22%3A%7B%22title%22%3A%22The+title+has+been+updated%22%7D%7D
I attached the data like this:
$curl_opts = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => http_build_query(array('content' => $post_data)),
);
And wanted to get the data using something like this
$payload = $request->getPostParameter('content');
It is not working and I've tried many ways to get this data in my actions file.
I've tried the following solutions:
parse_str(file_get_contents("php://input"), $post_vars);
$payload = $post_vars['content'];
// or
$data = $request->getContent(); // $request => sfWebRequest
$payload = $data['content'];
// or
$payload = $request->getPostParameter('content');
// then I'd like to do that
$json_array = json_decode($payload, true);
I just don't know how to get this data in my actions and it's frustrating, I've read many topics here about it but none is working for me.
Additional informations:
I have these setup for my cURL request:
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, $http_method);
if ($http_method === sfRequest::PUT) {
curl_setopt($curl_request, CURLOPT_PUT, true);
$content_length = array_key_exists(CURLOPT_POSTFIELDS, $curl_options) ? strlen($curl_options[CURLOPT_POSTFIELDS]) : 0;
$curl_options[CURLOPT_HTTPHEADER][] = 'Content-Length: ' . $content_length;
}
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_TIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_DNS_CACHE_TIMEOUT, 0);
curl_setopt($curl_request, CURLOPT_NOSIGNAL, true);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
In sfWebRequest.php, I've seen this:
case 'PUT':
$this->setMethod(self::PUT);
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $postParameters);
}
break;
So I tried to set the header's Content-Type to it but it doesn't do anything.
If you have any idea, please help!
According to an other question/answer, I've tested this solution and I got the correct result:
$body = 'the RAW data string I want to send';
/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
die('could not open temp memory data');
}
fwrite($fp, $body);
fseek($fp, 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));
$output = curl_exec($ch);
echo $output;
die();
And on the other side, you can retrieve the content using:
$content = $request->getContent();
If you var_dump it, you will retrieve:
the RAW data string I want to send
I want to create site map for my site. So before creating sitemap, i want to know the status code of each url. I have used curl option to deduct status code. I have more than 400 urls in my site. if i use curl, its taking long time.
Only i want to allow the url which is contain status code 200.
Could you please any one tell me any other option to deduct each url's status code.
I have used below curl code.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlparam);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_exec($ch);
$curlcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $curlcode;
reference link
I ran into this same issue a few months ago. I found that using this code example to access my own page status codes was much faster:
<?php
//
// Checking the status of a web page - funmin.com
//
$server="www.YOUR_WEBSITE.com";
function sockAccess($page)
{
$errno = "";
$errstr = "";
$fp = 0;
global $server;
$fp = fsockopen($server, 80, $errno, $errstr, 30);
if ($fp===0)
{
die("Error $errstr ($errno)");
}
$out = "GET /$page HTTP/1.1\r\n";
$out .= "Host: $server\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp,$out);
$content = fgets($fp);
$code = trim(substr($content,9,4));
fclose($fp);
return intval($code);
}
?>
Further documentation may be found here: http://www.forums.hscripts.com/viewtopic.php?f=11&t=4217
I have shoutcast administrator and i need to read xml from that it looks like this
http://SHOUTCAST-IP:PORT/admin.cgi
And i need to login and get the XML Data from http://SHOUTCAST-IP:PORT/admin.cgi?mode=viewxml and do it with php, i have made this script
$fp = fsockopen($server, $port, $errno, $errstr, 30);
fputs($fp, "GET /admin.cgi?pass=".$password."&mode=viewxml HTTP/1.0\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\r\n\r\n"); //
while (!feof($fp)) {
$content = fgets($fp);
}
But it doesn't work, it says Unauthorised. How can i fix it ?
Are you sure you can use standard $_GET variables to provide username and password there? Seems quite bad practice!?
I would use cURL to achieve this, it's quick and easy!
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://SHOUTCAST-IP:PORT/admin.cgi");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "user:pwd");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
$output = curl_exec($ch);
curl_close($ch);
What about this?
//*********** YOUR FM ***********//
// Begin Configuration
$scdef = "YOUR FM";
// ABOVE: Default station name to display when server or stream is down
$scip = "127.0.0.1"; // ip or url of shoutcast server (DO NOT ADD HTTP:// don't include the port)
$scport = "5977"; // port of shoutcast server
$scpass = "mysecretpassword"; // password to shoutcast server
// End Configuration
//*********** YOUR FM ***********//
$scfp = fsockopen("$scip", $scport, &$errno, &$errstr, 30);
if(!$scfp) {
$scsuccs=1;
echo''.$scdef.' is Offline';
}
if($scsuccs!=1){
fputs($scfp,"GET /admin.cgi?pass=$scpass&mode=viewxml HTTP/1.0\r\nUser-Agent: SHOUTcast Song Status (Mozilla Compatible)\r\n\r\n");
while(!feof($scfp)) {
$page .= fgets($scfp, 1000);
}
// REST OF YOUR CODE BELOW HERE!