Jump to content

help with perl LWP::UserAgent to php translation (long)


RoyHB

Recommended Posts

I have absolutely no knowledge of perl. 

 

I have some sample perl code from a supplier that sends a POST to their website in a very strict syntax and is supposed to return some data.  The perl code works.  My attempt at a translation to PHP doesn't work.  With perl I get the expected data, with PHP i get an error message from the vendor server that says ">Your browser sent a request that this server could not understand." but no detail on what is wrong with the request.  I suspect that the problem is in the message headers, not the body, since I send exactly the same xml body - loaded from the same file, for both.

 

I've been struggling with this long enough to consider loading the php perl module but that seems like an awfully big hammer for what I hope is a small problem.

 

I'm hoping that someone knows perl - in particular  LWP::UserAgent and that they can suggest what may be different between my PHP and the original code.  In the perl code the xml filename to send is passed as a command line param, for php I fread the same file since this is not yet production code - same effect (I think).  I've changed the URL to protect the innocent.  Thanks in advance if you can help.  The code follows, perl first, then php:

 

Perl

use strict;
use LWP::UserAgent;
foreach (@ARGV) {
  local *FILE;
  open FILE, "<$_" or die "unable to open file $_: $!";
  local $/ = undef;
  my $xml = <FILE>;
  my $ua = LWP::UserAgent->new;
  $ua->agent("Test");
  my $req = HTTP::Request->new(POST => 'http://some address:some port/some app');
  $req->content_type('text/xml');
  $req->content($xml);
  my $rc = $ua->request($req);
  if ($rc->is_success) {
    print $rc->content;
  }
  else {
    print 'Error: ' . $rc->status_line . "\n";
  }
}

PHP

<?php
$url = "http://someaddress:some port/some app";
$theFile = fopen("RequestDelivery.xml","r");
$post_string= fread($theFile,fileSize("RequestDelivery.xml"));
$header  = "POST HTTP/1.0 \r\n";
$header .= "Content-type: text/xml \r\n";
$header .= "Content-length: ".strlen($post_string)." \r\n";
$header .= "Content-transfer-encoding: text \r\n";
$header .= "Connection: close \r\n\r\n"; 
$header .= $post_string;
echo $header.PHP_EOL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$data = curl_exec($ch); 
if(curl_errno($ch))
    print curl_error($ch);
else
echo $data;
    curl_close($ch);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.