PHP curl gets stuck - php

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.

Related

cURL Failed to connect to port 80

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

Converting PHP Curl request of PAYGATE API to python

I am not much familiar with php and curl, need to convert an advance PHP cURL POST request to python equivalent.
It's a code from payment gateway site called paygate, and am using their sample php API from developer.paygate.co.za/. The code that I tried to convert into python is below:
<?php
//The PayGate PayXML URL
define( "SERVER_URL", "https://www.paygate.co.za/payxml/process.trans" );
//Construct the XML document header
$XMLHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE protocol SYSTEM \"https://www.paygate.co.za/payxml/payxml_v4.dtd\">";
// - Then construct the full transaction XML
$XMLTrans = '<protocol ver="4.0" pgid="10011013800" pwd="test"><authtx cref="ABCqwerty1234" cname="Patel Sunny" cc="5200000000000015" exp="032022" budp="0" amt="10000" cur="ZAR" cvv="123" rurl="http://localhost/pg_payxml_php_final.php" nurl="http://localhost/pg_payxml_php_notify.php" /></protocol>'
// Construct the request XML by combining the XML header and transaction
$Request = $XMLHeader.$XMLTrans;
// Create the POST data header containing the transaction
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($Request)."\r\n";
$header[] = $Request;
// Use cURL to post the transaction to PayGate
// - first instantiate cURL; if it fails then quit now.
$ch = curl_init();
if (!$ch) die("ERROR: cURL initialization failed. Check your cURL/PHP configuration.");
// - then set the cURL options; to ignore SSL invalid certificates; set timeouts etc.
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "POST");
// - then set the PayXML URL and the transaction data
curl_setopt ($ch, CURLOPT_URL, SERVER_URL);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
// Connect to PayGate PayXML and send data
$Response = curl_exec ($ch);
// Checl for any connection errors and then close the connection.
$curlError = curl_errno($ch);
curl_close($ch);
I know about basic requests in python but couldn't pass attributes in that request, I am also confused about passing cURL data in requests.
I am trying it like:
import requests
post_data = {'pgid':'10011013800',
'pwd':'test',
'cref': 'ABCX1yty36858gh',
'cname':'PatelSunny',
'cc':'5200000470000015',
'exp':'032022',
'budp':'0',
'amt':'50000',
'cur':'ZAR',
'cvv':'123',
'rurl':'http://localhost/pg_payxml_php_final.php',
'nurl':'http://localhost/pg_payxml_php_notify.php',
'submit':'Submit'
}
r = requests.get('https://www.paygate.co.za/payxml/process.trans', params=post_data,headers=headers)
# print(r.url)
print r.text
But it shows error
405 - HTTP verb used to access this page is not allowed.
Finally solved it,
import requests
import xml.etree.ElementTree as ET
headers = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'en-US,en;q=0.8',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'112',
'Content-Type':'application/x-www-form-urlencoded',
'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36",}
xml = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE protocol SYSTEM "https://www.paygate.co.za/payxml/payxml_v4.dtd">
<protocol ver="4.0" pgid="10011013800" pwd="test">
<authtx cref="ABCX1j64564" cname="Patel Sunny" cc="5200000000000015" exp="032022" budp="0" amt="10000" cur="ZAR" cvv="123"
rurl="http://localhost/pg_payxml_php_final.php" nurl="http://localhost/pg_payxml_php_notify.php" />
</protocol>
"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
response = requests.post('https://www.paygate.co.za/payxml/process.trans', data=xml, headers=headers).text
tree = ET.fromstring(response)
for node in tree.iter('authrx'):
sdesc = node.attrib.get('sdesc') # STATUS MESSAGE
tid = node.attrib.get('tid') # TRANSACTION ID
cref = node.attrib.get('cref') # REFERENCE NO. like invoice_no or sale_order_no
auth = node.attrib.get('auth')
rdesc = node.attrib.get('rdesc') # Result Code description.
print sdesc, tid, cref

How to get router informations using cURL and PHP

