Reputation: 53
I am using a simple HTML form to send http post request in this format: key1=value1&key2=value2&key3=value3&key4=value4&key5=value5
and i am trying to save the http post data into a text file using PHP
This is the PHP code I came up with:
$data1 = $_POST['key1'] ;
$data2 =$_POST['key2'] ;
$data3 =$_POST['key3'] ;
$data4 =$_POST['key4'];
$data5 =$_POST['key5'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $_POST['data1'], $_POST['data2'], $_POST['data3'], $_POST['data4'], $_POST['data5']);
fclose($fp);
but its only creating the file "data.txt" and not adding any of the values into the text file
What am I doing wrong?
Upvotes: 1
Views: 960
Reputation: 61839
Change
fwrite($fp, $_POST['data1'], $_POST['data2'], $_POST['data3'], $_POST['data4'], $_POST['data5']);
To
fwrite($fp, "$data1,$data2,$data3,$data4,$data5");
All those "data" variables you defined are individuals, they aren't part of the $_POST array.
And fwrite expects a single string of data not a set of separate ones, so you need to concatenate them together. I put commas between them so you've got some chance of telling them apart but obviously you can change it to suit your requirements. Documentation: https://www.php.net/manual/en/function.fwrite.php
P.S. if your variables are being sent in the URL querystring (rather than the body of the request) then you need to use $_GET to retrieve them instead, like this:
$data1 = $_GET['key1'];
$data2 = $_GET['key2'];
$data3 = $_GET['key3'];
$data4 = $_GET['key4'];
$data5 = $_GET['key5'];
Upvotes: 0
Reputation: 38
Query string parameters should be accessed with $_GET
, even if the request method is POST.
Also, indexes data1
, data2
, data3
, data4
, and data5
don't exist in request.
fwrite
accepts at most 3 arguments.
Final code should be like this:
<?php
$data1 = $_REQUEST['key1'];
$data2 = $_REQUEST['key2'];
$data3 = $_REQUEST['key3'];
$data4 = $_REQUEST['key4'];
$data5 = $_REQUEST['key5'];
$fp = fopen('data.txt', 'a');
fwrite($fp, implode("\n", [$data1, $data2, $data3, $data4, $data5]));
fclose($fp);
Upvotes: 1