file_put_content exhibits weird scaling behaviour - php

My task is to put data from a form with 24 input fields into a txt file. Not very adapt at PHP coding I got a few snippets of code from the web, the file_put_contentsnippet from an example with 2 input fields. It worked (=it wrote data to file and showed the 'thank_you'-page). I added another field - it worked. Ok, so now I added all my fields - it did not write to file and produced a blank white page.
I went back to the 3 fields version, and started adding fields 1 by 1. When it stopped working at 8 fields, I introduced a 2. isset(POST[]) element. That way I could add another 6 fields, and it worked. (In between I separately saved the code when it successfully printed data from 11 fields to my file). When on the 7th field it again produced a blank page and did not save to file, I removed tha last addition - and to my BIG SURPRISE the very code that had worked before I added the last one didn't work any more?! I continued to remove element by element - it didn't work anymore?! So I reverted to the saved version of the code - and it still does not work.
So I went over every single letter, sign and number - all to no avail. Even though I havent changed anything in the html form, I ched this too, because everything points to a problem in the form that points to my php file. All in vain.
I am aware that it has to be something I did and now overlook - please point out to me where my mistake lies.
This is the version that worked 2 days ago, and I saved it before expanding:
<?php
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['q01' | 'q02' | 'q03' | 'q04' | 'q05' | 'q06' | 'q07']) && isset($_POST['q08' | 'q09' | 'q99' | 'q98'])) {
$data = $_POST['q01'] . '#' . $_POST['q02'] . '#' . $_POST['q03'] . '#' . $_POST['q04'] . '#' . $_POST['q05'] . '#' . $_POST['q06'] . '#' . $_POST['q07'] . '#' . $_POST['q08'] . '#' . $_POST['q09'] . '#' . $_POST['q99'] . '#' . $_POST['q98'] . "\n";
$ret = file_put_contents('data/data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
header('Location:danke.html');
}
exit (0);
}
?>
Just to make sure I will also post the relevant lines of the form:
<form id="umfrage" class="appnitro" method="post" action="data2text.php" accept-charset="UTF-8">
<input id="saveForm" class="button_text" type="submit" name="submit" value="Fertig!" />

