Welcome to PHP Smarty Q&A, where you can ask programmaing questions and receive answers from other members of the community for PHP, Smarty, MYSQL related. You can also share or save your scripts in this repository for future reference.
Bulk SMS Marketing

PHP Writing received HTTP requests to a file and then Inserting them to MySQL Database

+1 vote
I have a project where I need to receive HTTP requests and then insert them to mysql database. By looking at the code in my own answer below, you will come to know about the process.
asked Sep 4, 2016 in PHP by anonymous

1 Answer

+1 vote
Best answer

With the following code, just copy and insert each request in a new line as url parameter.

	foreach($_REQUEST as $key => $value){
		$requestarray .= $key.'='.urlencode($value).'&';

	$requestarray = substr($requestarray, 0, -1)."\r\n";
	file_put_contents("myfile.txt", $requestarray, FILE_APPEND );


Now you can read that file and insert them into your mysql database.

	//include your dbconfig file here
	//http parameters will be receiving as follow
	$filename = "myfile.txt";
	$tablename = "my_test_table";
	$readfile = fopen($filename, "r");
		if (flock($readfile, LOCK_EX)){
			while (($line = fgets($readfile)) !== false){
				parse_str($line, $get_array);
				$sql = "INSERT INTO `".$tablename."` 
					(`external_id` ,`delivery_ts` ,`delivery_status` , `cause` , `grpname` , `mobile_no`, `delivery_date`) VALUES ";
				$ValuesArr = array();
				foreach((array($get_array)) as $row){
					if($row['externalId'] != ''){
						$process = true;
						$externalid_server = safepost($row['externalId']);
						$deliveredTS = safepost($row['deliveredTS']);
						$status_delivery = safepost($row['status']);
						$cause = safepost($row['cause']);
						$rphone = safepost($row['phoneNo']);
						$phoneNo = substr($rphone, -10);
						$grpName = safepost($row['grpName']);
						$ValuesArr[] = "(	".$conn->qstr($externalid_server).", 
											'".date("Y-m-d H:i:s")."' )";				
					} else {
						$process = false;
				$sql .= implode(',', $ValuesArr);
					//echo $sql."<br>";
					//$id = $conn->Insert_ID();
					//echo $id."<br>";
			ftruncate($readfile, 0);
			flock($readfile, LOCK_UN);
			file_put_contents($filename, $readfile);
	} else {
		echo " error opening the file.";


Hope this helps someone in the near future.

answered Sep 4, 2016 by anonymous
selected Sep 4, 2016 by robert