Hey people!
I have a really stupid PHP question:
When a button is clicked it needs to get an integer from the server, increment it and store it on the server again. I do not program any PHP so the only thing I know is how to increment that integer, and even that from Google.
I tried to find such a code snippet on the web but it seems there are no - at least I haven't found any.
Thanks in advance!
You need some kind of long-term storage, since most PHP programs only execute long enough to generate a single page. That means either writing the value to and from a text file, or to and from a database.
I found a script to store to and get from .txt files but it seemed to require a string and my PHP is really not good enough to do this...
This is the old code I used on my contact form when folks wanted to book me for their photographs. Rather than assign an invoice number by hand, I figured I get so little requests that I can do it automatically.
Code: $file = 'txt/invoice.txt';
if(($form == "Portrait" || "Pet") && (!preg_match("/href/", $message))) {
# Open & Read the last invoice.
$f = fopen($file, 'r');
$n = fread($f, 5);
# Increment it for use on this new form submission.
$n++;
fclose($f);
# Since I don't know how to do this at the same time
# Let's open the last invoice again
# Then save the new invoice number.
$f = fopen($file, 'w');
fwrite($f, $n);
fclose($f);
}
So the things you'll want to use are fopen, fread, fwrite and, fclose. My code can certainly be optimized, if you use this perhaps you can try and figure out how to read and write at the same time. Maybe it's more trivial than young me thought at the time. I've since abandoned this approach and have no desire to seek a more optimized method.
Thanks for your help, but as I said I never programmed in PHP. In fact, one hour ago, I didn't know how to run PHP.
So I really don't know what exactly this does - From what I see I can extract it really specifically processes something, but I don't know what/how to edit.
I simply needed a rountine that takes "$var" as input and writes it to something like "text.txt" and something that grabs "text.txt" and retrieves "$var" from it.
Yup! That's all included in that script. I'll break it down a little more than the included comments while removing the bits that are not relevant.
Code: $file = 'txt/invoice.txt';
Saving the file location to variable $file.
Code: # Open & Read the last invoice.
$f = fopen($file, 'r');
$n = fread($f, 5);
This opens $file as a read only and saves its contents to variable $f. Then we read up to 5 bytes of $f and save that to $n
Code: # Increment it for use on this new form submission.
$n++;
fclose($f);
Since the data stored in $file is a number, we can simply increment it by one, as demonstrated by $n++ or do whatever else we require then close it. If you need to store a string, such as "hello world", the php page I linked to above has a really good example on how to use a variable byte length. But I'll post it here for posterity sake.
Code: fread($f, filesize($file));
Since fread() requires the number of bytes you want to read, and each character in the text file is one byte, getting the file size is a great way of reading the whole file.
Code: fwrite($f, $n);
fclose($f);
}
After we alter $n how we want, we write $n to $f and then close $f (so it's not taking up memory on the server RAM anymore.
Thank you very much! That's just what I was looking for and even more!
It even taught me a bit of PHP and showed me once again how I will need PHP someday...
Thanks again!
Edit:
Well, actually I dont understand
Code: fread($f, filesize($file));
...
What is it supposed to do?
I can't stress enough how important it is to comment your code. Old me thanks young me for this. I've looked back on code I haven't commented on and I literally have no idea what it's doing. I have doubled my line counts with comments within certain files, especially when I'm learning new things.
Be sure to be a verbose when you comment! The only thing it'll hurt is file size (and maybe execution speed? But only marginally if anything) and you'll thank yourself forever later on!
Nik wrote:
Well, actually I dont understand
Code: fread($f, filesize($file));
...
What is it supposed to do? 1) From the help page for filesize: takes a path ($file) and returns the size of that file, in bytes. If you specify an invalid path (a file that doesn't exist), it returns FALSE (which if you try to do math with, will be coerced to 0).
2) From the help page for fread($handle, $size) : reads size bytes from the open file handle $handle.
Therefore, this line of code figures out the size of the file, then reads (size of file) bytes: that is, the entire file.
Edit: By the way, a key PHP survival skill is to open a new tab and type php.net/functionname any time you can't remember arguments to a function or what a function does.
I guess I got it. Just need to test what came out
.
Thank you anyways!
Edit: Doesn't work... Here is the code:
File 'score.php':
Code: <!DOCTYPE html>
<html>
<head>
<meta="UTF-8">
<title>Score test</title>
</head>
<body>
<?php
# Open data.txt to $f
$f = fopen('data.txt', 'r');
# Write all bytes of $f to $n
$n = fread($f, filesize('data.txt'));
# Close $f
fclose($f);
?>
Score: <?php echo $n; ?><br>
<a href="increment.php">Increase!</a>
</body>
</html>
File 'increment.php':
Code: <!DOCTYPE html>
<html>
<head>
<meta="UTF-8">
<title>Increment Script</title>
</head>
<body>
<?php
# Open data.txt to $f
$f = fopen('data.txt', 'r');
# Increment $n
$n++;
# Write $n to $f
fwrite($f, $n);
# Close $f
fclose($f);
# Debugging
echo $n;
$f = fopen('data.txt', 'r');
echo fread($f,filesize('data.txt'));
?>
</body>
</html>
File 'data.txt':
Code: 0
Increment.php returns 1 for $n but still 0 for 'data.txt'...
I have no idea why.
Probably this looks like code from a child in elementary school ...
Your second script doesn't read the file to initialize $n. When you run increment.php, none of the variables from when you ran score.php persist.
Thanks, I didn't know that... But somehow it still fails to write data.txt
.
Edit: I thought the problem was in opening the file read only ('r') but I tried everything that I think would make sense to try and it either returned errors, most of which I indeed tracked, or gave me the same result as before.
This works perfect for me:
File score.php:
Code: <!DOCTYPE html>
<html>
<head>
<meta="UTF-8">
<title>Score test</title>
</head>
<body>
<?php
# Open data.txt to $f
$f = fopen('data.txt', 'r');
# Write all bytes of $f to $n
$n = fread($f, filesize('data.txt'));
# Close $f
fclose($f);
?>
Score: <?php echo $n; ?><br>
<a href="increment.php">Increase!</a>
</body>
</html>
File increment.php:
Code: <!DOCTYPE html>
<html>
<head>
<meta="UTF-8">
<title>Increment Script</title>
</head>
<body>
<?php
# Open data.txt to $f
$f = fopen('data.txt', 'r');
# Increment $n
$n = fread($f, filesize('data.txt'));
$f = fopen('data.txt', 'w');
$n++;
# Write $n to $f
fwrite($f, $n);
# Close $f
fclose($f);
# Debugging
echo $n;
$f = fopen('data.txt', 'r');
echo fread($f,filesize('data.txt'));
?>
</body>
</html>
Ideed, you fixed it! Thank you very much.
I guess I will try to learn PHP soon!
Edit: Last Problem. When I try to redirect from increment.php to score.php using
Code: <?php header('Location:/score.php'); ?>
I get Code: Warning: Cannot modify header information - headers already sent by (output started at /urlhere/test/increment.php:8) in /urlhere/test/increment.php on line 22
What does that mean?
Edit2: Some whitespaces were making the output. I fixed it and it perfectly works! Thanks again for all the help!
Edit3: One more task to do... Well, this is for some sort of "Like" button. But I am afraid it is possible that users might spam this function. I managed to create a log file logging IP and date of access when running increment.php, but is it possible to only allow them to "Like" once every 30-60 minutes or something like that?
From what I've read, this can be done by cookies or a data base. But I didn't find an explanation on how to do that any of these ways... (The site won't be serious business, so security is a nice feature but not necessary at all. I should also be fine with cookies)
PS: I also tried logging the last accessing IP and comparing it to the current one, but this is not quite what I need. It only forces a user to wait before "Liking" until another user "Likes" too, that's way too inaccurate, even for my purposes.
You should indeed use a cookie, which expire in 30/60 minutes. The code to do is:
Code: <?php
// check if cookie already exist; if not, create one which expires within 30 minutes
if (!isset($_COOKIE['user'])) {
setcookie('user',1,time()+30*60);
// code for pressing "Like"
} else {
header('Location:notallowed.php')
}
?>
Thank you very much!
I guess you will become me PHP teacher for some tine now
!
Nik wrote:
Thank you very much!
I guess you will become me PHP teacher for some tine now
!
No problem; ask anything and I will try to give you the answer - if I know it
Okay, so the next problem I ran across is automatically refreshing a page... I wamt to do something similar to SAX but based on a .txt file. I have read some of the AJAX tutorials, but they all only say things like "It's so easy, you just need to put these five lines of code in your HTML head and that's it!" totally making no sense for me, as I don't know what, how and with what they refresh...
Did you take a look at
the original text file-backed SAX? No use reinventing the wheel when the wheel already exists. If you don't want to use something that already exists, then it sounds like you're conflating two things: refreshing a page and loading content via AJAX. Make sure you realize that those are two separate things, done separate ways.
Yes, I downloaded SAX 1.0 and quickly browsed the source. But I didn't find the refreshing and/or loading part there, as the whole thing isn't commented... Also, I tried to challenge myself, for practice I want to write as much code as possible by myself and see what comes out, so, sorry, but I don't want to use a ready made program. I want to do my own
.
Edit:
As far as I understood, AJAX is a way to refresh some part of a HTML document with Javascript by calling the PHP and dynamically outputting it's response. But it seems like I understood wrong.
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.
»
Go to Registration page
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum