Someone just dumped a perl script on me and now it's my problem. I know nothing about Perl. Here's the script.
#! /usr/bin/perl
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
$ua = LWP::UserAgent->new;
my $req = POST 'http://www.someurl.com/aff/', [ search => 'www', errors => 0 ];
my $xml = "<?xml version='1.0' encoding='UTF-8' ?>
<data xmlns='https://www.aff.gov/affSchema' sysID='Adin'
rptTime='2010-06-07T14:10:30.758-07:00' version='2.23'>
<msgRequest to='Co' from='trt' msgType='Data Request' subject='Async'
dateTime='2010-06-07T14:10:30.758-07:00'>
<body>2010-06-07T14:50:06Z</body>
</msgRequest>
</data>";
$req->content( $xml );
my $username = "providedUserName";
my $password = "providedPW";
$req->authorization_basic($username, $password);
print $ua->request($req)->as_string;
As far as I can tell it's creating a HTTP Request object, adding some content and printing the response. Google tells me that I need to install a Perl package to get a HTTPRequest object in PHP, which isn't an option. Is there anyway to do this with cURL or file_get_contents or something?
I'll keep tinkering away, but if anyone knows for sure how to do it, then it'll save me wasting my time at the very least.
This is an HTTP POST request with content type 'text/xml'. I believe you can do this with cURL as follows (example adapted from http://www.infernodevelopment.com/curl-php-send-post-data-background and is untested):
$x = curl_init("http://www.someurl.com/aff/");
curl_setopt($x, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($x, CURLOPT_HEADER, 0);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$xml = "<?xml version='1.0' encoding='UTF-8' ?>
<data xmlns='https://www.aff.gov/affSchema' sysID='Adin'
rptTime='2010-06-07T14:10:30.758-07:00' version='2.23'>
<msgRequest to='Co' from='trt' msgType='Data Request' subject='Async'
dateTime='2010-06-07T14:10:30.758-07:00'>
<body>2010-06-07T14:50:06Z</body>
</msgRequest>
</data>";
curl_setopt($x, CURLOPT_POSTFIELDS, $xml);
$username = "providedUserName";
$password = "providedPW";
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($x, CURLOPT_USERPWD, "$username:$password");
$data = curl_exec($x);
Related
I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.
I'm sure this has been answered, but I just can't figure out the right question to ask the search, so here goes:
I have a calling program that's doing a curl call to another program - however I'm not getting anything back from the called program.
Here's the calling program (Please excuse the rookie coding - I'm learning as I go with this project)....
<?php
session_start();
$user = "user";
$pass = "pass";
$part = "12345";
$strConnect = "AppServer://1.2.3.4/appsrv";
$strUser = "cono91|oper=1234";
$_SESSION["part"] = $part;
$_SESSION["strConnect"] = $strConnect;
$_SESSION["strUser"] = $strUser;
$_SESSION["response"] = "init";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://5.6.7.8/test/Pricing.php');
curl_setopt($ch, CURLOPT_POST, true);
$data = array('part' => $part,'strConnect' => $strConnect,'strUser' =>
$strUser);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($r);
var_dump($_SESSION); /* Just returns the $_SESSION var's I set above */
?>
And what it's calling:
<?php
session_start();
$part = $_SESSION['part'];
$strConnect = $_SESSION['strConnect'];
$strUser = $_SESSION['strUser'];
//$part = "341241";
//$strConnect = "AppServer://1.2.3.4/appsrv";
//$strUser = "cono=9|oper=xxx";
$soapUrl = "http://5.6.7.8/api/ApiService.asmx?op=Pricing";
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Pricing xmlns="X.WS">
<connectString>' .$strConnect. '</connectString>
<userCode>' .$strUser. '</userCode>
<requestObject>
<customerNumber>55555</customerNumber>
<warehouse>WHSE</warehouse>
<quantity>1</quantity>
<productCode>' .$part. '</productCode>
</requestObject>
</Pricing>
</soap:Body>
</soap:Envelope>';
$headers = array(
"POST /api/ApiService.asmx HTTP/1.1",
"Host: 5.6.7.8",
"Content-Type: text/xml; charset=utf-8",
"Content-Length: ".strlen($xml_post_string),
"SOAPAction: X.WS/Pricing"
);
$url = $soapUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$pos = strpos($response,"<OEPricingResult>");
$rx = substr($response,$pos,strlen($response));
$response1 = str_replace("</soap:Body>","",$rx);
$response2 = str_replace("</soap:Envelope>","",$response1);
$response3 = str_replace("</OEPricingResponse>","",$response2);
$response3 = "<xml>" .$response3. "</xml>";
$_SESSION["response"] = $response3;
var_dump($_SESSION);
print_r($response3); /* Gives me the output from the curl call this program makes
?>
So when program #1 does it's surl call to program #2 - it just returns nothing. So I forced in the variables in program #2 ran it stand alone and get the output I expected (in a command line and web call). I've tried to return the data in every way I can figure out - but after a few days of this, I just don't know the next question to ask.
So - how do I get the data from program #2 back to program #1?
I appreciate any help I can get on this....
A script invoked through curl doesn't inherit the session variables from the calling script. You're sending those parameters in the CURLOPT_POSTFIELDS, and you need to read them from $_POST, not $_SESSION.
So in the second script, you should use:
$part = $_POST['part'];
$strConnect = $_POST['strConnect'];
$strUser = $_POST['strUser'];
I am trying to create a form for the user to buy product from my Ruby on Rails website by using their "Scratch Card for Mobile Phones".
The problem is that the service only provides Module code for PHP. So I have to convert it to Ruby to put into my website. Here are the codes I want to convert to Ruby:
$post_field = 'xyz=123&abc=456';
$api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api_url);
curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
I have tried to convert them to Ruby code but always got confused. Can anyone help me convert these codes into working Ruby codes? Thanks in advance!
Here is my silly code so far:
RestClient.post($api_url, $post_field, "Content-Type" => "application/x-www-form-urlencoded")
Basically all that I need is a ruby version of the php curl code. I'm a newbie, not an experienced programmer, so please help.
Try something like this:
require 'rest-client'
require 'rack'
post_query = 'xyz=123&abc=456'
api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php"
query_hash = Rack::Utils.parse_nested_query(post_query)
begin
response = RestClient.post api_url, :params => query_hash
print response.code
print response.body
rescue Exception => e
print e.message
end
All the code is doing is sending a payload xyz=123&abc=456 through a POST request to a specified URL.
You might use e.g. the curb gem for this:
response = Curl.post("https://www.nganluong.vn/mobile_card.api.post.v2.php", {:xyz => 123, :abc => 456})
result = response.body_str
status = response.status
Here are my code samples:
function xmlPostStore($post_xml, $url, $port) {
$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
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, $post_xml); // add POST fields
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
what i'm sending:
$XML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<SendConfig>
<Request>
<key>passphrase</key>
</Request>
</SendConfig>";
$reply = xmlPostStore($XML, "http://www.urlhere.com/test.php", "80");
test.php is just a simple XML return:
echo "<?xml version='1.0' encoding='utf-8'?>
<response>
<config>
<test>it works</test>
</config>
</response>";
When I test this on one server, it works 100% of the time. I receive a response and there's no issues.
When I test it on our main server, it returns back nothing, most of the time, about 98% of the time it's blank. Without any code changes, it will randomly work and randomly stop. I'm stumped.
Turns out what I believed to be opening the firewall to allow incoming and outgoing connections was only allowing incoming, not outgoing. I also resolved a DNS error under resolv.conf and things are now working correctly.
I have a small PHP script that is listening for a POST request. I'm expecting xml, always.
Normally I'm the guy sending the xml requests. But today I'm on the receiving side.
I figured it would be a simple case of listening for a $_POST, but I guess I may be incorrect - I'm getting nothing.
Here's my script that waits for anything xml:
<?php
if(isset($_POST)) {
mail("me#myemail.com","some title i want", print_r($_POST, true));
}else{
die("uh, what happened?");
}
?>
And here is a simple xml string I'm sending from another place:
<?php
$xml_data ='
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don\'t forget me this weekend!</body>
</note>
';
function sendXML2Server($URL,$XML){
$xml_data = trim($XML);
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
echo sendXML2Server('https://someurl.com/inboundxml.php',$xml_data)
?>
And here's what I get in my email:
Array
(
)
I'm guessing I'm not working with an array correctly, but maybe there's something else I'm missing in all this. I'm expecting to get back the actual xml string.
You sending nothing but data, thats why PHP cannot interpreter this data as some key&value. So, you need to send it as a value of variable:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml_data' => $xml_data));
or receive as a raw post data:
<?php
if(isset($HTTP_RAW_POST_DATA)) {
mail("me#myemail.com","some title i want", print_r($HTTP_RAW_POST_DATA, true));
}else{
die("uh, what happened?");
}
?>
CURLOPT_POSTFIELDS requires an array:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('content'=>$xml_data));
Then retrieve it like:
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['content'])) {
mail("me#myemail.com","some title i want", print_r($_POST['content'], true));
}else{
die("uh, what happened?");
}
?>