2

How to link a HTML link like this - <a href="#">Click here to log out</a>

to a PHP function like - logout()

What I need to do is, when people click a link, php will run the php function.

Please advice! :D

2 Answers 2

3

What I need to do is, when people click a link, php will run the php function.

You can not call a PHP (server-side language) function when clicking on a link. From your question, I suspect you want to provide a link for users to logout, below is how you should go about.

Your link should be like:

<a href="logout.php">Click here to log out</a>

And in logout.php you should put php code for logging the user out.

Code inside logout.php might look like this:

<?php
  session_start();
  unset($_SESSION['user']); // remove individual session var
  session_destroy();
  header('location: login.php'); // redirct to certain page now
?>
Sign up to request clarification or add additional context in comments.

2 Comments

@Sarfarz - I'm trying to build a simple login system. So I follow this tutorial - tinsology.net/2009/06/… This is what I achieve so far - cokicoki.com/box/loginsys/reg.php Please advice me if you see something weird. Thanks!
@Zhaf: It seems to be fine, however when creating such login system, you need to be aware about sql injection attacks, see more info about here: php.net/manual/en/security.database.sql-injection.php
1

There are a number of ways; just to get this out of the way first. There is no way to invoke a PHP function from the client side (i.e, user interaction at the browser) without a page refresh unless you use AJAX. As one answer suggests, you can put the function in a PHP page, and link to it. Here's another way

<a href="index.php?action=logout">Logout</a>

And inside index.php

<?php
    switch $_GET['action']:
    {
         ....

         case 'logout': logout(); break;
         ...

    }
 ?>

There are other more sophisicated methods, such as determining which function to call from URI directly, which is used by frameworks like CodeIgniter and Kohana.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.