How to dump string variables to a text file [duplicate] - php

This question already has answers here:
How to write into a file in PHP?
(9 answers)
Closed 9 years ago.
I have a series of variables in my PHP script that are defined via POST.
For example:
$From = "";
if( isset($_POST['From']) )
{
$From = $_POST['From'];
}
How can I create a log file (not a database, just basic txt) to capture the POST values? This is part of a conferencing web app, so there is no way to display the content "on screen". I need to dump it to a file on the server.

JSON-encode your array using json_encode() and store it to a file:
$data = json_encode($_POST);
file_put_contents('file.txt', $data);
When you want to retrieve the contents, you can use file_get_contents() or similar and then use json_decode() to decode the JSON-string back into an array / object.
Using JSON makes the interchanging of data easier, and you don't need to parse the text file to retrieve information out of it. Just use json_decode() and be done with it. However, I suggest you use a database instead of a plain text file to store this information, as it gives you more control.
As #Wrikken noted in the comments below, you could use the FILE_APPEND flag - it allows you to append the data to the file instead of overwriting it.
file_put_contents('file.txt', $data, FILE_APPEND);

Try something like this
$post_dump = print_r($_POST, TRUE);
$log = fopen('log.txt', 'a');
fwrite($log, $post_dump);
fclose($log);

Something like this
$arr = array();
foreach($_POST as $key=>$value);
{
$arr[] = $key.'='.$value;
}
file_put_contents('log.txt', implode(',', $arr), FILE_APPEND);

try this...
<?php
$From = "";
if( isset($_POST['From']) ){
$file = fopen("test.txt","w");
fwrite($file,$From);
fclose($file);
}
?>

Related

convert multiple json to php array

I have json file which contains multiple json objects.
Example
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
Want to read this file and store into database, but I couldn't convert json to php array which further I can store into database.
I tried json_decode function, but its not working. I search for this but in every link its showing use json_decode. Below is my code
$filename = "folder/filename.json";
$data = file_get_contents($filename);
echo $data;
$tags = json_decode($data, true);
echo"<pre>";print_r($tags);exit;
$data is echoed but not the $tags.
Thanks in advance.
Make array of objects and use it later
$j = array_map('json_decode', file('php://stdin'));
print_r($j);
demo
If it's only four lines you can explode and json_decode each line and add it to an array.
$s = '{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}';
$arr = explode(PHP_EOL, $s);
Foreach($arr as $line){
$json[] = json_decode($line,true);
}
Var_dump($json);
https://3v4l.org/97m0E
Multiple objects in a row should be enclosed in a json array and separated with comma like elements.So you need a [ ] at the start and end of the file.Also you could close the pre tag
Either you should fix the file generating that 'json' or you can use fgets to get one line at a time, and use json decode on every line
As pointed by other, JSON which you shared isn't valid. And, I think, it is stored in your file in same fashion. I would suggest to read this file line by line each line then you can decode.
$handle = fopen("folder/filename.json", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$tags = json_decode($line, true);
echo"<pre>";print_r($tags);exit;
}
fclose($handle);
} else {
// error opening the file.
}
Assuming a file called `filename.json` contains the following lines
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
So each one is a separate json entity
$filename = "folder/filename.json";
$lines=file( $filename );
foreach( $lines as $line ){
$obj=json_decode( $line );
$t=$obj->t;
$d=$obj->d;
/* do something with constituent pieces */
echo $d,$t,'<br />';
}
Your JSON is invalid, as it has multiple root elements
Fixing it like the following should work (note the [, ] and commas):
[
{"t":"abc-1","d":"2017-12-29 12:42:53"},
{"t":"abc-2","d":"2017-12-29 12:43:05"},
{"t":"abc-3","d":"2017-12-30 14:42:09"},
{"t":"code-4","d":"2017-12-30 14:42:20"}
]
If you cannot influence how the JSON file is created, you will need to create your own reader, as PHP is not built to support invalid formatting. You could separate the file by new lines and parse each one individually.

Accessing variables in PHP files

Is there anyway to access variables of one php file into another?
- I am trying to validate a form. I need to access variables from the validationConditions.php file in form.php file.
I have tried creating sessions but they are error prone.
I am using the latest version of dreamweaver.
Is it possible to use $_POST to achieve the results?
Any example will be welcome...
Thanks a lot in advance.
The easiest would be to use session variables. In the first page you could set the values like this
session_start();
$_SESSION['myvar'] = 'My Data';
Then in the second page you can retrieve the data like this...
session_start();
$myvar = $_SESSION['myvar'];
Which in turn sets $myvar to "My Data"
You can read a php file with another php file. Assume that we have 2 php files.
new.php
<?php
$a="something";
?>
serach.php ---> search in new.php
<?php
// What to look for
$search = '$a'; //WE are searching $a
$lines = file('new.php'); // in new.php
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
?>
Something like that. You have to edit this file.
A somehow devious solution:
ob_start();
$request = array(
"_id"=>"0815",
"user"=>"john",
"email"=>"john#dunbar.com",
"phone"=>NULL
); // Don't know. Just how u need your request to look like.
include('validationConditions.php');
$response = getValidationConditions($request); // Function in 'validationConditions.php' that responds an array or a JSON
$out = ob_get_clean();
echo json_encode($out);

Array is shown when printed but cannot compare it with a string in php

