Null value written to JSON file with PHP - php

EDITED
Problem - A null value is written to the JSON file after the function runs.
Expectation - Capture data entered into HTML form, append it to an existing JSON file.
Some of the Stack resources I've used:
How do I extract data from JSON with PHP?
How to loop through JSON array using PHP
how to write a json file as a datasource in php?
How to Append JSON File in PHP?
How to add to json array in .json file with php
How can I write data in local JSON file using jQuery?
My JSON file looks like this:
{
"records": [
{"Date":"05/04/2016","Miles":168081,"Gallons":11.003,"Cost":28.60,"MPG":24.1,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"07:04"},
{"Date":"04/18/2016","Miles":167815,"Gallons":10.897,"Cost":27.23,"MPG":25.7,"Street":"5500 Mirage St","City":"Yorba Linda","State":"CA","Zip":92807,"Time":"15:46"}
],
"error" : false,
"status" : 200
}
EDITED - My PHP script looks like this (update implements Chay's code):
<?php
function runMyFunction() {
// #####
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file2.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file2.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
$formattedData = json_encode($formattedData);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = json_encode($data);
}
//Set a parent key
$records['records'] = $formattedData;
//Overwites everything
/* $handle = fopen($filename,'a+');
fwrite($handle,$records);
fclose($handle); */
file_put_contents($filename,$records, FILE_APPEND | LOCK_EX);
print_r($formattedData);
echo 'OK: ' . '<BR>' . $records . '<BR>';
}
// #####
}//end runMyFunction
/*
if (isset($_GET['hello'])) {
runMyFunction();
} */
if(isset($_POST['mpg_date'],$_POST['mpg_date'],$_POST['mpg_miles'],$_POST['mpg_gallons'],$_POST['mpg_cost'],$_POST['mpg_mpg'],$_POST['mpg_street'],$_POST["mpg_city"],$_POST['mpg_state'],$_POST['mpg_zip'],$_POST['mpg_time'])) {
runMyFunction($_POST);
}
?>
An excerpt of the HTML form looks like this:
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_miles" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<a href='_process.php?hello=true'>Run PHP Function</a>
</div>
</form>

I'm sure that your submission doesn't POST something since you're using anchor (without any javascript) to submit. In the other word, notice I change it to <button>.
<form action="_process.php" method="POST" role="form">
<div class="form-group">
<label for="mpg_date">Fuel Date:</label>
<input type="text" class="form-control" id="mpg_date" name="mpg_date" placeholder="04/18/2016">
</div>
<div class="form-group">
<label for="mpg_miles">Odometer (Miles):</label>
<input type="number" min=”0″ step="any" class="form-control" id="mpg_miles" name="mpg_num" placeholder="167815">
</div>
<!-- And so on... -->
<div>
<button type="submit" role="button">Run PHP Function</button>
</div>
</form>
If you also noticed I also changed the second input name above to mpg_num. And this should be your backend looks.
...
...
if(isset($_POST['mpg_date'], $_POST['mpg_num'])) {
runMyFunction($_POST);
}
Updated
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && !isset($_POST)) { //You may add $_POST[post_name] for validation
die('I need post method!');
}
// check if file exists
$filename = 'mpg-data-file.json';
if ( ! file_exists($filename) ) {
echo 'ERROR:' . $filename . ' not found' . '<BR>';
} else {
echo 'OK: ' . $filename . ' exists.' . '<BR>';
$data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
//Load data from json file
$dataFile = file_get_contents("mpg-data-file.json");
$dataFile = json_decode($str_data,true);
//Merge data from post with data from file
$formattedData = array_merge($dataFile['records'],$data);
//If data from file is empty, just use data from post
if (empty($dataFile)) {
$formattedData = $data;
}
//Set a parent key
$records['records'] = $formattedData;
$records['error'] = false;
$records['status'] = 200;
$records = json_encode($records);
//Overwites everything
$handle = fopen($filename,'w+');
fwrite($handle,$records);
fclose($handle);
print_r($records);
}
I hope this won't consume your environment RAM alot :)

