cURL POST data Problem - php

im bizzare and im new in stackoverflow , i have some problem and that's :
im sending some page directly to a page and page answer to my request correctly , but i when to try send post data using cURL by php , the page do not react anywhere:
<form action="http://remotehost.com/index.aspx" method="post"> -> its work correctly and the index.php show me what i want but when :
<form action ="http://localhost/fetch_data.php" mthod="post"> ->
fetch_data.php:
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<?php
print_r($_POST);
$remotehost_cgi = 'http://remotehost.com/index.aspx';
$ret = post_data($_POST, $remotehost_cgi);
echo $ret;
?>
<?php
function post_data($datatopost,$urltopost){
$crl = curl_init ($urltopost);
curl_setopt ($crl, CURLOPT_POST, true);
curl_setopt ($crl, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, true);
$returndata = curl_exec ($crl);
return $returndata;
}
?>

mthod="post" to method="post" ?

curl_exec() returns boolean FALSE if the exec failed for any reasons. Instead of just returning your $returndata, test it first:
...
$returndata = curl_exec($crl);
if ($returndata === FALSE) {
die('Curl failed: ' . curl_error($crl));
}
return($returndata);
Since you only echo out this value, you'd never see it, as boolean false will output as a null/empty string.

Related

JSON_DECODE returning NULL from cURL response even though encode format seems correct?

EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
I'm trying to take a login from my test.php file and cURL it to a site which uses the data to simulate a login on another page (I know this is tedious, but this isn't the full extent of what I'm doing as a whole, just where I have the problem). So I post an encoded json to the index.php url which has no problem decoding it. The information passed is then used and the decoded json is edited to show successful or unsuccessful login. The json is then encoded once again and echoed onto the page and held in $contents on test.php. When I try to decode it on this file I get NULL everytime. I've tried a ton of things and am just starting to think I made a stupid mistake somewhere so I'm desperately looking for any help here.
-If I echo $contents it shows:
{"user":"user","pass":"password","success":true}
-If I var_dump(trim($contents)) it shows (formatted exactly as shown):
string(364) "
{"user":"user","pass":"password","success":true} "
-last_json_error_msg shows:
SYNTAX ERROR
-I've tried trimming, utfencoding, iconv, setting curl headers and literally everything I've seen recommended on other posts here.
Any help at all would be greatly appreciated. Thanks in advance guys.
test.php:
<html>
<head>
<meta charset="UTF-8">
<title>TITLE</title>
</head>
<body>
<form action="test.php" method=POST>
<input type="text" name="user">
<input type="password" name="pass">
<input type="submit" value="Submit">
</form>
<?php
function logInfo(){
class data{
public $user = "";
public $pass = "";
public $success = false;
}
$data = new data();
$data->user = $_POST['user'];
$data->pass = $_POST['pass'];
$ch = curl_init();
$json = json_encode($data);
curl_setopt($ch, CURLOPT_URL, [URL TO INDEX.PHP]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("data"=>$json));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$contents = curl_exec($ch);
curl_close($ch);
$array = json_decode($contents, true);
var_dump($array);
//VAR_DUMP SHOWS NULL
}
if(isset($_POST['user']) && isset($_POST['pass'])){
logInfo();
}
?>
</body>
</html>
index.php:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
header('Context-type: application/json');
function logInfo(){
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
if(isset($_POST['data'])){
logInfo();
}
?>
</body>
</html>
EDIT: For the solution, view reply from Barmar below. Hope this helps anyone with a similar problem.
index.php is printing HTML before the JSON (weren't you suspicious when var_dump() said that the string is 365 characters long, but you can only see about 50?). When the script is being used to return JSON, it can't produce any other output.
So check for the data parameter before printing any output. And if it's found, exit the script after sending the JSON, so you don't print the HTML.
<?php
if(isset($_POST['data'])){
logInfo();
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="test.php" method=POST>
<input type="hidden" name="data">
</form>
<?php
</body>
</html>
<?php
function logInfo(){
header('Context-type: application/json');
$datastring = $_POST['data'];
$data = json_decode($datastring);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, [URL TO SIMULATE LOGIN]);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [LOGIN POST]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == [SUCCESSFUL LOGIN HTTP CODE]){
$data->success = true;
} else {
$data->success = false;
}
echo json_encode($data);
curl_close ($ch);
}
A simpler solution would probably be to put the code that returns logInfo() into a different script.
You should do
json_encode(get_object_vars($data));
in logInfo function
A couple of things I would recommend. It's not a good practice to define a class inside a function. You should have your class in a separate file. It helps keep your code organised.
Secondly, its good to follow either snake case or camel case for defining classes / methods / functions etc.
Snake case eg: my_function_name_to_execute
Camel case eg: MyFunctionNameToExecute
Try to check resulting JSON syntax using this library https://github.com/Seldaek/jsonlint
UPDATE
It correctly detects extra HTML from index.php and other possible problems.
Following example
use Seld\JsonLint\JsonParser;
$parser = new JsonParser();
$exception = $parser->lint('<html>{"user":"user","pass":"password","success":true}');
echo $exception->getMessage();
will output:
Parse error on line 1:
<html>{"user":"user"
^
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

php curl result is invalid

This is my first time posting here! :)
I have made a php license generation and validation system. The server end communicates with the mysql database and outputs a json result like the following:
{"valid":"true","info":{"id":"1","expire":"1421811123"}}
The problem is on the client server where i have the following script:
<?php
$key_info['key'] = "KEY"];
$serverurl = "http://URLTOSERVER";
$ch = curl_init ($serverurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $key_info);
$result = curl_exec ($ch);
$result = json_decode($result, true);
if($result['valid'] == true){
echo "valid";
}
else {
die("Invalid Key!");
}
?>
When i run this i get "valid" every time, even when i enter the wrong key - i have tried printing the output and i can confirm that.
Please advise.
Thanks.
Your JSON contains a string true, not a boolean true. Any string in there will pass == true.
if($result['valid'] == 'true'){

Azure won't cURL a google site search xml

I'm running the XML to PHP install of paid Google site search.
https://code.google.com/p/google-csbe-example/downloads/detail?name=gss.php&can=2&q=
My initial implementation runs perfectly on a LAMP server, however I now have to run a PHP environment on the Windows Azure Platform.
It appears as though the $url variable is not being passed through cURL, as the $result varaible returns as NULL.
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
If i modify the value of $url to a different remote xml file, with a little adjustment to the output structure, I get the expected results.
I have tried several different troubleshooting steps including:
cURL: alternate xml feed renders
simplexml: alternate rss feed renders
permissions: site permissions aren't required google cse dashboard
alternate azure site: tested and failed
alternate LAMP hosted site: tested and success
alternate search setup: this had no effect
is the domain blocked to google: don't think so
url queries blocked: not sure if this is causing any issues
I'm stumped.
Any help would be greatly appreciated.
Thanks!
Here's the full code (minus the cx number):
<?php
//ini_set('display_startup_errors',1);
//ini_set('display_errors',1);
//error_reporting(-1);
$q = $_GET['q'];
$q = urlencode($q);
//WRAPPED IN A IF STATEMENT SO PROMOTED RESULTS SHOW UP ON THE FIRST PAGE
if(isset($_GET['start'])){
$start = $_GET['start'];
}
$your_cx_number = 'enter_your_paid_google_site_search_cx_number';
$url = 'https://www.google.com/cse?cx=' . $your_cx_number . '&client=google-csbe&output=xml_no_dtd&q=' . $q;
if(isset($start)){
$url .= '&start=' . $start;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
//curl_setopt($ch, CURLOPT_POSTFIELDS, "postparam1=postvalue"); // add POST fields
//submit the xml request and get the response
$result = curl_exec($ch);
curl_close($ch);
//now parse the xml with
$xml = simplexml_load_string($result);
$START = $xml->RES['SN'];
$END = $xml->RES['EN'];
$RESULTS = $xml->RES->M;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search results</title>
</head>
<body>
<form action="search-test.php" id="searchform" >
<input type="text" name="q" placeholder="Search..." <?php if(isset($_GET['q'])) { echo 'value="' . $_GET['q'] . '"' ; }?> id="search-text" size="25" autocomplete="off" />
<input type="submit" id="search-button" title="Search" value="" />
</form>
<p>The url of the XML output</p>
<?php
//extract the title, link and snippet for each result
if ($xml->RES->R) {
foreach ($xml->RES->R as $item) {
$title = $item->T;
$link = $item->U;
$snippet = $item->S;
echo '<h3>' . $title . '</h3>
<p>' . $title . '</p>
<p>' . $snippet . '</p>
<hr />';
}
}
?>
</body>
</html>
cURL error reporting returned an error code : 60
Curl error: 60 - SSL certificate problem: unable to get local issuer certificate
A search for a similar error provided the solution
HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK
Add in the line:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
The full cURL function is now:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);// allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // times out after 30s
curl_setopt($ch, CURLOPT_HTTPGET, true); // set POST method
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Curl error: ' . curl_errno($ch) . ' - ' .curl_error($ch);
$info = curl_getinfo($ch);
if (empty($info['http_code'])) {
die("No HTTP code was returned");
} else {
echo $info['http_code'];
}
}
curl_close($ch);

