How can I use PHP and JavaScript to make an image clickable, and increment a counter stored as a flat file?

笑着哭i 提交于 2020-01-24 00:22:08

问题


Im trying to find a php/js script that will let me take an image, and when clicked, increase the number in a flat file, and save that file.

I know how to include the file to get the vote total.

Im going insane trying to find this to plug and play into my website. Id love to have ip logging, and a cool fade in/out refresh update thing. But at this point ill settle for basics.

Id like to avoid using MySQL, but if its necessary i can work with it.


回答1:


Your best bet is to use the AJAX support in jQuery to access, but not load to the user, some kind of URL that writes the increment to the file. If you're using any kind of a thorough platform, you should consider doing in the with your database. However, it'd be simple enough to use jQuery's $.get() function to access the URL /increment_number.php?image=whatever.jpg. If you ever start using a database, you'd just have to change this script to perform a DB query. For your case, you'd have a simple script like this (which has been in no way optimized or has any security considerations whatsoever):

$image = $_GET['image'];
$number = file_get_contents('tracker_for_{$image}.txt');
if ($number != ''){
    $number = (int) $number + 1
}
$file = fopen('tracker_for_{$image}.txt', 'w');
fwrite($file, $number);
fclose($file);

And just remember to have the following bit of JS on the page with the image:

$(document).ready(function(){
     $('img.incrementme').click(function(){
         $.get('/increment.php?'+$(this).attr('src'));
     });
);

I haven't tested this code so it might not work, but it's in the spirit of what you'd have to do.




回答2:


Something simple like this won't work?

<?php
// Link to this file: <a href='onclick.php'><img src='yourimg'></a>
$count = file_get_contents("count.file");
$count += 1;
file_put_contents("count.file", $count);

// Possibly log an IP too? open a file
$f = fopen("ipaddresses.file", "a");
fwrite($f, $_SERVER["REMOTE_ADDR"] . "\n");
fclose($f);
?>



回答3:


If you are doing this for a voting system like Stack Overflow, creating lots of files to store this one bit of information is going to become unwieldy. This is perfect for a database.

That way, you also wouldn't include the file, but perform a query to get the total score.



来源:https://stackoverflow.com/questions/1123132/how-can-i-use-php-and-javascript-to-make-an-image-clickable-and-increment-a-cou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!