Jump to content

Submitting a Server-Side PHP POST Request


Greywacke
 Share

Recommended Posts

hi,i see i can do this either by using cURL or the fsockopen function, but i don't seem to be getting anywhere. i've been trying various functions made available on the php.net page for the fsockopen function, but i end up getting HTTP 500 errors and what not. there seems to be a huge difference on opinion with regards to implementing this functionality using fsockopen... below is the code i've been using at the moment:

function open_page($url,$f=1,$c=2,$r=0,$a=0,$cf=0,$pd=""){	global $oldheader;	$url = str_replace("http://","",$url);	if (preg_match("#/#","$url")){		$page = $url;		$url = @explode("/",$url);		$url = $url[0];		$page = str_replace($url,"",$page);		if (!$page || $page == ""){			$page = "/";		}		$ip = gethostbyname($url);	}else{		$ip = gethostbyname($url);		$page = "/";	}	$open = fsockopen($ip, 80, $errno, $errstr, 60);	if ($pd){		$send = "POST $page HTTP/1.0\r\n";	}else{		$send = "GET $page HTTP/1.0\r\n";	}	$send .= "Host: $url\r\n";	if ($r){		$send .= "Referer: $r\r\n";	}else{		if ($_SERVER['HTTP_REFERER']){			$send .= "Referer: {$_SERVER['HTTP_REFERER']}\r\n";		}	}	if ($cf){		if (@file_exists($cf)){			$cookie = urldecode(@file_get_contents($cf));			if ($cookie){				$send .= "Cookie: $cookie\r\n";				$add = @fopen($cf,'w');				fwrite($add,"");				fclose($add);			}		}	}	$send .= "Accept-Language: en-us, en;q=0.50\r\n";	if ($a){		$send .= "User-Agent: $a\r\n";	}else{		$send .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";	}	if ($pd){		$send .= "Content-Type: application/x-www-form-urlencoded\r\n"; 		$send .= "Content-Length: " .strlen($pd) ."\r\n\r\n";		$send .= $pd;	}else{		$send .= "Connection: Close\r\n\r\n";	}	fputs($open, $send);	while (!feof($open)) {		$return .= fgets($open, 4096);	}	fclose($open);	$return = @explode("\r\n\r\n",$return,2);	$header = $return[0];	if ($cf){		if (preg_match("/Set\-Cookie\: /i","$header")){			$cookie = @explode("Set-Cookie: ",$header,2);			$cookie = $cookie[1];			$cookie = explode("\r",$cookie);			$cookie = $cookie[0];			$cookie = str_replace("path=/","",$cookie[0]);			$add = @fopen($cf,'a');			fwrite($add,$cookie,strlen($read));			fclose($add);		}	}	if ($oldheader){		$header = "$oldheader<br /><br />\n$header";	}	$header = str_replace("\n","<br />",$header);	if ($return[1]){		$body = $return[1];	}else{		$body = "";	}	if ($c === 2){		if ($body){			$return = $body;		}else{			$return = $header;		}	}	if ($c === 1){		$return = $header;	}	if ($c === 3){		$return = "$header$body";	}	if ($f){		if (preg_match("/Location\:/","$header")){			$url = @explode("Location: ",$header);			$url = $url[1];			$url = @explode("\r",$url);			$url = $url[0];			$oldheader = str_replace("\r\n\r\n","",$header);			$l = "Location:";			$oldheader = str_replace("Location:",$l,$oldheader);			return open_page($url,$f,$c,$r,$a,$cf,$pd);		}else{			return $return;		}	}else{		return $return;	}}// prepare variables$post = $_POST;$arrname = split(" ",$post["contact_name"]);$url = "http://lmx.leads360.com/web/SourcesHtmlForm.aspx?CampaignId=4255&OrgId=6068";	// post action$f = 1;												// 1 for header, 2 for body, 3 for both$c = 2;												// 1 for header, 2 for body, 3 for both$r = "http://lmx.leads360.com/web/SourcesHtmlForm.aspx?CampaignId=4255&OrgId=6068";		// referrer$a = NULL;												// user-agent$cf = NULL;												// cookie file$pd = "firstNameTextBox=".$arrname[0].								// post data      "&lastNameTextBox=".array_slice($arrname,1,count($arrname) - 1).      "&companyTextBox=".      "&address1TextBox=".      "&address2TextBox=".$post["province"].      "&cityTextBox=".$post["city_town"].      "&stateDropDownList=".      "&zipTextBox=".      "&homePhoneTextBox=".      "&workPhoneTextBox=".      "&mobilePhoneTextBox=".$post["contact_cell"].      "&h="."&m="."$t=".      "&emailTextBox=".$post["email"].      "$ssnTextBox=".      "$dateOfBirthTextBox=".      "&control112=".$post["canopy_req"].      "&control113=".$post["canopy_style"].      "&control114=".$post["budget"].      "&control115=".$post["fitment"].      "&control116=".$post["add_reqs"].      "&control329=".$post["vehicle_status"].      "&control330=".$post["vehicle_make_model"].      "&control331=".$post["year_model"].      "&control332=".      "&control334=".      "&control335=".      "&control336=".      "&control337=".      "&control338=".      "&control339=".      "&control340=".      "&control341=".      "&control342=".      "&control343=".      "&control344=".      "&control345=".      "&control346=".      "&control347=".      "&control348=".      "&control349=".      "&control350=".      "&control351=".      "&control352=".      "&control353=";// send post request$page = open_page($url,$f,$c,$r,$a,$cf,$pd);echo $page; 

however, i keep getting the following browser error:

Internal Server ErrorThe server encountered an internal error or misconfiguration and was unable to complete your request.Please contact the server administrator, webmaster@intellisource.performatix.net and inform them of the time the error occurred, and anything you might have done that may have caused the error.More information about this error may be available in the server error log.Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
and the following error descriptions are dumped in the error log, with the last 2 being repeated till the error log size reaches 512mb:
[09-Jun-2010 11:17:15] PHP Warning: fsockopen() [<a href='function.fsockopen'>function.fsockopen</a>]: unable to connect to https::80 (Connection timed out) in /home/dwtphovu/public_html/intellisource.co.za/test_8347379386/private/request_salespages.php on line 313[09-Jun-2010 11:17:15] PHP Warning: fputs(): supplied argument is not a valid stream resource in /home/dwtphovu/public_html/intellisource.co.za/test_8347379386/private/request_salespages.php on line 351[09-Jun-2010 11:17:15] PHP Warning: feof(): supplied argument is not a valid stream resource in /home/dwtphovu/public_html/intellisource.co.za/test_8347379386/private/request_salespages.php on line 352[09-Jun-2010 11:17:15] PHP Warning: fgets(): supplied argument is not a valid stream resource in /home/dwtphovu/public_html/intellisource.co.za/test_8347379386/private/request_salespages.php on line 353
of course the last 3 errors are because the fsockopen function does not manage to pull through. i can't seem to locate any information on fixing this issue, perhaps the server is behind a proxy to access internet outside that network? i have been working on this and googling trying to find a solution since monday, but i cannot seem to get it to work.any ideas people?i have absolutely no idea how to do this with cURL and the internet is without results, at least for my search queries... (kinda makes me feel dumb :)) :) Edited by Pierre 'Greywacke' du Toit
Link to comment
Share on other sites

HTTPS does not operate on port 80, it typically uses 443. That's why it's not able to connect. In order to stop those errors and the infinite while loop producing them you can check to see if the socket was successfully opened before trying to do anything else.I'm wondering about this message though:unable to connect to https::80I wonder if that's the entire URL it's trying to connect to. It will probably be worthwhile to print everything out and verify what the code is doing.

Link to comment
Share on other sites

well, thats the thing - see how the url is specified for the call - i have no idea where that error comes from. i am trying to connect over http on port 80.i will start printing out what the code is doing, solong.

Link to comment
Share on other sites

well the client has been pressing on the urgency of this matter, and it's debugging the previous method vs. learning to navigate cURL functions vs the following function:

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;}

i will attempt this one instead.

Edited by Pierre 'Greywacke' du Toit
Link to comment
Share on other sites

Maybe this will help....a basic example of using cURL to POST an SMS message to a form:

$phoneNumber = '4255551212';$message = 'Sample message generated by curl and php';$curlPost = 'pNUMBER='  . urlencode($phoneNumber) . '&MESSAGE=' . urlencode($message) . '&SUBMIT=Send';$ch = curl_init();curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/send_sms.php');curl_setopt($ch, CURLOPT_HEADER, 1);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);$data = curl_exec();curl_close($ch);

Link to comment
Share on other sites

not using sms'that function that i am trying works - only the server side handlers are a bit messed up.i keep getting response as "Duplicate" when emulating the HTML forms they provide.tried the form on www.leads360.com, and i get the following html:

<html>    <head>        <title>Object reference not set to an instance of an object.</title>        <style>         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}          p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }         pre {font-family:"Lucida Console";font-size: .9em}         .marker {font-weight: bold; color: black;text-decoration: none;}         .version {color: gray;}         .error {margin-bottom: 10px;}         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }        </style>    </head>    <body bgcolor="white">            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>            <h2> <i>Object reference not set to an instance of an object.</i> </h2></span>            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.            <br><br>            <b> Exception Details: </b>System.NullReferenceException: Object reference not set to an instance of an object.<br><br>            <b>Source Error:</b> <br><br>            <table width=100% bgcolor="#ffffcc">               <tr>                  <td>                      <code><pre>Line 25:             base.OnInit(e);Line 26:             Page.ClientScript.RegisterClientScriptResource(typeof(FieldItemDropDownList), "Leads360.Express.WebControls.Controls.js");<font color=red>Line 27:             this.BuildForm(this.CurrentOrg.Sector, placeHolder);</font>Line 28:         }Line 29: </pre></code>                  </td>               </tr>            </table>            <br>            <b> Source File: </b> c:\Inetpub\wwwroot\Express\Web\SourcesHtmlForm.aspx.cs<b>    Line: </b> 27            <br><br>            <b>Stack Trace:</b> <br><br>            <table width=100% bgcolor="#ffffcc">               <tr>                  <td>                      <code><pre>[NullReferenceException: Object reference not set to an instance of an object.]   Leads360.Express.Web.SourcesHtmlForm.OnInit(EventArgs e) in c:\Inetpub\wwwroot\Express\Web\SourcesHtmlForm.aspx.cs:27   System.Web.UI.Control.InitRecursive(Control namingContainer) +321   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +834</pre></code>                  </td>               </tr>            </table>            <br>            <hr width=100% size=1 color=silver>            <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.1873; ASP.NET Version:2.0.50727.1433            </font>    </body></html><!-- [NullReferenceException]: Object reference not set to an instance of an object.   at Leads360.Express.Web.SourcesHtmlForm.OnInit(EventArgs e) in c:\Inetpub\wwwroot\Express\Web\SourcesHtmlForm.aspx.cs:line 27   at System.Web.UI.Control.InitRecursive(Control namingContainer)   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)[HttpUnhandledException]: Exception of type 'System.Web.HttpUnhandledException' was thrown.   at System.Web.UI.Page.HandleError(Exception e)   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)   at System.Web.UI.Page.ProcessRequest()   at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)   at System.Web.UI.Page.ProcessRequest(HttpContext context)   at ASP.web_sourceshtmlform_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\8f766d84\170faff6\App_Web_vzsyz8nv.0.cs:line 0   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)--><!-- This error page might contain sensitive information because ASP.NET is configured to show verbose error messages using <customErrors mode="Off"/>. Consider using <customErrors mode="On"/> or <customErrors mode="RemoteOnly"/> in production environments.-->

