Update text file on web server using PHP - php

I have written a HTML form to collect user's inputs for an order and also a PHP program to receive the order when Submit button is pressed. In addition I got to update a text file stored on the web server to reflect the order items. Can anyone explain how am I to go about updating a text file stored on the server? Thanks..

You should lock the file to protect the file from getting clobbered by concurrent updates sent by several users. There is a full example of locking and writing to a file in the flock function documentation: http://es.php.net/manual/en/function.flock.php
Or, to save yourself the trouble, use a proper database. SQLite is easy to use and requires no setting up: http://es.php.net/manual/en/book.sqlite3.php

Use fwrite:
$fp = fopen('data.txt', 'w');
fwrite($fp, $yourData);
fclose($fp);
UPDATE:
If I understood you right you need something like this:
if(!empty($noOfApples)){
$fp = fopen('data.txt', 'w+');
$count=fread($fp,filesize('data.txt'));
$count+=$noOfApples;
fwrite($fp, $count);
fclose($fp);
}

Simplest way to do this AND preserve array structure of form fields is to dump $_POST via serialize.
Write example, after a user clicks submit:
file_put_contents('myfile.txt', serialize( $_POST ) );
Read example:
$data = unserialize(file_get_contents('myfile.txt'));
The form field would look something like:
<input type="text" name="myfield" value="<?php echo $data['myfield'] ?>" />
Alternatively, you can technically do $_POST = unseralize(file_get_contents(... but it will obviously overwrite anything that a user might input.

Just store the user input with the key which should be the input name and the value which should be the content user input. In this way, you can get the user input in an array.
Then you can translate the key-value pair into a string with serialize function. Now you can store the string into file with those code:
$fp = fopen('user{$id}.txt', 'w');//replace the {$id} with user id
fwrite($fp, $dateFromUser);
fclose($fp);
When you want to show the user input, just read the file and unserialize the string you get from the file and fill the input with the data which is stored in the array with the same key. When you want to update the user input just do the process above again.

Related

PHP - Saving form data to two different text files

I have a simple HTML form comprising of check boxes and text fields.
When I submit this form it submits the data back to the same page where I capture the data and write it to a text file.
What I'd like to try and do is write some of the check box and field data to one text file and the rest to another.
Can this be done ? if it can how do I say which fields are written to which file ?
Thanks
you send your form and after that you handle the data. For example:
$dog = $_POST["dog"];
$cat = $_POST["cat"];
$fileForDogs = fopen('path://to/first/file', 'a+'); //a+ means if not exst, create one and write on the end of file
fwrite($fileForDogs, $dog);
fclose($fileForDogs);
$fileForCats = fopen('path://to/second/file', 'a+'); //a+ means if not exst, create one and write on the end of file
fwrite($fileForCats, $cat);
fclose($fileForCats);
I would highly recommend to look at databases for example mysql to save data from form.

how to use php to save old array and also show the new arrays?

I have two text boxes for first and last name and I want the first and last name to print out after submitting.
I wonder if there's an easy to to print out old and new arrays I entered....
for example:
I entered ABC ABC then after submitting it shows ABC ABC then I reload the page and type in CCC CCC and submitting but this time the print out is ABC ABC CCC CCC.
how can I do that?
this is what I have for my html scripts
<form action = "./3.php" method = "get">
First name: <input type = "text" name = "firstname">
Last name: <input type = "text" name = "lastname">
<input type = "submit">
</form>
this is my php scripts
<?php
$array = array($_GET["firstname"],$_GET["lastname"]);
foreach($array as $info)
{
echo $info . "<br/>";
}
?>
you could use $_SESSION[] to store values so that you can use it again until you done.
note: Using sessions may have effect that every time youre want your transactionsto be finish you must destroy session..
you may store the values in a table [firstname, lastname].
And every time you submit
insert new values
read all the values from the table.
display
Just to add to the other answers:
What you are looking for is called persistent data. You need some data to exist over a longer period of time than just an HTTP request (a page load). In order to do that, you have to store the data somewhere more permanent.
There are a few ways you can do this.
You can store the data in a database.
You can store the data in a file.
You can store the data in a cookie/session.
You're looking for the simplest and easiest solution - and that would be cookies/sessions. PHP offers built-in methods for dealing with cookies and sessions.
Using cookies/sessions is very similar to just creating a variable and storing the value you need in it, except that PHP saves this data onto a file (either on the client's machine or your server) and loads the data into the variables for you automatically before the script starts, so you don't have to think much about how to handle the file that's created.
In PHP, here's an example using cookies:
setcookie('TestCookie', $value, time()+3600*24);
This creates a cookie (a small file) on the client's machine, names it "TestCookie", stores the contents of $value in the file, and saves the file. PHP will automatically load that file into a global array named $_COOKIE, which you can use on any script in that domain e.g. www.domain.com for the next 24 hours.
echo $_COOKIE['TestCookie'];
Sessions work very similar to this, except they store the file on the server, which is a more secure, but slightly more complicated process.

Creating a Registration and Login Page

I'm currently in the process of making a Registration and Login Page. My first page asks you if you want to create an account or login. What we have to do is take the information from the form that the user enters information into, and place it into a text file. I've got this working roughly. I understand that this is not good practice for security reasons, but this is an assignment for class and I MUST put the information into the text file. I have the information going into the text file, however I am having trouble comparing the posted username to all of the usernames inside of the database. Here is my code for the newaccount.html page, and the register.php file that the form submits to.
newaccount.html
<html>
<head>
</head>
<body>
<h3>Hello new user! Choose a user name and password ^_^</h3><br>
<form action = "register.php" method = "POST" >
Username: <input type = "text" name = "username"><br><br>
Password: <input type = "password" name = "pass"><br>
<input type = "submit" value = "Create Account" name = "submit"><br>
</form>
<form method = "LINK" action = "Proj2_practice.html">
<input type = "submit" value = "Home Page" name = "submit2">
</form>
</body>
</html>
register.php
<?php
$username = $_POST['username'];
$password = $_POST['pass'];
$userAndPass = $username.",".$password;
$userNames = 'usernames.txt'." ";
$passwords = 'passwords.txt'." ";
$fh_users = fopen($userNames, 'a+')or die("sorry, we couldnt open the file");
$fh_passwords = fopen($passwords, 'a+')or die("sorry, we couldnt open the file");
fwrite($fh_users, $username." ");
fwrite($fh_passwords, $password." ");
$allUserNames = fread($fh_users, filesize('usernames.txt'));
echo $allUserNames;
?>
The usernames and passwords are being sent to the text files correctly, At the end of the code, it is not echoing the variable. As of right now, there is no information in the text files, I don't know if that is the reason that nothing is being echoed. Is my approach correct here? What I'm trying to do here is send each name and password to a username and password text file.Then, Im planning on
exploding each of those text files by a space between them, which is why I add one after writing them to the text file, and then comparing the usernames and the passwords by their respective array elements. Am I overcomplicating this as much as I think I am? Please share your comments with me, I'm just trying to get better ^_^
Thank you in advance!
if you open the file with the "a+" flag it will place the file pointer on the end of the file. so when you're reading then you won't get anything as you're already on teh end of teh file.
just go back to the beginning of the file before reading
fseek ($fh_users, 0);
or close and open it again with flag "r"
$fh_users = fopen($userNames, 'r')
or simply do
$dataString = file_get_contents($userNames);
or
$dataArray = file($userNames);
If this is a class assignment, can I suggest a method as well as a solution?
If things like this don't work, try to reduce the complexity of what you're trying to do and build step by step. You say yourself that your file is empty; if it's empty you're not going to be able to read from it so your first problem is figuring out how to correctly write to a file and read stuff back from it. Forget about all of the rest of your task, focus on that first.
Now, if you open a resource (such as a file), you must close it again when you no longer need it. So you definitely need an fopen / fclose pair to begin with.
$username = "Penguin";
$userNames = 'usernames.txt'; // Why did you have a space after this?
$fh_users = fopen($userNames, 'a+');
fwrite($fh_users, $username." ");
fclose($userNames);
I haven't tested this, but at this point, you should have a file that contains "Penguin ". If you run the code multiple times, you should see the file contents grow.
If you want to read things back from this file, realise that there is a file pointer that determines where you are going to read or write. You can open the file again in such a way that the file pointer is moved to the front (and so you can read what you need) or you can explicitly move it back to the front using fseek or rewind.
Once you have gotten this writing and reading to work, then add code to handle your form and so on.

Is there a way to have php check a csv file for duplicate value before inserting a new row?

I have searched and searched for a simple solution and I am afraid there may not be a simple one after all of my research...
Here is what I have... All users who are authorizing the twitter app are opting in to being added to a list (the csv file) to be followed by other users. Its a spot for users with the same interest to follow each other.
Here is what I am trying to achieve. I have users authorizing their twitter account which inserts their username into a csv file using php.
Users can only access the page once they have inserted their twitter which I am using oauth to authorize is an actual twitter account.
However, if the user visits the page again, they will be inserted into the csv file again.
I have very simple logic to prevent an insert if they refresh the page and whatnot (when the $username value is blank).
<?php
if ($username == '') //check if $username is blank so empty row isnt inserted
{}
else{
$cvsData = $username."\n";
$fp = fopen("Twitter.csv","a"); // $fp is now the file pointer to file $filename
if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
}
?>
There is no header row in the file. It is just a single column of twitter handles.
I know the logic sounds kind of simple:
open csv file
loop through each row searching for value of $username
if $username exists - close file
else append $username
close file
Unfortunately I am learning still and having trouble finding a solution. Perhaps its the loop part that I need help with? Or a starting point. I am not at all looking for the code to make this happen though that would save me time. I'm not afraid to learn it - just having trouble finding the solution on my own. Any help is very much appreciated!
array_unique — Removes duplicate values from an array
Put the the values from the csv into an array and run array_unique() on it.

PHP counter for multiple variables for website

I am looking to setup a Server that accepts a URL with a few variables in it which I'll use the $_GET statement to obtain. These variables will increment counters stored on the server. I was going to write these files to a file and then open it/write to it kind of like this http://www.developingwebs.net/phpclass/hitcounter.php however this is only showing for one variable. I changed the code to reflect multiple variables but am not entirely sure how to write the multiple variables to the file. I was using this:
$counters = ("counter.txt");
$increment = file($counters);
/* Bunch of if else ladders checking the $_GET statements and
incrementing $increments[] accordingly */
for($i; $i < 16; $i++) //write variables to file
fputs($fp, $increment[$i]);
Where $fp points to the text file I was using and $increment[ ] holds the variables being incremented and such. So would this work? And would this work with multiple people accessing this URL at the same time? It needs to keep an accurate count of all the variables regardless of how many people are accessing the page.
Example: a survey submitted online with 4 questions. Each response has 4 options to it so in total 16 variables being stored. People will be submitting their responses to the server randomly and possibly at the same time. I need to parse their response and update the counter accordingly even when multiple people are submitting at the same time.
Thanks for any help, hope I supplied enough detail but if not just ask questions.
EDIT: The URL is being sent from an Android device to the Server I don't know if that changes anything but just wanted to be clear. The Android device is submitting the survey responses.
Building on Graham's comment, you'd be far better off letting your database server handle responses, and building your totals as part of a reporting system rather than part of the form submission process.
Here's an example, in sort-of-meta code. First, your HTML form:
<form method="GET"> <!-- though I recommend POST instead -->
<input type="checkbox" name="ch[1]"> Checkbox 1
<input type="checkbox" name="ch[2]"> Checkbox 2
<input type="checkbox" name="ch[3]"> Checkbox 3
</form>
Then, the PHP that receives the form:
<?php
$qfmt = "INSERT INTO answers (question, answer) VALUES ('%s, '%s')";
foreach ($ch as $key => $value) {
if ($value == 'Yes') {
$query = sprintf($qfmt, $key, $value);
mysql_query($query);
}
}
print "<p>Thanks!</p>\n";
?>
Lastly, to gather your totals:
SELECT COUNT(*) FROM answers WHERE question = '1';
SELECT COUNT(*) FROM answers WHERE question = '2';
SELECT COUNT(*) FROM answers WHERE question = '3';
You can adapt this to handle other form input as well, and perhaps store a long-lived session cookie to let you detect whether the same browser gets used to fill out your form multiple times.
This could work, assuming you already have an existing file with the right number of newline characters to start you off. I do not believe however that it will maintain data integrity very well, as it could cause race conditions. To prevent race conditions, theoretically you would open the file, flock it, then write to the file. Other script instances attempting to read the flocked file will have to wait. A better approach might be using a database.
You could use the http_build_query function, to store the $_GET array using an string separator char like "||".
$data = http_build_query($_GET)."||";
$fp = fopen("counter.txt", "w");
fputs ($fp, $data);
fclose ($fp);
To read the info stored could do this
$fp = fopen("counter.txt", "r");
$contents = fread($fp, filesize("counter.txt"));
fclose($fp);
$array=explode("||",$contents);
foreach($array as $var){
parse_str($var, $data);
//-$data contains youre stored values.
}

Categories