I am trying to write a php script to confirm an email address. I am using a file instead of a database to store user info which is outside the root directory. The file is csv.
When I try to store its contents in an array and print it, it works but when I try to compare an element from the array, it doesn't work. And also I want to write the email address of the user in csv as the last entry on the same line as other info.
Please help.
<?php
$rows[] = array();
$username = $_GET["username"];
$passkey = $_GET["passkey"];
$userdata = fopen("/****/*********/*****/$username.csv", "r");
$email = $_GET["email"];
$line = file_get_contents("/****/********/*****/$username.csv");
$rows = explode(",", $line);
print_r ($rows);
$newrows = trim($rows[6]);
$newpasskey = trim($passkey);
if($newrows == $newpasskey)
{
echo "Email-Id confirmed.";
fclose($userdata);
$userdata = fopen("/****/********/******/$username.csv", "a+");
fwrite($userdata, ",".$email);
fclose($userdata);
}
?>
I suggest you take a look at PHPs csv functions to ease loading/writing .csv data.
http://php.net/manual/en/function.fgetcsv.php and http://php.net/manual/en/function.fputcsv.php
Also, in your code, make sure that $username and $passkey are set, trimmed and sanitized before continuing.
You might also want to switch from GET to POST method in your form, I personally wouldn't want my password to be seen in the URL.
Try this:
$passkey = trim($passkey);
$stored_pass = trim($rows[6]);
if($stored_pass == $passkey)
{
//do stuff here
}
I found out the reason.I had made a mistake while entering the user info onto the file. I changed the php script that enters user info to the file. Now it works perfectly.

How to Overwrite Json if Fields Match - PHP

Working on a website and need to store data for each user. Currently using json files and the way it is set up currently it overwrites the data each time.
1st question, is using one json file the best way to house this data or should I set up a directory for each user?
2nd question, if one file is the best way to go, how do I append 'unique' data? I found some example code from the posts on "Overwrite JSON if fields match PHP" but it is not working for me. It is not writing to the file at all now.
Original code:
$posts[] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat);
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Revised code to be able to append new data and eliminate redundancies(Does not work):
$file = file_get_contents('results.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[vhclID] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat,
'statVal2'=> $brakeStat);
//save the file
$data = array_values($data);
file_put_contents('results.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
Thanks for your help!!
You should use a database if you're storing typical user data; clearly you don't want to load megabytes of user data just to observer or modify one field for one user.
If you have some posted data, and I understand your question correctly, you might do something like this (but add more security):
$new_data = $_POST[];
foreach ($new_data as $name=>$datum) {
if (empty($data[vhclID][$name]) {
// This means that this field is unique
$data[vhclID][$name] = $datum;
}
}
And then just save that data to your JSON file.
$fp = fopen('results.json', 'r');
$postjson = json_decode(fread($fp, 1024*1024), true);
fclose($fp);
$posts = ($posts==array()) array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat) : $postjson['posts'];
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Should do what you want.
Modify $posts.
I mess around with PHP and json data a lot.
One thing I've noticed is that json_decode will create a PHP object(stdClass) by default
Example
Contents of results.json >>> {"example":"test"}
$file = file_get_contents("results.json");
$json = json_decode($file);
var_dump($json); // Outputs: object(stdClass)#14 (1) { ["example"]=> string(4) "test" }
If you add true as the second parameter to json_decode you end up with an array instead
Example
$file = file_get_contents("results.json");
$json = json_decode($file, TRUE); // Added TRUE as second parameter
var_dump($json); // Outputs: array(1) { ["example"]=> string(4) "test" }
Once you have your appropriate data, you can modify and change the $json however you want and then re-write it to the .json file.
So for question 1: Having an individual json file for each user (eg: userID-001.json, userID-002.json) is probably the better way to go.
For question 2: You can take the individual file, grab the contents and store it in a PHP array using json_decode($data, TRUE) // with true as second parameter if you want an array and then modify the array and resave it (using json_encode).
Hope this helps~!

FLASH AS2 and PHP variables

My Flash movie reads and sends data to a PHP file in a free server. It seems ok for Flash to read variable values from a text file (which is managed by a PHP file) if they are wrote in this way: &variable = value&, I have no problem with that.
But my PHP file, pre-treated (by some mathematical functions) data sent by Flash and then, updates the values in the text file, that is my intention but I can't accomplish it.
Suppose I want to update a counter ( it counts how many times the data were updated):
in the text file I have &counter=0& (initial value) and if I put in the PHP file:
<?php
$fp = fopen("jose_stats.txt", "r");// I guess with it, I've read all the variables and values
// one of them is the variable &counter.
fclose($fp);
$toSave = "&counter=&counter+1&\n";
$fp = fopen("jose_stats.txt", "w");
if(fwrite($fp, "$toSave")) {
echo "&verify=success&"; //prints to screen &verify=success which flash will read
//and store as myVars.verify
} else { // simple if statement
echo "&verify=fail&"; //prints to screen &verify=fail which flash will read and
//store as myVars.verify
}
fclose($fp);
?>
but then, I check my text file and it has &counter=&counter+1& line :( and not the expected &counter =1&.
Please, give me and advise. Thank you.
Why not use JSON?
Just store the data in JSON format:
$count = 1;
$toWrite = array( 'count' => $count );//put other data into this array if you want
//encode it
$toWrite = json_encode( $toWrite );
//and now write the data
To decode it in flash, import the JSON class:
An example of JSON in as2 using the JSON.as class:
try {
var o:Object = JSON.parse(jsonStr);
var s:String = JSON.stringify(obj);
} catch(ex) {
trace(ex.name + ":" + ex.message + ":" + ex.at + ":" + ex.text);
}
So just import the class, and run JSON.parse( yourPhpResponse );.
Also, the reason for why you're seeing &counter=& in the text file is because you're storing it like that: $toSave = "&counter=&counter+1&\n";.

Categories