This:
<a href='_process.php?hello=true'>Run PHP Function</a>
will actually submit your form. When you just link to the script that way rather than submitting the form, none of the $_POST values will be set.
It looks like your form just needs a submit button. You can put '_process.php?hello=true' into the form action if you want the if (isset($_GET['hello'])) { check to work.
In other words:
<form action="_process.php?hello=true" method="POST" role="form">
<!-- All your inputs, etc. ...-->
<input type="submit" value="Run PHP Function">
</form>
In order to append the new data to your existing JSON, you'll need to change the order that things happen in your function. The else part should be like this:
// First get the existing JSON from the file and decode it
$str_data = file_get_contents("mpg-data-file.json"); // Get the JSON string
$data = json_decode($str_data,true);// json_decode expects the JSON data, not a file name
// Then create a new data array from the $_POST data and add it to the 'records' key
$new_data = array(
"Date"=> $_POST['mpg_date'],
"Miles"=> $_POST['mpg_miles'],
"Gallons"=> $_POST['mpg_gallons'],
"Cost"=> $_POST['mpg_cost'],
"MPG"=> $_POST['mpg_mpg'],
"Street"=> $_POST['mpg_street'],
"City"=> $_POST["mpg_city"],
"State"=> $_POST['mpg_state'],
"Zip"=> $_POST['mpg_zip'],
"Time"=> $_POST['mpg_time']
);
$data['records'][] = $new_data;
// Then re-encode the JSON and write it to the file
$formattedData = json_encode($data);//format the data
$handle = fopen($filename,'w+');//open or create the file
fwrite($handle,$formattedData);//write the data into the file
fclose($handle);//close the file
print_r($data);

Related

Open php file, change value for one variable, save

I am trying to modify the value of a variable $denumire produs=' '; from a php file _inc.config.php through a script by this code with form from file index.php and i have some errors.
The new value of the variable will become value entered from the keyboard via the form.
Anyone can help me, please?
<?php
if (isset($_POST['modify'])) {
$str_continut_post = $_POST['modify'];
if (strlen($_POST['search']) > 0 || 1==1) {
$fisier = "ask003/inc/_inc.config.php";
$fisier = fopen($fisier,"w") or die("Unable to open file!");
while(! feof($fisier)) {
$contents = file_get_contents($fisier);
$contents = str_replace("$denumire_produs =' ';", "$denumire_produs ='$str_continut_post';", $contents);
file_put_contents($fisier, $contents);
echo $contents;
}
fclose($fisier);
die("tests");
}
}
?>
<form method="POST" action="index.php" >
<label>Modifica denumire baza de date: </label>
<input type="text" name="den">
<button type="submit" name="modify"> <center>Modifica</center></button>
</div></div>
</form>
This is an XY problem (http://xyproblem.info/).
Instead of having some sort of system that starts rewriting its own files, why not have the file with the variable you want to change load a json config file?
{
"name": "Bob",
"job": "Tea Boy"
}
Then in the script:
$json = file_get_contents('/path/to/config.json');
$config = json_decode($json, true);
$name = $config['name'];
Changing the values in the config is as simple as encoding an array and putting the json into the file.
$config['denumireProdu'] = 'something';
$json = json_encode($config);
file_put_contents('/path/to/config.json', $json);
This is far saner than getting PHP to rewrite itself!
Docs for those commands:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.file-get-contents.php
http://php.net/manual/en/function.file-put-contents.php

How to make a textbox form redeem a promocode form a text file in php?

How to make a textbox form redeem a promo code form a text file in php i cant seem to figure it out it's for my csgo gambling site i want them redeem to redeem codes that comes from a text file /promo/codes.txt and make it so they can just use any codes from the list in the text file but im to useless :(
It depends totally on the format of the file.
Example:
ZQC01
ZQR92
ZQA84
ZQD73
To check if a promotion code is in this file and remove it afterwards:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$myPromoCode = isset($_POST['promocode']) ? $_POST['promocode'] : false;
$contents = file_get_contents('/path/to/file.txt');
$promoCodes = explode("\n", $contents);
// Check if the promo code is present in the file
if ($myPromoCode && in_array($myPromoCode, $promoCodes)) {
// Find the corresponding key
$key = array_search($myPromoCode, $promoCodes);
// Remove the code
unset($promoCodes[$key]);
// Write coes back to file
$contents = implode("\n", $promoCodes);
file_put_contents('/path/to/file.txt', $contents);
} else {
die("Promotion code doesn't exist");
}
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="promocode" />
<button type="submit">Redeem</button>
</form>

Not generating and downloading HTML table data in CSV file in PHP with "header already added" error

Dear Fellow PhP Experts,
I am writing below code to export HTML table data in PHP.
Its working nicely in localhost. However, when I deployed to the domain, there is warning-
'Warning: Cannot modify header information - headers already sent by
(output started at ../result_month.php:64 //dbconnect.php line//) in
../result_month.php on line 77 //header("Location: $FileName") line//'.
Seeking suggestion from you, what I am exactly doing wrong.
<?php require_once('dbconnect.php'); ?>
<?php
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
?>
<?php //I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>
Any content without PHP open tag are treated as HTML, sent as HTTP_BODY.
HTTP_BODY will be sent after HTTP_HEADER was closed.
Try these codes:
<?php
require_once('dbconnect.php');
//To generate report, home page added below data to query desired information.
$month=$_POST["themonth"];
$year=$_POST["theyear"];
//I am not intended to redirect to new page when pressing export button
if(isset($_POST["export"]))
{
//as i am in the same page, need to generate query string again, that is why kept this month and year in hidden inputs
$month_visit=$_POST["selected_month"];
$year_visit=$_POST["selected_year"];
$FileName = "data_" . $month_visit . "_" . $year_visit . ".csv";
// WARNING : Uncomment this will cause header() call failed.
//echo "THIS IS HTTP_BODY";
header("Location: $FileName"); //its showing error in this line
$output = fopen($FileName, 'w');
// output the column headings
fputcsv($output, array('ID', 'Name'));
// fetch the data
$query_string = "SELECT ID, Name from Participant";
$rows = mysql_query($query_string);
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows))
fputcsv($output, $row);
fclose($output);
}
?>
<form method="post"> // added this form at the top of HTML table to add export button
<input type="hidden" name="selected_year" value="<?php echo $year; ?>">
<input type="hidden" name="selected_month" value="<?php echo $month; ?>">
<input type="submit" name="export" value="Export to CSV" />
</form>
<?php
$result = mysql_query("SELECT ID, Name from Participant");
echo "displaying query data in html table";
?>

PHP, using $_FILES and $_POST at the same time

I have a problem in using $_FILES and $_POST at the same the because I have a form to upload an image and some data bus when I use one of them it works but when I used the other one id doesn't work.
my code is :
<?php
include 'debugging.php';
//phpinfo();
echo '<br />';
echo '<h1>Image Upload</h1>';
//create a form with a file upload control and a submit button
echo <<<_END
<br />
<form method='post' action='uplaodex.php' enctype='multipart/form-data'>
Select File: <input type='file' name='picName' size='50' />
name: <input type='text' name='usName' size='50' />
username : <input type='text' name='usUsername' size='50' />
pass: <input type='password' name='usPass' size='50' />
email: <input type='text' name='usEmail' size='50' />
<br />
<input type='submit' value='Upload' />
<input type="hidden" name="submit" value="1" />
</form>
<br />
_END;
//above is a special use of the echo function - everything between <<<_END
//and _END will be treated as one large echo statement
//$_FILES is a PHP global array similar to $_POST and $_GET
if (isset($_FILES['picName'])and isset($_POST['submit'])) {
//we access the $_FILES array using the name of the upload control in the form created above
//
//create a file path to save the uploaded file into
$name = "images//" . $_FILES['picName']['name']; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if (move_uploaded_file($_FILES['picName']['tmp_name'], $name)) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
//we are going to store the file type and the size so we get that info
$type = $_FILES['picName']['type'];
$size = $_FILES['picName']['size'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//select the ID of the image just stored so we can create a link
//display success message
echo "<h1> Thankyou </h1><p>Image stored successfully</p>";
//this above line of code displays the image now stored in the images sub directory
echo "<p>Uploaded image '$name'</p><br /><img src='$name' height='200' width='200'/>";
//create alink to the page we will use to display the stored image
echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
} else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
}
} else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
echo "</body></html>";
?>
I don't know what is the problem, any help??
Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit'])) doesn't work because the superglobal $_FILES is probably not having a key named picName. To check this out, try var_dump-ing the $_FILES, like var_dump($_FILES);
By the output of the var_dump you'd get to know if there is any content inside $_FILES. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On in the ini file for php.
Hope it helps!
You have to validate the size of the file if you want to do an isset. I don't know if this is works, but the better way for do that is check first the size for validate if isset or was send to the server.
Then, in your <form method='post' action='uplaodex.php' enctype='multipart/form-data'> you have to create another PHP file with the name uplaodex.php where you'll send al the data. So, your code with be like the below code following and considering the step 1. This will be your uploadex.php
$name_file = $_FILES['picName']['name'];
$type = $name_file['type'];
$size = $name_file['size'];
$tmp_folder = $name_file['tmp'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
if ( $size > 0 ) {
//REMOVE another slash images//
$name = "images/" . $name_file; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if ( move_uploaded_file($tmp_folder, $name) ) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//USE PRINTF
printf('<h1> Thankyou </h1><p>Image stored successfully</p><br>
<p>Uploaded file: %s</p>. <img src="%s" height="200" width="200" />',
$name_file, $name );
#WHAT IS $fileId? In which moment was define?
//echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
}
else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
} //ENDIF OF if (move_uploaded_file($_FILES['picName']['tmp_name'], $name))
} //ENDIF OF if ( $size > 0 )
#ELSE OF YOUR if ( $size > 0 )
else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
I solved the problem, you can't perform $_FILES and $_post at the same time or one of them inside the other.
start with $_Post and then $_FILES and outside the $_FILES run your saving function
thats it

