I have a simple form which i want to convert into a PHP backend system.
Now this form has an action to submit to a URL - the URL only accepts an invite only when a data with the name postdata and correct information is submitted (xml which has been encoded).
Works: - Note that the input name is called postdata and the value contains the xml which has been urlencoded and it works perfectly.
<form name="nonjava" method="post" action="https://url.com">
<input name="postdata" id="nonjavapostdata" type="hidden" value="<?xml version="1.0" encoding="utf-8"" />
<button type="submit" name="submit">Button</button>
</form>
However, i want to achieve the following by moving the postdata element within PHP as a lot of information is passed through that way.
Please note: the link is https but it wasnt working on local so i had to disable it within the CURL.
<?php
$url = 'https://super.com';
$xmlData = '<?xml version="1.0" encoding="utf-8"?>
<postdata
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<api>2</api>
</postdata>';
$testing = urlencode($xmlData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "postdata=" . $testing);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$response = curl_exec($ch);
// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
echo $header_size . '<br>';
echo htmlspecialchars($header) . '<br>';
echo htmlspecialchars($body) . '<br><br>';
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo "$http_status for $url <br>";
?>
I keep getting a 302 error (which is the url content is not finding the data so its redirecting to a not found page.)
302 is NOT error; it just means you need to go to the redirected URL. A browser does that automatically for you. In PHP code, you would have to do it yourself. Look at the Location header on 302.
I tried to look if there is a way that Curl could be told to follow through redirects; many language HTTP libraries support that. This thread seems to suggest that CuRL also supports it - Is there a way to follow redirects with command line cURL
Your code works as it is supposed to, I am getting POST data:
Array ( [postdata] => <?xml version="1.0" encoding="utf-8"?> <postdata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/20
01/XMLSchema"> <api>2</api> </postdata> )
as a result. The problem is on the receiving side, it isnt handling it correctly.
You need to follow the 302 redirect in curl. This is relatively easy to do by adding the location flag. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
This is the equivalent of doing curl -L at the CLI. You can see an example here in the php documentation.
Related
I try to get odata produced by a navision webservice. When I directly access the url given using chrome browser, the page asks for user name and password and then chrome shows xml data as expected.
But when i use a PHP script, it always returns "1".
My code looks like this:
$url = 'http://103.7.1.182:14048/DynamicsNAV71-6/OData/Company(\'Unit%20G%205\')/Item_Master_on_hand_no_Desc';
$login = 'Gem-gae\senzo1:Bsbsenzo2018';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, $login);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/x-www-form-urlencoded',
'Content-Length: ' . strlen(1))
);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
Is there any mistakes with that code ?
Thanks for your help
There's no mistake on your code, it successfully connects to the external server via cURL and retrieves the data.
The value in $output (if you do a var_dump) is true (that's why you see 1 if you echo it).
Said that, the issue is on the server you are contacting (103.7.1.182:14048).
You probably need to send some data or something, I can't tell you exactly what because I don't know what is in that server.
To send data, you can add a curl_setopt line:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
Where $data is an array.
I'm new here so please be patient, This is my request code, I want to write another piece of code in another server that will be accepting it and returning an xml 7101 success code using php and curl. How do I write code in a receiving server. This is actually API that I will be using to exchange data between my system and another remote system stored in clouds I have managed to send request successfully but I have stuck at receiving their requests, I have spent an entire week on it please help me out on receiving the requests when they send them to me.
success code is
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<gepgBillSubReqAck>
<TrxStsCode>7101</TrxStsCode>
</gepgBillSubReqAck>
the request code is this,
<?php
//Bill Request
$content ="<gepgBillSubReq>
<BillHdr>
<SpCode>SP103</SpCode>
<RtrRespFlg>true</RtrRespFlg>
</BillHdr>
<BillTrxInf>
<BillId>1812022009968</BillId>
<SubSpCode>1001</SubSpCode>
<SpSysId>TANESCO001</SpSysId>
<BillAmt>1180</BillAmt>
<MiscAmt>0</MiscAmt>
<BillExprDt>2017-12-31T23:59:59</BillExprDt>
<PyrId>5144AA5914</PyrId>
<PyrName>test</PyrName>
<BillDesc>Bill Number 5913</BillDesc>
<BillGenDt>2017-12-21T09:39:00</BillGenDt>
<BillGenBy>Bhstenkubo</BillGenBy>
<BillApprBy>Bhstenkubo</BillApprBy>
<PyrCellNum/>
<PyrEmail/>
<Ccy>TZS</Ccy>
<BillEqvAmt>1180</BillEqvAmt>
<RemFlag>false</RemFlag>
<BillPayOpt>1</BillPayOpt>
<BillItems>
<BillItem>
<BillItemRef>5144AA5914</BillItemRef>
<UseItemRefOnPay>N</UseItemRefOnPay>
<BillItemAmt>1180</BillItemAmt>
<BillItemEqvAmt>1180</BillItemEqvAmt>
<BillItemMiscAmt>0</BillItemMiscAmt>
<GfsCode>140316</GfsCode>
</BillItem>
</BillItems>
</BillTrxInf>
</gepgBillSubReq>";
$resultCurlPost = "";
$serverIp = "XXXXXXXXXXXXXXXX";
$uri = "/XXX/XXX/qrequest"; //this is for qrequest
echo "Message ready to GePG:"."\n".$content."\n";
$ch = curl_init($serverIp.$uri);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/xml',
'Gepg-Com:default.sp.in',
'Gepg-Code:SP103',
'Content-Length:'.strlen($content))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);
//Capture returned content from GePG
$resultCurlPost = curl_exec($ch);
curl_close($ch);
//$resultCurlPost=$data;
if(!empty($resultCurlPost)){
echo "\n\n";
echo "Received Response\n";
echo $resultCurlPost;
echo "\n";
}
else
{
echo "No result Returned"."\n";
}
?>
Thanks, you guys for contributing I found a solution, I used file_get_contents("php://input"); on the receiving server and so far it is working fine.
This is my first shot at getting something back from a web service. What I'm expecting is something to the effect of 'Authorization Failed'. The URL is one in our test environment and the XML being sent is correct, but I'm not getting a response and don't know what I'm doing wrong.
The service is REST, the headers have to pass an encoded authorization (this example is correct) and the content type is set as xml.
When I use the same parameters to test it in the Advanced Rest Client in Chrome it connects and gives me a response.
Also, if there's a better way to create the XML, I'm all for that - this is just an example I found and started with. Code is below
<?php
if (!isset($_POST['firstname'])) {
?>
<form name="ppost" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="text" name="firstname" />
<input type="submit" name="SUbmit" value="Submit" />
</form>
<?php
} // end if, form not posted
else {
extract($_POST);
$inputdata = '
<ReqGetWebUserInfo>
<OrgId>598</OrgId>
<OrgUnitId>598</OrgUnitId>
<MasterCustomerId>'.$firstname.'</MasterCustomerId>
<SubCustomerId>0</SubCustomerId>
</ReqGetWebUserInfo>';
echo '<pre>'.$inputdata.'</pre>';
$url = "https://gsusacustom.ebiz.uapps.net/GSUSARestWebService/PersonifyWcfSvc.svc/GetWebUserInfo";
$headers = array(
'Authorization: Basic dG1hc2d1bmRhbTpwYXNzd29yZDE=',
'Content-Type: application/xml;charset=utf-8',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url ); // THE URL TO FETCH - CAN ALSO BE SET IN THE CURL_INIT
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0); // DON'T INLCUDE HEADER IN THE OUTPUT
curl_setopt($ch, CURLOPT_POST, 1); // TRUE FOR A REGULAR HTTP POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputdata); // THE DATA POST FROM THE FORM
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
print $response;
} // end else, form submitted and processed
?>
Thanks in advance.
My guess is you didn't handle the https connection as your has it. Try this option:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
If the error still persists then do the following to dig more.
Run the code with enabling all error reporting:
error_reporting(E_ALL);
Run the curl with enabling debugging option:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
Please excuse my terminology if I get anything wrong, I'm new to Google API
I'm trying to add events via the Places API, for a single venue (listed under the bar category). I've followed the instructions here:
https://developers.google.com/places/documentation/actions?utm_source=welovemapsdevelopers&utm_campaign=places-events-screencast#event_intro
and this is the URL I am posting to (via PHP)
https://maps.googleapis.com/maps/api/place/event/add/format?sensor=false&key=AIzaSyAFd-ivmfNRDanJ40pWsgP1 (key altered)
which returns a 404 error. If I have understood correctly, I have set the sensor to false as I am not mobile, and created an API key in Google apis, with the PLACES service turned on.
Have I missed a vital step here, or would a subsequent error in the POST submission cause a 404 error? I can paste my code in but I thought I'd start with the basics.
Many thanks for your help, advice and time. It's very much apprecciated.
I've added this line to my CurlCall function which I believe should specify a POST, and the result is still the same.
curl_setopt($ch, CURLOPT_POST, 1);
so the whole functions reads
function CurlCall($url,$topost)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADERS, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $topost);
$body = curl_exec($ch);
curl_close($ch);
echo $body;
echo '<br>';
echo 'URL ' . $url;
echo '<br>';
return $body;
}
Are you sure that you are using the POST method and not GET?
You need to specify the format of your request in the URL by changing the word format to either json or xml depending on how you are going to structure and POST your request.
XML:
https://maps.googleapis.com/maps/api/place/event/add/xml?sensor=false&key=your_api_key
JSON:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=your_api_key
I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?