How to link a HTML link with a PHP function? - php

How to link a HTML link like this - Click here to log out
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

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:
Click here to log out
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
?>

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
Logout
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.

Related

redirection without reloading the whole page

I have a framework and I think I'm following something like the MVC pattern: A framework (the model) an index page that controls the input (the controller) and the views pages (that are included inside main.php/the main html)
I read a lot about structure and logics, to write a good application. I read many comments like "Why are you outputting anything if all you are going to do is try and redirect the user to another page?". Well the answer is, the most common case: redirect after the user successfully logged in. Do I need to print something? Of course, the whole main page with a login form/post. How I'm supposed to do that redirection??
So I'm a bit confused about logics and structure of the application. How do you store all the output and do the header redirection without printing anything?
I was thinking about using javascript to do the redirection but I also read comments saying; "if you write good code (following a good logic/structre), you won't need to use hacks like javascript redirection". How is that even possible?
Because the php output_buffering should not be enabled.
I have the output_buffering enabled, and I can use header (after output) without any problem. If I use the javascript redirection the whole page reloads, but using header it just loads the content (the views content that are included in main.php).
So how do you do this without output_buffering?
If you want to redirect to a success page AND pass messages - say, after a successful login - an easy solution is to use "flash" sessions, where you store a message in a SESSION and then, as soon as it's used, you discard it. You don't need to sore anything in the output buffer for this.
This is a very basic example, but should give you the gist of it.
login.php
if($login_successful) {
// put your message in the session
$_SESSION['message'] = 'Login Successful';
// redirect to the success page
header('location: success.php');
}
success.php
<?php
session_start();
// check if $_SESSION['message'] exists
if(isset($_SESSION['message'])) {
// print the message
echo $_SESSION['message'];
// clear the session
$_SESSION['message'] = null;
}
Looks like you are mixing up some things here. What you are talking about are actually two different requests. Either the user wants to view the main page, or he wants to log in using that form on your main page. In your index.php you would have something like this (pseudocode):
if (isLoginRequest) {
// user wants to log in
if( validateLogin($loginFormData) ) {
redirect('successful');
} else {
displayLoginError();
}
} else {
// user wants to view main page
echo main.html
}
Update to answer the question in the comments: The better alternative would be to leave your form validation stuff in login.php and refer to that in your login form <form action="login.php" .... Then in your login.php you would have something like this:
if (loginSuccessful) {
redirect('success.php');
// no need to call die() or whatever
} else {
setFlashMessage('Login failed'); // set a flash message like timgavin described
redirect('index.php')
// also no die() or whatever
}
index.php then is responsible to display your main page and, if set, rendering the flash message from a failed login attempt.
Simple solution: Move the login post script from login.php to another file (login_post.php). The same for other scripts using header() after dom output. (no need to change the form action="")
In index.php:
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
//some more security checks like esc_url() (non-php function)
if ($url == '/login') {
include('header_pages/login_post.php');
}
// all these includes before including main.php
// where views pages are included and the DOM output starts
Since header() is inside the post script, no more headers already sent errors (And output_buffering off, of course).
Same for logout page that is currently being included inside main.php
Thanks to the other answers, they helped me finding this solution.

How to connect several html/php files to form a complete website?

I've basically made different html files that work with php over wamp server, and I want to know how do I put them together?
For example, I have a login page. I'd like the user to be able to login and see the next html file like a main page or something.
I found the header function in php and I'd also like to know if it's the formal way of redirecting the user from page to page.
You can use HTML Links;
Next Page
You can use Header in PHP files;
header("Location:nextpage.php");
Yes use header() function of PHP to redirect user to your Home page OR Dashboard page after succeful login of a user:
header('Location: http://www.example.com/');
exit;
To add different files into one page,you can use include_once(), require_once(), include(), require() functions as per your requirement.
Click Here
If I am correct you are trying to authenticate using a PHP code and based on that redirect the user to the HTML page
You can use the following code
<?php
if(authneticate();) {
header("Location: http://www.yoururl.com/home.html");
exit;
}
else {
header("Location: http://www.yoururl.com/error.html");
exit;
}
?>

