I got this simple hit counter off the internet and it's exactly what I needed:
<?PHP session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']=$_SESSION['views']+1;
}
else{
$_SESSION['views']=1;
}
echo "Total page views= ".$_SESSION['views'];
?>
So I threw it in my home.html which needless to say is my homepage. I however want the views to be printed on my info.html page, but I want it displaying the hits for home.html. Does anyone know if that's possible?
Firstly you need to change your pages to .php extensions not .html if you need PHP to be compiled by the server.
There are probably a few ways of achieving what you need, however i will first point out a few things about php sessions you should know.
Session variables are available from any page on your site, providing a the session_start(); function is called first.
Sessions are essentially temp storage. In a nutshell a cookie containing a unique id is saved to the users computer. The unique id is reference to the session information stored on the server (temporarily).
For full info check out php.net
Because sessions are temp storage and they are unique to a user, you will not be able to show any users visits to the home page made by other users except themselves. To achieve this you would need to create a solution which has global and perminent storage (i.e. DB or File).
Now I will show you the solution to what you have asked, i just wasnt sure of the context, so thought i would explain the constraints.
Ok, so you should include the code below on home.php.
<?php
session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']++;
} else{
$_SESSION['views']=1;
}
?>
This is exactly the same as what you had except i removed the echo function.
Now over on the info.php page add the following.
<?php
session_start();
if(isset($_SESSION['views'])){
echo $_SESSION['views'];
}
?>
This will then display the amount of times the user has viewed home.php.
Put this in your home.html
<?PHP session_start();
if(isset($_SESSION['views'])){
$_SESSION['views']=$_SESSION['views']+1;
}
else{
$_SESSION['views']=1;
}
?>
and this on your info.html
<?PHP session_start();
if(isset($_SESSION['views'])){
echo "Total page views= ".$_SESSION['views'];
} else {
echo "no page views to show";
}
?>
But you realize that this only counts a single persons visits, sessions are per person (devise) not shared. And that person will only see his own count; until the session expires.
And you many need to home.html to home.php for this to work! or set html files to parse as php
Related
I know this is a bit stupid and there's probably a smarter way. But are there a way to generate a session variable just by visiting a specific website. What I want to do is that I want a customer to visit one website before visiting another website. And also, is there a way so a session variable can only be used once?
thanks! :)
Just to clear everything. What I didn't know existed was the unset function. I wanted the user of the website to visit the first page first, then the next and then the final page. I also wanted it in a way that if the user wants to visit the second page he/she would first have to visit the first again. It's super simple and I don't know why I didn't know this. Here's what I did:
First page:
<?php
session_start();
$_SESSION['second_page']=true;
?>
Second page:
<?php
session_start();
if ($_SESSION['second_page']==true){}
else {
header('Location: example.php');
exit;
}
unset($_SESSION["second_page"]);
$_SESSION['final_page']=true;
?>
Final page:
<?php
session_start();
if ($_SESSION['final_page']==true){}
else {
header('Location: example.php');
exit;
}
?>
I'm slowly learning PHP ;-) I'm having difficulties understanding how separate PHP-files work together.
I make AJAX calls to different php files that all need to be connected to the backend (Parse). Such as:
sign_up.php
login.php
verify_email.php
get_something_out_of_the_database.php
What is the standard way to stay logged in over the different php files? (or what is the google search term for it..?)
Update:
Thanks for all your answers about 'sessions'. I doesn't work very well yet, so i made a new question.
Thanks!
Remzo
You should use PHP sessions. These are a way to store information on visitor browser between multiple pages...
To start a session, you first need to add session_start(); in every PHP file you intend to use it. Usually it's added in a header.php
Then, you can use sessions already.
To store a result:
$_SESSION['some_data'] = $var;
To retrieve a result in another page, for example:
echo $_SESSION['some_data']; // will echo $var
More info can be found here:
http://www.w3schools.com/php/php_sessions.asp
You can do this for example by storing the login-data in a session-variable and checking it at the start of every new page.
Example:
You check if login-data is valid. Then
session_start();
$_SESSION["login"] = $loginname;
At the start of another page:
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"] != "check_somehow")
{
header("Location: logout.php");
exit;
}
For logging out you can use
session_start();
session_destroy();
On the start of your user logged in, you can do something like
session_start();
$_SESSION['USER'] = <some user info>;
In your other pages you can see if
if(isset($_SESSION['USER'])){
// do something
}
at last on logout
session_destroy();
will kill the session
I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...
So after a LOT of trial and error, I set up something to test whether my session is set or not, which looks like this :
<?php
session_start();
if (isset($_SESSION['email'])) {
echo "Logged In!";
}
else {
echo "NOT LOGGED IN!";
}
?>
And what I realize is that after Login ( which redirects to the site's homepage) The session is not set until I reload the entire homepagepage.
Has anyone experienced anything like this and/or knows how to get around such a problem?
Thanks in advance!
This snippet of code works for me as a test. Make sure your order of operations matches this. If that does not work, make sure you are allowing cookies in your browser. Failing that, there could be something screwy about your PHP/Apache configuration.
<?php
session_start();
if (!isset($_GET['test']))
{
$_SESSION['email'] = "something ".time();
header('location:?test');
die;
}else{
echo 'Value: "' .$_SESSION['email']. '"';
echo '<br /><br />< Do again';
die;
}
?>
Your pages need to be set up like so in this order (particularly the session_start()):
login.php
<?php
session_start();
// 1) Some code here to check database if username and password check out
// 2) If username and password check out and validation is good
// 3) Redirect to your next page (index.php in this case)
?>
index.php (home page)
<?php
session_start();
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><?php
if(isset($_SESSION['email'])) { ?>
EMAIL IS SET!! Great job!
<?php } else { ?>
UM...No..<?php } ?></h1>
</body>
</html>
I was having a horrible time with this. I have an index page that loads every time and inside a content div loads specific php scripts via include. I control the navigation of the website in this way by passing GET variables to the index.html, so my index page loads every single time no matter what content you're viewing. The very first line of index.html was:
<?php
session_start();
Some of my php scripts running as includes on the index page would set session variables then redirect to the index page and the session variable would not be there,, or they would not be set to what they should be. It was driving me mad, I could ctrl-F5 and sometimes they would show up and sometimes not. The only thing I can figure was that it was somehow opening different sessions for different urls that were in the address bar (by different urls I mean ones with different GET parameters. Simply putting this at the beginning of my index.html solved all my problems. I assume this causes the same session to open each time:
<?php
session_name('SessName');
session_start();
Thanks for all the help guys, but I found the problem.
Apparently I have to be extremely specific with my url in the redirect file.
I had header('location: http://domain.com');
instead of
header('location: http://www.domain.com');
...facepalm
When I have a user logged in, it redirects to this page:
<?php
session_start();
if (isset($_SESSION['LoggedIn'])){
include "content.php";
}
else {
echo "You must be logged in.";
}
?>
What I just realized is that there is nothing stopping people from just going to the content.php page if they are logged out. Yeah, it won't show much, but what is the proper way to handle this?
I think you have things set up backwards. Instead of including content.php from the page that checks whether you're logged in, have content.php include the file that contains the check. That file should do something like:
session_start();
if (!isset($_SESSION['LoggedIn']) {
die("You must be logged in.");
}
Another option is to keep your current structure, but put content.php outside the web root, so it can't be addressed directly with a URL.
The issue is you should not just have one file/function be the gateway to content being loaded. But you need to create a structure for how content is accessed. So this code:
<?php
session_start();
if (isset($_SESSION['LoggedIn'])){
include "content.php";
}
else {
echo "You must be logged in.";
}
?>
Should perhaps be tweaked & added to an authentication.php file that behaves like this:
<?php
session_start();
if (!isset($_SESSION['LoggedIn'])){
echo "You must be logged in.";
die();
}
?>
The logic is basically: Is this user logged in? Good, do whatever else needs to happen on the rest of the page. If not, echo a message blocking them & exit via die(). And then in content.php—and any other page you want restricted—you load authentication.php like so as the very first thing the page does:
<?php
require_once('authentication.php');
[...rest of `content.php` goes here...]
?>
And you always do that require_once on every page you want restricted.
In your else statement, use something like this instead:
header("location:index.php");
Basically, you are saying if the user isn't logged in, redirect them to the homepage (or whatever page you specify, like a login page).
The only way to restrict access to any page is to check that access is granted for that user on that page. That means either adding
session_start();
if (isset($_SESSION['LoggedIn'])){
}
else {
//header redirect;
}
to every page, or having a functions/config etc type of file that runs all the functions you need and include that header in there.
I'd recommend making something called init.php and including that in every page. Inside init.php you can have the code above, so you wont need to have session_start() and checking for login everytime. Keep in mind though if your functions such as data inside content.php is dependent on the user_id (meaning you have a custom page based on the user who logs on) then you have to include the init.php before you run any functions dependent on that.
For example you have a functions.php file
// get data from mysql db
function say_hi()
{
$user_id = $_SESSION['user_id']
$sql = "SELECT * FROM users WHERE `user_id` = '".$user_id."'";
$result = $db->query($sql);
while ($rows =$chaptersResult->fetch_assoc())
{
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$date_registered = $rows['date_registered'];
}
echo $first_name. " ".$last_name. "You registered on: ".$date_registered;
}
then on content.php you want to do something like you wont be able to use that unless your inti.php (which will contain your $_SESSIONs for user ids and other stuff) is called BEFORE your functions.php.
for example
content.php
<?php
require_once 'init.php';
require_once 'functions.php';
echo say_hi();
?>
The order does matter, and as you learn more you'll eventually have a config file for database connections, etc.