cURL Failed to connect to port 80 - php

I am using cURL in my PHP script to test my API. When i try to use my function to get data it throw me an error
Error: Failed to connect to alenke.test port 80: Connection refused
but when I execute it in the terminal
curl --ipv4 -v "http://alenke.test/wp-json/chatbot/v1/brand";
it give me
`Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to alenke.test (127.0.0.1) port 80 (#0)
GET /wp-json/chatbot/v1/brand HTTP/1.1
Host: alenke.test
User-Agent: curl/7.54.0
Accept:
HTTP/1.1 200 OK
Server: nginx/1.15.7
Date: Sun, 01 Sep 2019 16:47:36 GMT
Content-Type: application/json; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/7.3.7
X-Robots-Tag: noindex
Link: <http://alenke.test/wp-json/>; rel="https://api.w.org/"
X-Content-Type-Options: nosniff Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages Access-Control-Allow-Headers: Authorization, Content-Type Allow: GET `
and give me all data that I need but when to execute this php script
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// OPTIONS:
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "admin:admin");
// EXECUTE:
$result = curl_exec($curl);
if(!$result){
if (curl_errno($curl)) {
echo 'Error: ' . curl_error($curl);
echo'//;
echo print_r(curl_getinfo($curl));
echo'//;
die("Connection Failure..?");
}
}
curl_close($curl);
return $result;
}
it shows me this error
Error: Failed to connect to alenke.test port 80: Connection refused

I've copy-pasted your code to a file (test.php) on my computer, surrounded it with a
<?php .. ?>
block, and added a call like this after the function:
$res=callAPI('GET', 'http://myserver/', '');
echo $res;
Then started the script in command line by php test.php, and got the expected result (the index.html file of my server).
So whatever you're doing works. Try testing it in command line first to see if necessary modules are installed/enabled. If it works that way, try to fix your webserver's config files. If you need more help, please add some information about your system (webserver, version, OS, and anything relevant). Sysadmins tend to disable certain features (including curl) on shared hosting, maybe your default configuration is based on that.

I will recommend you check your firewall and to check if the domain what ip is resolving.
telnet domain 80
telnet ipserver 80

Related

PHP curl gets stuck

I am trying to write a basic curl code in PHP. I think what I am doing is right (as far as I have read) -
$url = '0.0.0.0:8080/data.php';
$data = array('username'=>'name','email'=>'abcd#gmail.com');
$payload = json_encode(array($data));
print_r($payload);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_PORT , 8080);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type:application/json'));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
print_r(curl_getinfo($ch));
curl_close($ch);
This is what data.php looks like:
$_POST=json_decode(file_get_contents("php://input"),1);
print_r($_POST);
if(isset($_POST['username'],$_POST['email'])){
$username=mysqli_real_escape_string($db,$_POST['username']);
$email=mysqli_real_escape_string($db,$_POST['email']);
$query = "INSERT INTO tbl_user (username, email)
VALUES('$username', '$email')";
mysqli_query($db, $query);
}
I can't understand why this is not working. The code gets stuck at curl_exec(). I will do sanitization, and use prepared statements once I get this to work.
This is the log:
* Trying 0.0.0.0...
* TCP_NODELAY set
* Connected to 0.0.0.0 (127.0.0.1) port 8080 (#0)
> POST /data.php HTTP/1.1
Host: 0.0.0.0:8080
Accept: */*
Content-Type:application/json
Content-Length: 46
* upload completely sent off: 46 out of 46 bytes
And it gets stuck there. What am I doing wrong here? Does curl not work on localhosts?
EDIT:
This is a major change, but I don't think it would be right to change the original question too much. I reduced all of this down to -
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
//curl_setopt ($ch, CURLOPT_PORT , 8080);
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/data.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
// grab URL and pass it to the browser
curl_exec($ch);
if ( curl_error ( $ch ) ) { echo curl_error ( $ch ); }
// close cURL resource, and free up system resources
curl_close($ch);
?>
Which also gets stuck. However, the same thing works with www.example.com. So I think the problem is with retrieving my URL.
this is the log:
* Rebuilt URL to: http://localhost:8080/
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET / HTTP/1.1
Host: localhost:8080
Accept: */*
data.php only has an echo "Hello"; right now to test it
I can remove the previous parts of the question if they are not necessary.

Getting error 'No authorization header passed' with PHP's POST CURL request - envato api

I'm getting started with the Enavato API
So far I've created an app, got client_id & client_secret and managed to get the code access_key from the https://api.envato.com/authorization after that I'm using the below php code to make POST curl request
$client_id = '***********';
$client_secret = '***********';
$redirect_uri = urlencode('http://localhost:3000');
if(isset($_GET["code"])) :
$apiUrl = 'https://api.envato.com/token';
$params = array(
'grant_type' => 'authorization_code',
'code' => $_GET["code"],
'redirect_uri' => $redirect_uri,
'client_id' => $client_id,
'client_secret' => $client_secret,
);
$curl = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_STDERR, $f);
$result = curl_exec($curl);
fclose($f);
// Check if any error occurred
if(empty($result))
{
// die(curl_errno($curl));
// die(curl_error($curl));
$info = curl_getinfo($curl);
echo '<br><br>';
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
echo '<br><br>';
var_dump($info);
echo '<br><br>';
}
var_dump($result);
// Close handle
curl_close($curl);
endif;
and here is the request.txt dump
* Hostname was found in DNS cache
* Hostname in DNS cache was stale, zapped
* Trying 107.23.230.180...
* Connected to api.envato.com (107.23.230.180) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: *.envato.com
* Server certificate: RapidSSL SHA256 CA - G3
* Server certificate: GeoTrust Global CA
> POST /token HTTP/1.1
Host: api.envato.com
Accept: */*
Content-Length: 699
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------1a95a06d7b815306
< HTTP/1.1 100 Continue
< HTTP/1.1 400 Bad Request
< Access-Control-Allow-Origin: *
< Cache-Control: no-store
< Content-Type: application/json; charset=utf-8
< Date: Sun, 17 May 2015 17:03:41 GMT
< Pragma: no-cache
* Server nginx/1.7.10 is not blacklisted
< Server: nginx/1.7.10
< set-cookie: connect.sid=s%3ARC9gGye-Txp4KLp67M9ESspXijYoUc8i.pT3jYHvu1WyOsSjwsuQzEsy5hLQlc2QpmHkZRm05pXo; Path=/; HttpOnly
< X-Frame-Options: Deny
< X-Powered-By: Express
< Content-Length: 80
< Connection: keep-alive
* HTTP error before end of send, stop sending
<
* Closing connection 0
and finally the error(getting it in JSON)
string(80) "{"error":"invalid_request","error_description":"No authorization header passed"}"
Astonishingly every thing is working with Postman and I'm getting "refresh_token" and "access_token" with a success 200 status code.
I know I'm missing some thing but couldn't find what?
You're using curl_setopt($curl, CURLOPT_POSTFIELDS, $params); with $params being an array. That results in a HTTP POST message with multipart/form-data content type and formatting. But the spec says the content type should be application/x-www-form-urlencoded. You can achieve this by using:
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
You also don't need to urlencode the redirect_uri parameter, since http_build_query will do it for you.
Lastly, do not turn off SSL validation (CURLOPT_SSL_VERIFYHOST, CURLOPT_SSL_VERIFYPEER) since it renders your system insecure.

PHP cURL function related - what is the difference between browser visit, linux curl command and PHP cURL function?

for the url "http://hq.sinajs.cn/list=sh600123"
i can get the response through any of the browser, the result as below,
var hq_str_sh600123="兰花科创,13.53,13.63,13.45,13.61,13.43,13.45,13.46,1113110,15047856,3200,13.45,1500,13.44,11590,13.43,36900,13.42,68900,13.41,9800,13.46,6400,13.47,26496,13.48,14453,13.49,3400,13.50,2013-08-30,09:44:08,00";
also i can get the same response from the linux curl command
curl http://hq.sinajs.cn/list=sh600123
var hq_str_sh600123="兰花科创,13.53,13.63,13.44,13.61,13.43,13.43,13.44,1144910,15475169,39090,13.43,37100,13.42,91000,13.41,235500,13.40,5800,13.39,800,13.44,41300,13.45,9800,13.46,6400,13.47,25496,13.48,2013-08-30,09:44:43,00";
but the big problem is i can't get the right response from the PHP cURL function
my trunk code is like this, have deleted the business logic
$url = "http://hq.sinajs.cn/";//the url
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // the result could be got by the return value
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:' )); // this line is added according to the advice from the internet
curl_setopt($ch, CURLOPT_URL,$url);
$post_data = "list=".urldecode($code); // here the code can be "sh600485"
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
The $result is false, and i add verbose code like this :
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $verbose = fopen('php://temp', 'rw+'));
echo "Verbose information:\n<pre>", !rewind($verbose), htmlspecialchars(stream_get_contents($verbose)), "</pre>\n";
The output is
Verbose information:
* About to connect() to hq.sinajs.cn port 80 (#0)
* Trying 202.108.37.102...
* connected
* Connected to hq.sinajs.cn (202.108.37.102) port 80 (#0)
POST / HTTP/1.1 Host: hq.sinajs.cn Accept: / Content-Length: 13 Content-Type: application/x-www-form-urlencoded
upload completely sent off: 13 out of 13 bytes
Empty reply from server
Connection #0 to host hq.sinajs.cn left intact
Verbose information:
* Connection #0 seems to be dead!
* Closing connection #0
* About to connect() to hq.sinajs.cn port 80 (#0)
* Trying 202.108.37.102...
* connected
* Connected to hq.sinajs.cn (202.108.37.102) port 80 (#0)
POST / HTTP/1.1 Host: hq.sinajs.cn Accept: / Content-Length: 13 Content-Type: application/x-www-form-urlencoded
upload completely sent off: 13 out of 13 bytes
Empty reply from server
Connection #0 to host hq.sinajs.cn left intact
my question is why the difference from the result is so big?
what is the root cause the website server ? does it forbid the PHP cURL access?
how to solve the problem ?
Thanks in advance!
Your first two examples you are making HTTP GET requests. In your failing php/curl example, you are using HTTP POST.
I suspect you
Try changing the CURLOPT_POST option:
curl_setopt($ch, CURLOPT_POST, 0);
The following example works for me. Notice I've added the query parameter to the url and changed the HTTP method to GET.
<?php
$url = "http://<INSERT URL HERE>?list=sh600123";
// ^ use query params instead of post values...
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
var_dump($result);

How to perform a PUT operation using CURL in PHP?

I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
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/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);

How to trouble shoot - post data to script with CURL

I need to post some data to a script on my server. I'm using curl with and verbose error reporting. Does anyone have any idea why this is not working please?
Thanks,
Posting script
function makePost($postvars, $count) {
$url = 'http://servername.something.org/php/callback-f.php';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$result = curl_exec($ch);
curl_close($ch);
}
The script which is posted to contains this line:
<?php log_error("success",ERROR_LOG_TO_STDERR); ?>
My post vars a string which look like this:
surname=smth&address1=No+Value&this=that
The result i get back is this:
Connected to myserver.org port 80
> POST /php/callback-f.php HTTP/1.1
Host: myserver.org
Pragma: no-cache
Accept: */*
Content-Length: 1510
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 301 Moved Permanently
< Location: https://myserver/php/callback-f.php
< Content-Length: 0
< Date: Wed, 16 Nov 2011 16:21:23 GMT
< Server: lighttpd/1.4.28
* Connection #0 to host left intact
* Closing connection #0
Could you try using:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
You are getting back a 301 error. Your attempted url is http://servername.something.org and the 301 is saying the page is to be found at https://myserver (note https protocol).
301 errors also are not supposed to redirect on POST without user assent.

Categories