Ok, so a little while back I had some help writing some PHP voting code, it worked just fine after I upgraded my server to use the latest version of PHP. However now I have switched servers, and the PHP isn't as up to date as the other one. Anyways here's my code:
<?php
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}
if($_GET['click'] == 'up1'){
file_put_contents('vote/1u.txt', ((int) file_get_contents('vote/1u.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
Execute and display:
<a href="?click=up1"><img src="images/thumbsup.jpg" width="40px"border=开发者_运维知识库"0"> </a><br>Votes: <?php echo file_get_contents('vote/up1.txt'); ?>
Now when on my other server (PHP version 5.2.5) this code worked great! However on my new server the PHP version is 5.2.11, and because of this the code won't work. My question is, is there any way to make this more compatible with an earlier version of PHP, or to write completely new code that will work just like this one? Or is there a way to tell my servers to use PHP 5.2.5+? I'm using cPanel X admin panel.
I have set the text file permissions to 777 and still nothing!
you are checking for variable "click" but executing the code only if it equals "up1".
But your link tells click to equals "yes" so that part of the code is never true, hence never executed.
Change your executor to this:
<a href="?click=up1"><img src="images/thumbsup.jpg" width="40px"border="0"> </a><br>Votes: <?php echo file_get_contents('counteru.txt'); ?>
But more logically, your processing code should be rationalized a bit to this:
if the link is clicked : First, if the data file (lu.txt) does not exist, create it and write '+1' inside of it, else, add 1 to its existing value.
Then, redirects to the initial page.
if($_GET['click'] == 'up1'){
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}else{
$content = file_get_contents('vote/1u.txt');
if(!$content){
die("Error! file_get_content failed !");
}
file_put_contents('vote/1u.txt', ((int)$content) + 1);
}
header('Location: ' . $_SERVER['SCRIPT_NAME']);
}
exit;
Not a bad idea to add a trim() around file_get_contents(). Or to check if $_GET['click'] isset() prior to checking if it's equal to 'up1'.
It's conventional to exit() instead of die() after a header redirect--well, from what I've seen at least.
Basically, during development, turn on error reporting and set your error flag to E_ALL to see everything, including warnings and notices--neither of which halt your code, but should still be known and addressed.
You might discover the reason your code produces different outcomes under different minor versions of PHP by turning on full error reporting.
精彩评论