开发者

PHP on link click effects

I have one question which is somewhat two-parted (though the parts go hand in hand). I've started picking up PHP, and I wanted to do two things when an image is clicked.

I want the click to

  1. Increment a session variables, say $_SESSION['entry'].
  2. Reload the current pa开发者_StackOverflow中文版ge (say index.php).

How should I go about this?

To be clear, I'm not asking for someone to code this for me, I'd just like to be pointed in the right direction because I'm not too sure what the best way would be.


Well, anchor links "reload" the page if the href points to the same page. So, all you need to do is tell PHP you want to increment the session variable. You could use a GET variable to do this:

<a href="index.php?increment=true">Increment the counter</a>

And then in your index.php:

if (isset($_GET['increment']) && $_GET['increment'] == 'true') {
  $_SESSION['counter']++;
}

This assumes you've already initialized the session variable counter at some point. You can check out the wonderful PHP docs to explain the functions used above if you aren't familiar with them.


The way to do this would be to link the image to "itself" $_SERVER['PHP_SELF'] perhaps or just to /index.php, and check the session to see if that value is set, and if so increment it.

<?php

session_start();
if (isset($_SESSION['entry'])) {
    $_SESSION['entry']++;
} else {
    $_SESSION['entry'] = 1;
}

// if entry is greater than some value in your DB, then set it back to 1


<a href="?incr=1"><img src=.../></a>
<?php  if($_GET['incr']) $_SESSION['entry']++; ?>

this should give you the idea.


You could do an AJAX call to a PHP script that increments $_SESSION['entry'].


  • Load page with image that has a link around it: "?imageClick=1" for instance
  • On image click the page is therefor automatically loaded
  • If $_GET[ 'imageClick' ] equals 1 increment the session variable
  • Redirect to same page without the imageClick variable

If you are concerned that index.php?imageClick=1 may be remembered by the browser in it's history, and therefor can be used to reload without an actual image click:

  • Load page with a form that has method POST and an input element of type image, named imageClick (acting as a submit button) with value 1
  • On image button click the form is submitted to the same page
  • If $_POST[ 'imageClick_x' ] or `$_POST[ 'imageClick_y' ] is set and increment the session variable
  • Redirect to same page
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