Avatar of intellisource
intellisourceFlag for South Africa asked on

emulating form post via php backend. what is wrong with new environment?

hi there,
i have the following document C on Server C, to capture the data and send off to document A on Server A via a post request, as well as document B on Server B. the do_post_request is without curl, and is shared here: HTTP POST from PHP, without cURL
<?php
// required functions
function do_post_request($url, $data, $optional_headers = null) {
	$params = array('http' => array(
			'method' => 'post',
			'content' => $data
		)
	);
	if ($optional_headers!== null) {
		$params['http']['header'] = $optional_headers;
	}
	$ctx = stream_context_create($params);
	$fp = @fopen($url, 'rb', false, $ctx);
	if (!$fp) {
		throw new Exception("Problem with $url, $php_errormsg");
	}
	$response = @stream_get_contents($fp);
	if ($response === false) {
		throw new Exception("Problem reading data from $url, $php_errormsg");
	}
	return $response;
}
// emulate form submissions to leads 360 and intellisource
$url = "http://www.intellisource.co.za/999_andycabenquiries.php";		// intellisource request
$data = "name=".$_POST["name"].											// First Name
		"&surname=".$_POST["surname"].									// Last Name
		"&email=".$_POST["email"].										// Email
		"&textfield32=".$_POST["textfield32"].							// Phone
		"&cellphone=".$_POST["cellphone"].								// Cellphone
		"&message=".$_POST["message"];									// Message
$ret = do_post_request($url,$data);										// post intellisource request id
echo $ret;																// print intellisource return value
$url  = "https://secure.leads360.com/Import.aspx?Provider=Vertical".	// leads 360 url
		"Masters-Other&Client=LMX-9014&CampaignId=7075";
$data = "Ref Id= ".														// Lead Provider ID
		"&First Name=".$_POST["name"].									// First Name
		"&Last Name=".$_POST["surname"].								// Last Name
		"&Email=".$_POST["email"].										// Email
		"&Home Phone=".$_POST["textfield32"].							// Home Phone
		"&Work Phone=".$_POST["textfield32"].							// Work Phone
		"&Mobile Phone=".$_POST["cellphone"].							// Mobile Phone
		"&Message=".$_POST["message"].									// Message
		"&AndyCab ID=".$ret;											// add andycab id retrieved from intellisource
$ret = do_post_request($url,$data);										// post leads 360 request
echo $ret;																// print leads 360 return value
?>

Open in new window

now with the current configuration of server A, this code works posting to both server A and server B when testing from server A - but with the unknown configuration of server C, i need to figure out why i am getting the following exception and if there is a way to get any more details when running. the response on server C:
<br />
<b>Fatal error</b>:  Uncaught exception 'Exception' with message 'Problem with http://www.intellisource.co.za/999_andycabenquiries.php, ' in /usr/www/users/andyca/intellisourceleads360.php:15
Stack trace:
#0 /usr/www/users/andyca/intellisourceleads360.php(35): do_post_request('http://www.inte...', 'name=Pierre&amp;sur...')
#1 /usr/www/users/andyca/form.php(5): include_once('/usr/www/users/...')
#2 {main}
  thrown in <b>/usr/www/users/andyca/intellisourceleads360.php</b> on line <b>15</b><br />

Open in new window

