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
132 views
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.

<?php
	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.

<?php
	set_time_limit(10);
	//include your dbconfig file here
	
	//http parameters will be receiving as follow
	//externalId=6515616165165165&deliveredTS=1466655840000&status=SUCCESS&cause=SUCCESS&phoneNo=98*********&grpName=&errCode=000
	
	$filename = "myfile.txt";
	$tablename = "my_test_table";
	
	$readfile = fopen($filename, "r");
	if($readfile){
		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).", 
											".$conn->qstr($deliveredTS).", 
											".$conn->qstr($status_delivery).", 
											".$conn->qstr($cause).", 
											".$conn->qstr($grpName).", 
											".$conn->qstr($phoneNo).", 
											'".date("Y-m-d H:i:s")."' )";				
					} else {
						$process = false;
					}
				}
				$sql .= implode(',', $ValuesArr);
				if($process){
					//echo $sql."<br>";
					$conn->Execute($sql);
					//$id = $conn->Insert_ID();
					//echo $id."<br>";
				}
			}
			ftruncate($readfile, 0);
			rewind($readfile);
			flock($readfile, LOCK_UN);
			fclose($readfile);
			unset($readfile);
			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
...