this is probably due to this field being omitted, but how would i send a value containing an = or & in a post str? guessing urlencode...

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMjA4ODgwMjIyD2QWAgIDD2QWBAIDD2QWBAIDD2QWAgIBDxYCHgRUZXh0BUtodHRwOi8vbG14LmxlYWRzMzYwLmNvbS93ZWIvU291cmNlc0h0bWxGb3JtLmFzcHg/Q2FtcGFpZ25JZD00MjU1Jk9yZ0lkPTYwNjhkAh0PEA8WBh4NRGF0YVRleHRGaWVsZAUFVGl0bGUeDkRhdGFWYWx1ZUZpZWxkBQVUaXRsZR4LXyFEYXRhQm91bmRnZBAVPAwtLSBTZWxlY3QgLS0CQUsCQUwCQVICQVoCQkMCQ0ECQ08CQ1QCREMCREUCRkwCR0ECSEkCSUECSUQCSUwCSU4CS0ECS1MCS1kCTEECTUECTUICTUQCTUUCTUkCTU4CTU8CTVMCTVQCTkMCTkQCTkUCTkgCTkoCTk0CTlYCTlkCT0gCT0sCT04CT1ICUEECUFICUkkCU0MCU0QCVEUCVE4CVFgCVUsCVVQCVkECVkMCVlQCV0ECV0kCV1YCV1kVPAACQUsCQUwCQVICQVoCQkMCQ0ECQ08CQ1QCREMCREUCRkwCR0ECSEkCSUECSUQCSUwCSU4CS0ECS1MCS1kCTEECTUECTUICTUQCTUUCTUkCTU4CTU8CTVMCTVQCTkMCTkQCTkUCTkgCTkoCTk0CTlYCTlkCT0gCT0sCT04CT1ICUEECUFICUkkCU0MCU0QCVEUCVE4CVFgCVUsCVVQCVkECVkMCVlQCV0ECV0kCV1YCV1kUKwM8Z2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZGQCBQ8UKwADZGUFCDAwMDEuMS4xZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18WAQUIY2FsZW5kYXLm6W6MSvDTvXRCpZOUkHZMau8+aw==" />

Link to comment
Share on other sites

this issue has been resolved - that last bit of code works. turned out the Ref Id hidden field was to be left as a space, my client tried to insert the lead id there... :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...