your resetForm function does not seem to be PHP.
isset($_POST['q01' | 'q02' | 'q03' | 'q04' | 'q05' | 'q06' | 'q07'])
what are you expecting this to do? this does binary operations on string... This is not how you check array key availability. you should check each key individually:
if (isset($_POST['q01']) || isset($_POST['q02']) .....) {
note the double pipes!

Related

Sort PHP POST by a fields inputted date

With a simple form, i have a field for users to input a date - when the fields are posted into my txt file i need them to be sorted by the date field, cant figure out a way to sort them by the date field, any ideas?
PHP Code:
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
$data = 'REQUEST - ' . $_POST['field1'] . ' - ' . $_POST['field2'] . ' - ' . $_POST['field3'] . "\n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);}
You're writing to the file in append mode, which only adds to the data already in the file. You're going to have to read the file back in,
add the data in sorted order, then re-write the entire file.
Using a database would probably be a simpler way to handle this.

What is wrong with my 'Save File' php code?

The question is simple but i will give some background information to hopefully make answering it easier.
So, I am working with the ELGG framework and taking information from a form and the text boxes in it in hopes to print that data to a simple text file.
Unfortunately, for some reason this has been giving me lots of trouble and I cannot seem to figure out why no matter where I look.
Code is as followed
<?php
error_reporting(E_ALL);
//Get the page
$title = get_input('title');
$body = get_input('body');
$date = date("l jS F Y h:i A");
//remove any possible bad text characters
$FileName = $title . ' ' . $date;
//print to file
//get filename and location to save
$folderName = '/Reports/' . $FileName . '.txt';
$ReportContent = "| " . $body . " |";
//write to the file
file_put_contents($folderName, $ReportContent, 0);
//error check to see if the file now exists
if (file_put_contents($folderName, $ReportContent)) {
system_message("Report Created (" . basename($folderName) . ")");
forward(REFERER);
} else {
register_error("Report (" . basename($folderName) . ") was not saved!");
forward(REFERER);
}
So what above SHOULD do is grab the text from the title and body box (which i can confirm it does from the title at least) and then save it under the /reports/ folder (full path for the plugin is Automated_script_view/reports/ if needed). Yet I will always get the register error, and I cannot seem to find why.
I believe it has to do with the declaration of the folder (/reports/), as if I take that part away, it passes and submits, although it doesn't seem to actually save anywhere.
Any and all advice would be very much appreciated!
The Function file_put_contents(file,data,mode,context) returns the number of character written into the file on success, or FALSE on failure. Note the following corrections and your script will work just fine:
1 Your File name has an 'illegal' character ":" coming from the $date part of the string you concatenate to form the filename.
2 Remove file_put_contents($folderName, $ReportContent, 0); Since the function returns an integer, simple use:
if( file_put_contents($folderName, $ReportContent) > 0 ){
//true
}else{
//false
}

Form search save in file & display result

What is the most elegant and efficient way of search a string against injected script file in PHP.
The flow:
i want make form search when user input strings & click search, data searched save on txt/php file with auto create new file based on month & year ex: -201601.php / txt
then data was saved on safety query with serial key on each string
then if data on -201601.php contents have more than 1000+ query, the data old was deleted automatic
then how showing 50 strings based on random strings on -201601.php
then in -201601.php there are no double string or same string
If you have a solution for my issue and want to post an answer, please add some explanation so that I can understand why/how you did it so that I won't come asking the same questions all over again. Thanks
Im search & create file that i want making it with my plot imagination. Here is what I have so far manually :
<center>
<form action="./cari.php?q=" method="GET">
<input type="text" name="q" value="" placeholder=" Cari .." style="cursor: pointer;width:69%"/>
<input type="submit" value="Search"/>
</form>
</center><?php
if(isset($_GET['q'])) {
$data = ''.$_GET['q']."<br>\n";
$ret = file_put_contents('rcnt.php', htmlspecialchars($data), FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
//echo "$ret bytes written to file";
}
}
//else {die('no post data to process');}
?>
Im stuck searching with cant find related tutorial & hope find answer :(
Please your help, i want learn more with this, i use XAMPP 5.6
First step, the ?q= var the browser will create, you don`t need to set this on your form action.
<form method="get">
<input type="text" name="q" placeholder="search">
</form>
The PHP code will be:
<?php
if(!empty($_GET["q"]))
{
$file = fopen(date("Ym") . ".txt","a+");
fwrite($file, $_GET["q"] . "\r\n"); //\r\n jump the line
flose($file);
}
?>
If today is the 1st search of the 1st day of the month, the file will not exists, then, the PHP will create it, otherwise, will open and write on it.
Hope it could help you.
We could try this way:
<?php
$theFile = date("Ym") . ".txt";
$myFile = file($theFile);
for($i = 0; $i < 100; $i++){ //deleting the first 100 lines
unset($myFile[$i]);
}
//rewriting the file without the 100st first lines
file_put_contents($theFile, implode($myFile));
?>

How to create conditional button in HTML based on MySQL data?

I am trying to create a button that will either say "Follow" or "Unfollow", depending on whether or not the current user follows another user.
If John followed Tim, but not Sarah, the web view would look as follows, according to John's view:
_________________________________
| | |
| Tim | (unfollow) |
|________________|______________|
| | |
| Sarah | (follow) |
|________________|______________|
Where (" ") denotes a button.
I have a database that indicates who follows whom, but how would I display the correct button based upon validation with said database?
Assuming you have three fields "name_id","name" and "followed" where "name_id" is the id of the person, "name" is a string signifying the name of the person, and "followed" is a boolean:
<script type="text/javascript">
function toggleFollowing(name_id) {
window.location = 'toggleFollowing.php?name_id='+name_id;
}
</script>
...
<?php
...
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>'.$row['name'].'</td><td><a href=""><button type="button" onclick="toggleFollowing('.$row['name_id'].')">'.($row['followed']==1 ? 'Unfollow':'Follow').'</button></td>';
echo '</tr>';
}
...
?>
You would have toggleFollowing.php receive the variable $_GET['name_id'] to toggle on the database and come back to this page. I'm assuming you have the current user's ID stored as a session variable or by other means since you would need that as a primary reference to update the record. If you're passing that from page to page by some other means, then you would want to pass that variable as well.
Apparently, this is more truncated code, but a better method would be to use AJAX to perform the toggling on the DB, and DOM manipulation (JQuery?) for a "real-time" update.
Hard to answer without examples of your code, but something like this?
<?php
if(follow){
echo '<input type="button" value="Follow" />';
} else {
echo '<input type="button" value="Unfollow" />';
}
?>

form variable + submit button not concatenating with php

UPDATED: Examples added at end as requested:
Got a seemingly unique problem with concatenating form variables + the name of the button used to submit.
This works:
$word="number"; $number=1; myalbum=$word.$number;
echoing $myalbum gives "number1". No surprises there.
BUT if I POST the form to a php script with the intention of writing to file ONLY the data on row on which the button was pushed, I get problems.
So, let's say I've got 10 rows, and the button for row 5 is pushed.
If I get the script to echo what button was pushed ($button), I get "5" back.
If I get the script to echo what's in the box in row 5 (in this case, "$number5=5") then by echoing $number5 I get 5.
But if I concatenate $number.$button, I get nothing, when I expect "number5".
And yet, if I concat any two parts of the submitted data, it works as expected.
I've been over the variables section at php.net, I've been over the w3 forms tutorials.
I've googled. I've stackoverflowed. I've checked and triple checked my spelling.
I even started from scratch - again, it's almost as if appending the value of the button kills the concatenation process.
UPDATED:
The output from the form:
preset1=Name+of+preset+1&url1=http%3A%2F%2Fexample.com%2F1&preset2=Name+of+preset+2&url2=http%3A%2F%2Fexample.com%2F2&preset3=Name+of+preset+3&url3=http%3A%2F%2Fexample.com%2F3
The code for the form handler:
<?php
$myFile = "test.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "Preset: " . $preset . " - Title:" . $title . $submitButton . " - Submit Button:" . $submitButton . "\n";
fwrite($fh, $stringData);
fclose($fh);
?>
The output from the above:
Preset: 3 - Title:3 - Submit Button:3
So, we know it knows what buttons has been pressed. But not the output I expected.
But if I change the line to
$stringData = "Preset: " . $preset3 . " - Title:" . $title3 . " - Submit Button:" . $submitButton . "\n";
then I get, as expected:
Preset: Name of preset 3 - Title:http://www.example.com/3 - Submit Button:3
But of course, this is no good. I understood that if
$preset.$submitButton would be the same as $preset3 if submitButton was 3.
Oh, and I've also tried
$thepreset='$title' . $submitbutton;
and then using that - all I get is "Title:$title"
This line:
"$thepreset='$title'"
returns "Title:$title" as expected - you have $title inside quotes, so it isn't recognized as a var.

Categories