the A server is www.intellisource.co.za which is on an Apache 2.2.19 machine.
the B server is www.leads360.co.za which seems to be on an IIS machine.
the C server is www.andycab.co.za which is on an Apache 2.2.9 machine.
server A posts to server B and itsself, but server C does not post to either it seems.
document A which captures the data, and inserts into a database table, is the following:
<?php
$GLOBALS["sql"] = array();
$conn = mysql_connect("localhost", "dwtphovu_f3rr37y", "JapieMySkapie101");
if (!$conn) {
	$err = "ERROR #".mysql_errno()."Could not connect: ".mysql_error()." in ".$doc." on Line ".$line;
	array_push($GLOBALS["sql"],$err);
}
mysql_select_db("dwtphovu_8347379386_prod", $conn);
function mysql_query_errors($sql, $conn, $doc, $line, $expret = false) {
	$line--;
	$err = "";
	$result = mysql_query($sql);
	if (mysql_errno() > 0) {
		$err = "ERROR #".mysql_errno().": ".mysql_error()." in ".$doc." on Line ".$line;
	} elseif ($expret) {
		if (is_null($result)) {
			$err = "NOTICE #0504: A null value was returned by the query defined in ".$doc." on line ".$line--;
		} elseif ($result === false) {
			$err = "NOTICE #0502: A false value was returned by the query defined in ".$doc." on line ".$line--;
		} elseif ($result === true) {
			$err = "NOTICE #0501: A true value was returned by the query defined in ".$doc." on line ".$line--;
		} elseif (mysql_num_rows($result) < 1) {
			$err = "NOTICE #0500: An empty result set was returned by the query defined in ".$doc." on line ".$line--;
		}
		array_push($GLOBALS["sql"],$sql."\n",$err."\n");
	}
	return $result;
}
/* **************************************************************************************************
function str_in_array($haystack, $needle, $sw = 1) {
    foreach ($haystack as $value[0] => $value[1]) {
        if (stristr($value[$sw],$needle)!==FALSE) {
            return true;
        }
    }
    return false;
}
// get table fields to compare with form
$existing = array();
$tsql = "SHOW COLUMNS FROM dwtphovu_8347379386_prod.999_andycabenquiries;";
$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);
if ($result) {
	while ($row = mysql_fetch_assoc($result)) {
		if ($row["Field"] != "bigint_EnquiryID") {
			array_push($existing,$row["Field"]);
		}
	}
}
echo "\$existing = ".print_r($existing,true)."<br>";
// alter table to add new fields if found
$tocreate = array();
foreach ($_POST as $key=>$value) {
	if ($key != "Reset" &&
		$key != "Submit2" &&
		!str_in_array($existing,$key)) {
		array_push($tocreate,ucfirst($key));
	}
}
echo "\$tocreate = ".print_r($tocreate,true)."<br>";
foreach ($tocreate as $key=>$value) {
	$asql = "ALTER TABLE 
				dwtphovu_8347379386_prod.999_andycabenquiries 
			 ADD 
				`text_Enquiry".$value."` 
				TEXT CHARACTER SET utf8 
				COLLATE utf8_unicode_ci 
				NULL 
				DEFAULT NULL 
				COMMENT 'Enquiry ".$value."',
			  ADD FULLTEXT 'FULLTEXT' (
				`text_Enquiry".$value."`
			 )";
	$result = mysql_query_errors($asql, $conn, __FILE__, __LINE__);
}
echo print_r($GLOBALS["sql"],true);
************************************************************************************************** */
// insert new record
$tsql = "INSERT INTO 
			 dwtphovu_8347379386_prod.999_andycabenquiries 
		 (
			 text_EnquiryName, 
			 text_EnquirySurname, 
			 text_EnquiryEmail, 
			 text_EnquiryPhone, 
			 text_EnquiryCellPhone, 
			 text_EnquiryMessage
		 ) VALUES (
			\"".mysql_real_escape_string($_POST["name"])."\", 
			\"".mysql_real_escape_string($_POST["surname"])."\", 
			\"".mysql_real_escape_string($_POST["email"])."\", 
			\"".mysql_real_escape_string($_POST["textfield32"])."\", 
			\"".mysql_real_escape_string($_POST["cellphone"])."\", 
			\"".mysql_real_escape_string($_POST["message"])."\"
		 );";
$result = mysql_query_errors($tsql, $conn, __FILE__, __LINE__);
echo (count($GLOBALS["sql"]))?implode("\n",$GLOBALS["sql"]):mysql_insert_id($conn);

Open in new window

document B is a third party lead manager.
PHPWeb DevelopmentApache Web Server

Avatar of undefined
Last Comment
intellisource

8/22/2022 - Mon
gr8gonzo

Out of curiosity, have you tried using cURL to do your post? It's pretty much the standard way that most developers use to do POSTs to other servers, and it handles a lot of the escaping and all that stuff for you (and will throw less cryptic / confusing error messages).
ASKER CERTIFIED SOLUTION
intellisource

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
intellisource

gr8gonzo: i need to resolve this issue without cURL - as various hosts do not always have it enabled.
Ray Paseur

gr8gonzo is giving you good advice here.  You are not using "various hosts" - you're using your own specific hosts.  Use phpinfo() to see if CURL is enabled.  Then if it is, you will have an easy solution.

Or you might try to use fsockopen() as shown in this teaching example.  The data base stuff may be extraneous for your work, but I like to keep a log of things like this.

HTH, ~Ray
<?php // RAY_post_repost_with_fsockopen.php
error_reporting(E_ALL);



// IF NOTHING IS POSTED YET, PUT UP THE HTML FORM TO RECEIVE THE DATA
if (empty($_POST))
{ ?>
   <form method="post">
   ENTER TWO THINGS:
   <input name="foo" />
   <input name="bar" />
   <br/><input type="submit" />
   </form>
   <?php die();
}



// THE EMAIL ADDRESS WE WANT TO SEND TO
$my_email = 'Ray.Paseur@Gmail.com';

// THE SITE WE WANT TO TALK TO - IN THIS CASE, TO MY SITE
$server_url  = "www.your.org";
$server_url  = $_SERVER["HTTP_HOST"];

// THE PAGE INSIDE THE WEB SITE
$request_uri = "/RAY_dump_superglobals.php";

// CONSTRUCT THE SQL STATEMENT
$sql = 'INSERT INTO mytable ( ';
$sql_keys = '';
$sql_vals = '';

// CONSTRUCT THE SQL AND POST STRINGS
$postdata  = '';
foreach ($_POST as $key => $val)
{
    $postdata .= '&' . $key . '=' . urlencode(stripslashes($val));
    $sql_keys .= "`$key`,";
    $sql_vals .= "`$val`,";
}
$postdata = ltrim($postdata, '&');
$sql_keys = rtrim($sql_keys, ',');
$sql_vals = rtrim($sql_vals, ',');
$sql      = $sql . $sql_keys . ' ) VALUES ( ' . $sql_vals . ') ';

// SEND THE EMAIL
mail ($my_email, 'POST STUFF', $sql);

// UPDATE THE DATA BASE HERE
// $res = mysql_query($sql), ETC ETC ETC


// CONSTRUCT THE HEADERS FOR THE RE-POST
$header = '';
$header .= "POST $request_uri HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($postdata) . "\r\n\r\n";

// SHOW WHAT WE ARE GOING TO DO (REMOVE THIS SEGMENT FOR A LIVE SYSTEM)
echo "<pre>\n";
echo "REQUEST DATA FOLLOWS:\n";
var_dump($server_url);
var_dump($request_uri);
var_dump($postdata);
var_dump($header);
echo "</pre>\n";


// OPEN THE SOCKET TO THE PAGE
$fp = fsockopen ($server_url, 80, $errno, $errstr, 30);

// TEST FOR VERIFICATION
if (!$fp)
{
    die("HTTP ERROR $server_url $request_uri fsockopen() FAILED ERRNO=$errno ERRSTR=$errstr");
}

// HTTP OPEN - WRITE HEADER AND REQUEST
fputs ($fp, $header . $postdata);

// HTTP OPEN - READ RESPONSE
$reply = '';
while (!feof($fp))
{
    $reply .= fgets($fp, 1024);
}

// SEE WHAT THE FOREIGN SITE SAID
echo "<pre>\n";
echo htmlentities($reply);
echo "</pre>\n";

// FINIS
echo 'Done!';
?>

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
gr8gonzo

Sorry for my late response. I didn't expect you to respond that quickly. I realize that not all hosts have cURL enabled, but I've worked on most of the major ones over the years with different clients and the majority of them do support cURL (otherwise it wouldn't be quite as popular of an extension as it is).

That said, Ray covered the non-cURL approach.

I would also recommend that you not post your database connection info (user and pass). Keep in mind that these answers can be viewable by non-experts who are just googling for their own answers, so there's a chance your information could fall into the wrong hands.
ASKER
intellisource

thing is, the posting of the leads360 form works, thus nothing is wrong with that function i am using. the issue clearly seems to be with the intellisource host however, who does not accept post requests from domains outside their network. the issue seems to be in the process of being resolved. there are 3 different hosts being used here, only two are Apache with php (server A and C) - the other is IIS with asp (server B). we only have a choice of host with server A. Server C is our client, and server B is a third party lead management system.