var_dump says bool but returning a string -php

i'm trying to check my email with curl.
I've got a function which connects to gmail:
function check_email($url)
{
// sendRequest
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0);
$curlData = curl_exec($curl);
curl_close($curl);
//returning retrieved message
return $curlData;
}
When I call the function and echo it ($email = check_email($ur);
echo $email;), gmail sends me some html instead of showing the message:
<HTML>
<HEAD>
<TITLE>Moved Temporarily</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Temporarily</H1>
The document has moved here.
</BODY>
</HTML>
so i want to then extract the "-very large url-" and curl to that, but when i var_dump($email) it says it's a bool! why is it returning html if it's a boolean and how can i get to the aforementioned html via php?
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Shall be used if you want curl_exec() to return anything other than boolean.
http://php.net/manual/en/function.curl-exec.php says
Returns TRUE on success or FALSE on failure. However, if the
CURLOPT_RETURNTRANSFER option is set, it will return the result on
success, FALSE on failure.
Looks like you've got CURLOPT_RETURNTRANSFER set to 0 (false).
http://php.net/manual/en/function.curl-setopt.php

Send xml to webservices using Curl in PHP but returns error

I have a web service to which I send a xml request (application/x-www-form-urlencoded encoded) and get a response back. These are sent to the URL contained within a query parameter called 'xml'
When I use a simple html form such as the one below, I am returned a result. However, when I use my php code, I am returned an error. Perhaps it is because of this: These are sent to the URL contained within a query parameter called 'xml'? If that's the case, how do I send it in that parameter? I'd be very grateful if someone could point out what I've been doing wrong. Many thanks
<form method="post" name="form1" action="http://webservicesapi.com/login.pl">
<textarea cols="80" rows="20" name="xml">
<?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>
</textarea>
<input type="submit" value="submit XML document">
</form>
This doesn't work:
<?php
// open a http channel, transmit data and return received buffer
function xml_post($xml, $url, $port)
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port); //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xml = '<?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>';
$url ='http://webservicesapi.com/login.pl';
$port = 80;
$response = xml_post($xml, $url, $port);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<P><?=nl2br(htmlentities($response));?></P>
</body>
</html>
?>
CURLOPT_POSTFIELDS expects either an associative array, or a raw post string. Since you are passing it a string, it treats it as a raw post string. So either of these should work:
$response = xml_post(array('xml' => $xml), $url, $port);
OR
$response = xml_post('xml='.urlencode($xml), $url, $port);

Categories