URL rewriting, same URL across multiple PHP files

Hey so I have create a login system to a website and I wish to have this login appear when I type in my address. When I have typed in details and logged in, I wish to be redirected to another PHP file, but with the same address.... this way, All I need to do is type in my address if I am allready logged in and I will go to the site which requires login.
I have made a transaction happen identifing if the session is created, if it is, it redirects me to another page, but also to another URL. I tried googleing it, but couldn't find anything exact and straight forward.
Currently:
Login page:
www.example.com
Member page:
www.example.com/members
What I wish for:
Login page:
www.example.com
Member page:
www.example.com
The program structure should look like this.
index.php
if (user is logged in)
display dashoard
else
display login page
Since you are using PHP, make use of session functions. Thus, URL rewriting is no longer necessary.
Update
Assuming if you have file structure in PHP like this:
- index.php
- login.php
+ template
- login.php
- dashboard.php
You can do the following structure in index.php file.
define('IN_FILE', true);
if (isset($_SESSION['user'])) {
require 'template/dashboard.php';
} else {
require 'template/login.php';
}
In template/dashboard.php
if (!defined('IN_FILE')) {
exit;
}
// Then your HTML, PHP and whatnot
And in login.php
if (!isset($_SESSION['user'])) {
require 'template/login.php';
} else {
header('Location: index.php');
}
Change the code according to your needs.
This can be achieved using several approaches.
a) Use session to determine the current page, so if a user click on a link, create a session store the value and on page load read the session data and include the file accordingly.
b) Use URL parameter to determine the page (this is the most common approach). for example in index.php you can add more parameters like index.php?page=somepage and by reading the value using $_GET and including the PHP file accordingly.
There are some more way to achieve what you want to, for instance using javascript/jQuery this is possible.

How can I redirect page without changing URL with PHP?

I want the following:
After logging in, A user will have assigned session variable, and the logging in page will be refreshed. The URL should not be changed at all but the page would be different.
I don't know the idea of doing that.
I know that Facebook does it. (Logging in, and logged in page url is same but different page)
I'm using nginx, PHP.
Should I some sort of rewrite URL? or some configuration on nginx? Or should I manipulate header with php in some way? then how to?
just do a conditional on an include. In general if the session does not exist you say something like
<?
if (!isset($_SESSION['user'])){ include_once("login_please.php"); exit(); }
..actual page content
?>
Use PHP to decide what to show (or which page to include) based on the session variable.
if ($_SESSION['form_submitted'] == true) {
include('content.php');
}
else include('form.php');

How can I create a button that links to another PHP page and still staying inside Facebook framework?

I am new both to PHP and new to Facebook...
I am trying to create a button that by clicking on it, the next page will be called ,
how can I do that and still remain in Facebook framework?
I tried using an HTML button with reference to next PHP page, but it took me out of Facebook framework...
and I need to use variables from the calling page.
can someone help me?
Thank!!
In PHP, you should always use a "Dispatcher" in your top level directory, and hide your other classes in subfolders, with appropriate permissions.
Doing so, here is what you can do:
index.php (dispatcher)
<?php
switch($_GET['p']) {
case 'home':
include './include/home.php';
break;
case 'anotherPage':
include './include/anotherPage.php';
break;
default:
include './include/home.php';
break;
}
?>
And now, all you have to do is to call your Facebook page like this (sorry, I don't remember the exact facebook url for application):
http://www.facebook.com/yourapp/?p=home
http://www.facebook.com/yourapp/?p=anotherPage
[EDIT]
If you want to send informations and get it back, modify your HTML form to POST data at the dispatcher like this:
<FORM METHOD=POST ACTION="./?p=anotherPage">
Than, modify the "anotherPage.php" to verify the POST data, process it and maybe set the data you want back in $_SESSION['myVariable']. Once everything is done, redirect the page to the initial one:
<?php
session_start();
if (ISSET($_POST['myData']) && $_POST['myData'] == 1) {
$_SESSION['myVariable'] = "HelloWorld";
}
header('Location: http://www.facebook.com/myApp/?p=home');
I hope this will help you with your project

Categories