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

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
}

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.

PHP Not Displaying How I'd Expect

EDIT: I've found the source of the problem. It was the webserver, but it was the way that the webserver was processing my requests via my index page. In other words, a foolish mistake on my part. I only discovered this because of the comments in this thread, however, so thank you.
I've recently started taking a PHP class for school, however I can't seem to get any of my PHP to work. We are supposed to upload our projects to a provided website via FTP, so PHP and all necessary pieces should already be setup on the website. For my first project, I was basically instructed to copy/paste a piece from the textbook and upload it. Even this did not work, coming back with a "No input file specified" error. The code for that was:
<?php
//Get current time in a readable format
$currentTime = date( "M j, Y g:i:s a" );
//Display greeting and time
echo "Hello, world! The current time is $currentTime";
?>
I assumed it was something that would fix itself with time and moved on. Just now, I was working on the next exercise, it stated to create a file with the following code:
<?php
$radius = 4;
$diameter = $radius * 2;
$circumference = M_PI * $diameter;
$area = M_PI * pow( $radius, 2 );
echo "This circle has... <br /> ";
echo "A radius of " . $radius . " <br /> ";
echo "A diameter of " . $diameter . " <br /> ";
echo "A circumference of " . $circumference . " <br /> ";
echo "An area of " . $area . " <br /> ";
?>
However when I tried opening this to check and see if it worked, it returned the following:
"; echo "A radius of " . $radius . "
"; echo "A diameter of " . $diameter . "
"; echo "A circumference of " . $circumference . "
"; echo "An area of " . $area . "
"; ? >
This result... doesn't even make sense to me. At all. Even if it was just pasting my lines as plain text they aren't formatted like that. I understand this is probably an entirely basic question to be asking but I'm just starting PHP and none of this makes sense. None of it is explained either.
EDIT: I've been asked for a bit more information, so here is what I can give.
For the first example, I uploaded it to the webserver via FileZilla and when I opened the webpage, the only text was an unformatted "No input file specified." When I hit "View Source Code", the source code also said simply "No input file specified", despite the fact that I definitely uploaded a .php file with code in it to the webserver.
For the second example, it is clear to me that I messed up, as I simply tried opening the file in Google Chrome, not associated with any webserver. I had no idea you couldn't do that, and honestly that seems fairly inefficient, but I guess it can't be helped.
There is yet a third example that I just uploaded to the server now. An actual exercise that is a part of the homework for the class. The file I uploaded had this exact code:
<html>
<body>
<?php
$x = 4;
$x = $x + 1;
$x += 1;
$x++;
echo $x;
?>
</body>
</html>
This file also returns "No input file specified."
Notice how you start getting input right after the first > in your code.
This is a sure sign that PHP isn't processing your file.
Did you name your file something.php? It needs that .php extension, or else custom configuration, or else it won't handle it.
Are others having the same problem? If the files are named *.php then perhaps the PHP module is not enabled on the web server or the web server is somehow otherwise configured incorrectly.

How do I place a unique ID in my PHP confirmation page?

I have a PHP script that emails me the results from a form that generates a unique ID number. The PHP script executes a confirmation page. I'm trying to place the unique ID on the confirmation page: quote_confirm.php. I already tried this in the conformation page:
<?php
$prefix = 'LPFQ';
$uniqid = $prefix . uniqid();
$QuoteID = strtoupper($uniqid);
."<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>".$QuoteID."</td></tr>\n"
First off, uniqid() has a prefix parameter, so your line $uniqid = $prefix . uniqid(); should actually be $uniqid = uniqid($prefix);
Also, are you receiving an error? What is the output?
From what I can understand it is something like this:
form -> mail + output page
So there is mail()-like function and after that some output.
If the variable($uniqid) is set you have to make sure it's not overwritten or unset by something else before the actual output. You have to also check the scope of variable.
There is no mistake in the code you posted.
But speaking of style:
I also recommend using using $uniqid = uniqid($prefix) instead of $uniqid = $prefix. uniqid();.
And the following line is strange:
."<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>".$QuoteID."</td></tr>\n"
Write it as "<tr><td class=\"label\"><strong>Quote ID:</strong></td><td>$QuoteID</td></tr>\n" (if you insist on using "") and if the function is echo (example: echo $something not $content .= $something) use , instead of . .
Full example:
echo 'Constant text without variables', $variable, "String with a $variable and a newline \n";

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.

Get user input from form, write to text file using php

As part of a subscriber acquisition I am looking to grab user entered data from a html form and write it to a tab delimited text file using php.The data written needs to be separated by tabs and appended below other data.
After clicking subscribe on the form I would like it to remove the form and display a small message like "thanks for subscribing" in the div.
This will be on a wordpress blog and contained within a popup.
Below are the specific details. Any help is much appreciated.
The Variables/inputs are
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$leader is a two option radio button with 'yes' and 'no' as the values.
$country is a drop down with 40 or so countries.
All other values are text inputs.
I have all the basic form code done and ready except action, all I really need to know how to do is:
How to write to a tab delimited text file using php and swap out the form after submitting with a thank you message?
Thanks again for all the help.
// the name of the file you're writing to
$myFile = "data.txt";
// opens the file for appending (file must already exist)
$fh = fopen($myFile, 'a');
// Makes a CSV list of your post data
$comma_delmited_list = implode(",", $_POST) . "\n";
// Write to the file
fwrite($fh, $comma_delmited_list);
// You're done
fclose($fh);
replace the , in the impode with \t for tabs
Open file in append mode
$fp = fopen('./myfile.dat', "a+");
And put all your data there, tab separated. Use new line at the end.
fwrite($fp, $variable1."\t".$variable2."\t".$variable3."\r\n");
Close your file
fclose($fp);
// format the data
$data = $Fname . "\t" . $email . "\t" . $leader ."\t" . $industry . "\t" . $country . "\t" . $zip;
// write the data to the file
file_put_contents('/path/to/your/file.txt', $data, FILE_APPEND);
// send the user to the new page
header("Location: http://path/to/your/thankyou/page.html");
exit();
By using the header() function to redirect the browser you avoid problems with the user reloading the page and resubmitting their data.
To swap out the form is relatively easy. Make sure you set the action of the form to the same page. Just wrap the form inside a "if (!isset($_POST['Fname']))" condition. Put whatever content you want to show after the form has been posted inside the "else{}" part. So, if the form is posted, the content in the "else" clause will be shown; if the form isn't posted, the content of the "if (!isset($_POST['Fname']))", which is the form itself will be shown. You don't need another file to make it work.
To write the POSTed values in a text file, just follow any of the methods other people have mentioned above.
This is the best example with fwrite() you can use only 3 parameters at most but by appending a "." you can use as much variables as you want.
if isset($_POST['submit']){
$Fname = $_POST["Fname"];
$email = $_POST["emailPopin"];
$leader = $_POST["radiobuttonTeamLeader"];
$industry = $_POST["industry"];
$country = $_POST["country"];
$zip = $_POST["zip"];
$openFile = fopen("myfile.ext",'a');
$data = "\t"."{$Fname}";
$data .= "\t"."{$email}";
$data .= "\t"."{$leader}";
$data .= "\t"."{$industry}";
$data .= "\t"."{$country}";
$data .= "\t"."{$zip}";
fwrite($openFile,$data);
fclose($openFile);
}
Very very simple:
Form data will be collected and stored in $var
data in $var will be written to filename.txt
\n will add a new line.
File Append Disallows to overwrite the file
<?php
$var = $_POST['fieldname'];
file_put_contents("filename.txt", $var . "\n", FILE_APPEND);
exit();
?>

Categories