I am building a web application for my router, it will be my Bachelor's Thesis.
The bad thing is that I can't display my router's informations using my cURL function because I get bad router username and password error. I didn't found any problem at all:
The cURL function:
function myCurl($url, $post="")
{
global $status;
$header = 'Authorization: Basic YWRtaW46YWRtaW4=';
$cookiepath_tmp = "c:/xampp/htdocs/wifi/cookie.txt";
$resp = array();
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
curl_setopt($ch,CURLOPT_URL, trim($url));
curl_setopt($ch,CURLOPT_REFERER, trim($url));
curl_setopt($ch,CURLOPT_COOKIEJAR,$cookiepath_tmp);
curl_setopt($ch,CURLOPT_COOKIEFILE,$cookiepath_tmp);
curl_setopt($ch,CURLOPT_COOKIESESSION, true);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_MAXREDIRS, 10);
curl_setopt($ch,CURLOPT_ENCODING, "");
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
#curl_setopt($ch,CURLOPT_AUTOREFERER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch,CURLOPT_TIMEOUT, 15);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_HTTPHEADER, array( 'Expect:' ) );
curl_setopt($ch,CURLOPT_VERBOSE, 1);
#curl_setopt($ch,CURLOPT_FAILONERROR, true);
if($post) { curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$post); }
$returned = curl_exec($ch);
$resp['returned'] = $returned;
$status=curl_getinfo($ch);
$resp['status'] = $status;
curl_close($ch);
return $resp;
}
I am trying to display the informations using PHP:
The PHP code:
<?php echo $success_msg;
$url = "http://192.168.0.1/session.cgi";
$post = "REPORT_METHOD=xml&ACTION=login_plaintext&USER=admin&PASSWD=admin&CAPTCHA=";
$data = myCurl($url, $post);
#$url = "http://192.168.0.1/st_log.php";
#$data = myCurl($url);
echo $data['returned'];
?>
The error is:
Username or Password is incorrect.
However, The username and password admin are correct.
I have added the following code into myCurl function but still doesn't work:
$header = 'Authorization: Basic YWRtaW46YWRtaW4=';
YWRtaW46YWRtaW4= is the encoded username:password in Base64.
LAST EDIT:
I set the CURLOPT_HEADER to true, and I got this text displayed:
HTTP/1.1 501 Not Implemented Server: Router Webserver Connection: close WWW-Authenticate: Basic realm="TP-LINK Wireless Lite N Router WR740N" Content-Type: text/html
Any solution for this?
I really appreciate your help! Thank you!
I don't known what is your router (vendor / model) but most of them use HTTP basic authentication. And, when the authentication is empty or wrong you get a HTTP 401 error: Unauthorized, which could correspond to your error string.
So you should try to insert a HTTP authorization header in the cURL request:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

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);

Wordpress XMLRPC returning blank, but successful

I'm trying to post to WordPress using curl via PHP - I'm posting using the XMLRPC built into Wordpress by default.
Posting is successful with the below code, but nothing is returned. I need to know some information about the post, such as it's URL - I can do this if I have the 'post ID', which by looking at the xmlrpc.php file, it should return. Below is my code for posting:
function post($username, $password, $title, $content, $url, $category=array(), $keywords='', $type='Wordpress')
{
$encoding = 'UTF-8';
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$reqparams = array(
'title'=>$title,
'description'=>$content,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>$category
);
$params = array(0,$username,$password,$reqparams,true);
$request = xmlrpc_encode_request('metaWeblog.newPost',$params);
$ch = curl_init();
$fp = fopen('/home/*/public_html/file.txt', 'w+');
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fp);
$results = curl_exec($ch);
echo '<pre>'.print_r($results, true).'</pre>';
curl_close($ch);
return $results;
}
The echo '<pre>'.print_r($re... line just shows <pre></pre>. I have savd the verbose output of curl into a file, please find it below (I've starred out the URL):
* About to connect() to www.*******.com port 80 (#0)
* Trying 87.106.55.179... * connected
* Connected to www.*******.com (87.*.*.179) port 80 (#0)
> POST /xmlrpc.php HTTP/1.1
Host: www.*******.com
Accept: */*
Content-Length: 1445
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
< HTTP/1.1 100 Continue
* Operation timed out after 1000 milliseconds with 0 bytes received
* Closing connection #0
As I said, the CODE DOES POST, BUT NOTHING IS RETURNED. Sorry to be blunt, but I know this will start off a torrent of pointless answers. So, should I be expecting a post ID to be returned, and if not, how can I easily get it returned?
Thanks
Sod's law. After posting I tried changing the max timeout time: curl_setopt($ch, CURLOPT_TIMEOUT, 1); to 10: curl_setopt($ch, CURLOPT_TIMEOUT, 10); and I get some nice XML returned with the post ID embedded.
I haven't deleted this post as I thought it might be useful for someone.
It will return ($results) the results as xml ... I think in your program it wont display anything in screen ( But u can see that xml data in source code of the output screen ) .. You should use xmlrpc_decode or XML parsing function to get the data from returned XML .. In your program it will return the newly created post id.
For your program, I think folowing changes will do the work
$results = curl_exec($ch);
$results = xmlrpc_decode($results);
echo '<pre>'.print_r($results, true).'</pre>';

Categories