Submit email form to .txt file won't work

I have made a script with a form which is supposed to submit a persons email to a .txt file, only problem is that nothing happends to the .txt file, it is kept blank when the function is called. Both the html file and the php file is kept in the same folder and the .txt file is named formdata.txt .
Html code:
<form name="newsletter-form" action="process-form-data.php" method="post" id="newsletter-form">
<input type="email" name="newsletter-email" id="newsletter-email" class="form-control" placeholder="Enter Your Email" data-validate="validate(required, email)" />
<input type="submit" id="newsletter-submit" class="btn" value="Notify Me" />
</form>
Php code named process-form-data.php:
<?php
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email : '.$email.'
=========================
';
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
$file = fopen($filename, "a");
fwrite($file,$f_data);
fclose($file);
?>
Your code works for me.
Here's a variation using file_put_contents:
// Receive form Post data and Saving it in variables
$email = $_POST['newsletter-email'];
//$email = 'myhappymail#unhappy.com';
// Write the name of text file where data will be store
$filename = "formdata.txt";
// Marge all the variables with text in a single variable.
$f_data= '
Email2! : '.$email.'
=========================
';
file_put_contents( $filename, $f_data, FILE_APPEND | LOCK_EX );
// $file = fopen($filename, "a");
// fwrite($file,$f_data);
// fclose($file);
echo 'Form data has been saved to '.$filename.' <br>
Click here to read ';
Do a:
var_dump( $_POST );
die;
at the top of your script. I'm thinking you're missing your POST data.

Categories