I am not an expert in PHP, and all that I know comes from tuts. I try anyway to do the best I can by myself, but now I have a problem and cannot find what is causing the issue.
I made a bolg using this tutorial. The tutorial is great, easy to understand and everything, the only BUT is that they don't explain how to make a control panel/admin system. So, I made one by myself! I created a simple php/html5 file with icones for the functionalities that exist in the blog: "Add a new blog entry", "Edit an existing blog entry", "Add/manage categories" and "Log out". For the log in mechanism I used this other tutorial. Everything is working fine except for one thing:
After one has logged in the control panel and presses in one of the functions (let's say "Add a new blog entry") and then presses on the button "Back to the control panel", the system automatically logs out and forces you to log in again.
Anybody can explain me why? Bellow is the code of my control panel and the check.php which is included on the control panel (I cut off unnecessary code for other functions like slide shows, css sheets and others):
Control Panel:
<?php require('autent/check.php'); ?>
<p style="background:#48c248; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">If you can see this, you're logged in</p>
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- Rich text editor -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<body>
<div class="row">
<div class="twelve columns">
<h4>Useful links</h4>
<h5>Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result = mysql_query("SELECT FROM_UNIXTIME(timestamp, '%Y') AS get_year, COUNT(*) AS entries FROM php_blog GROUP BY get_year");
while ($row = mysql_fetch_array($result)) {
$get_year = $row['get_year'];
$entries = $row['entries'];
echo "Entries from " . $get_year . " (" . $entries . ")<br />";
}
?>
</p>
<h5>Category Archive</h5>
<p>
<?php
mysql_connect ('localhost', 'dbuser', 'dbpass') ;
mysql_select_db ('tablename');
$result1 = mysql_query("SELECT * FROM php_blog_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($result1)) {
$result2 = mysql_query("SELECT COUNT(`id`) AS entries FROM php_blog WHERE category = $row[category_id]");
$num_entries = mysql_fetch_array($result2);
echo '' . $row['category_name'] . ' (' . $num_entries['entries'] . ')<br />';
}
?>
</p>
</div>
<h4>Control panel - Manage your blog</h4>
<img src="../images/new_blog.png" title="Add a new blog entry" alt="Add a new blog entry"/><br>
<p>Add a new blog entry</p>
</div>
<div class="four columns">
<img src="../images/edit_blog.png" title="Edit a blog entry" alt="Edit a blog entry"/><br>
<p>Edit an existing blog entry</p>
</div>
<div class="four columns">
<img src="../images/cat_blog.png" title="Add/manage categories" alt="Add/manage categories"/><br>
<p>Add/manage categories</p>
</div>
<div class="four columns">
<p> </p>
</div>
</div>
<div class="four columns">
<img src="../images/logout.png" title="End your session" alt="End your session"/><br>
<p>End your session</p>
</div>
<!-- other html and footer follows -->
</body>
</html>
check.php
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
header("Location: login.php");
exit;
} else {
// the session variable exists, let's check it's valid:
require('autent/config.php');
$userexists = false;
foreach($users as $username => $password) {
if (md5($username.$password.$salt) == $_SESSION['loggedin'])
$userexists = true;
}
if ($userexists !== true) {
exit('<p style="background:#fd0000; line-height:30px; vertical-align:middle; color:#fff; font-weight:bold;">Invalid session: please login.</p>');
}
}
?>
It may because of session timeout problem.try to increase the session time by referring the following url.
How do I expire a PHP session after 30 minutes?
Session variables are stored on your server, not on the users computer like a cookie. So the user can't ever modify $_SESSION variables. It is helpful to create a boolean variable in your session that can be used as a quick flag to tell you if the user is still signed in.
When you create the session for the user, you could create a session variable like this:
$_SESSION['valid'] = TRUE;
From here on out, all you have to do is check if the session is still set to true:
session_start();
if (!$_SESSION['valid']) {
header("Location: login.php");
exit;
}
That code checks if the session is not true and if it is not, send them to login.php
When you sign them out, you can unset the session variable or just set it to false.
Related
Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!
I'm developing a php application and i have a problem retaining session values. I have two files, one is a sidebar (sidebar.php) and a home page (home.php). I have included the sidebar on the home page.
There are login controls on the sidebar and i can successfully login. I know it has successfully logged in because it shows me a message Welcome 'username'. But when i go to the home page, the welcome 'username' part is not shown as the session values are destroyed. instead the login form is shown. Why is that?
This is the home page (sidebar.php)
<?php require_once('connections.php'); ?>
<?php
// if the login button is clicked
if (isset($_POST['btnLogin']))
{
$myusername=$_POST['textusername'];
$mypassword=$_POST['textpassword'];
$result=mysql_query("SELECT * FROM users_table WHERE username='$myusername' and password='$mypassword'");
$count=mysql_num_rows($result);
if($count>=1)
{
$_SESSION['username'] = $row["username"] ;
$_SESSION['userid']= $row["ID"];
}
else
{
//Any code here
}
}
?>
<div class="col-md-12 right-aside">
<?php
if (isset($_SESSION['userid']))
{
echo Welcome : " . $_SESSION['username'];
echo " <a href='logout.php'> | Logout</a>";
}
else //if session is not set
{
echo 'Some html for login form';
}
?>
</div>
The following is the home page (home.php)
<?php include("head.php"); ?>
<body>
<div class="container container-body">
<div class="row">
<div class="col-md-9 main-content">
<div class="row">
<p>Some Text Here</p>
</div><!-- /.row -->
</div><!-- /.main-content -->
<div class="col-md-3">
<div class="row">
<?php include 'sidebar.php';?>
</div>
</div>
Are you starting a session in home.php?
You must call session_start() at the first line of every php script in which you want to access session variables.
Try adding this in top of home.
<?php
session_start();
//Then do your work
Then even if session_start is called again in head.php or sidebar.php , it will be ignored, as the session was already started.
<?php
session_start();
if(isset($_SESSION['login']))
{
include_once('includes/header.php'); ?>
<!DOCTYPE html>
<html>
<body>
<div id="mainframe">
<img src="img/header.png">
<div id="menu">
<?php include_once('includes/navbar.php'); ?>
</div>
<div id="content">
<h3>Shopping Cart</h3>
</div>
</div>
<?php include_once('includes/footer.php'); ?>
</body>
</html>
<?php }
else
{
header('location: login.php');
}
?>
Here is my small PhP code I've got at the moment, my login session is $_SESSION['login'].
And I'd like to display : Logged in As on my page when they are logged in, I've tried several things but it didn't work out.
Does anyone know a simple method / solution for this?
Put this somewhere in your if statement.
It will show Logged in as User at right top corner of page
<div style="position:absolute; right:0px; top:0px;">
<?php echo "Logged In as". $_SESSION['login']; ?>
</div>
U need to pass username using SESSION variable for the same
write a simple sql query to get the username from any variable you are taking from user to make sure that the particular user is the correct user.i am taking password.
$query = "SELECT name FROM users WHERE password='$password'";
$username = mysql_result(mysql_query($query),0);
$_SESSION['username'] = $username;
than proceed as you are doing
<?php
session_start();
if(isset($_SESSION['login']) && isset($_SESSION['username']))
{
echo "logged in as".$_SESSION['username'];
}
I am trying to make a website and it's almost completed but I want to add a view counter so when someone visit the page it count the view and save it into the database.
My script is working fine but the problem is that it continue view count even visitor is viewing anyother page
My pages url show like this
pictures.php?ID=13
I have added this PHP code in *count.php*
<?php
session_start();
if (isset($_SESSION['views'])){
$_SESSION['views']++;
} else {
$_SESSION['views'] =0;
}
//echo $_SESSION['views'];
?>
Page *views.php*
<?php
session_start();
if (isset($_SESSION['$post_id'])){
$_SESSION['$post_id']++;
} else {
$_SESSION['$post_id'] =0;
}
//echo $_SESSION['views'];
?>
<?php
echo "<hr><div align=\"center\">";
echo $_SESSION['$post_id'];
?>
<?php
$save = $_SESSION['$post_id'];
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE save_data SET Views='$save' WHERE ID='$page_id'");
mysqli_close($con);
?>
And added this line in Pictures.php where I want to show and count visits
<?php include("views.php"); ?>
Problem:
When someone visits page pictures.php?ID=8 it will show him page view 1 and save this view in database where ID=8, when he visit page pictures.php?ID=12 it will show him view 2 and save this 2 in database where ID=12. My point is that it is continuously counting instead of each page view.
Thanks in advance
Here is Pictures.php
<?php
include("connection.php");
if(isset($_GET['ID'])){
$page_id = $_GET['ID'];
$select_query = "select * from save_data where ID='$page_id'";
$run_query = mysql_query($select_query);
while($row=mysql_fetch_array($run_query)){
$post_id = $row['ID'];
$post_title = $row['Title'];
$post_image = $row['Name'];
?>
<h3>
<a href="pictures.php?ID=<?php echo $post_id; ?>">
<?php echo $post_title; ?>
</a>
</h3><center>
<form id="search-form" action="javascript:void(0);">
<input type="text" id="dimen" name="dimension" />
<input type="submit" value="Resize" Onclick ="splitString()"/></form>
<div id="sizet">
Type size like 200*300 in box
</div></center>
<div id="img"><img id="myImage" src="uploads/<?php echo $post_image; ?>" /></div>
<?php } }?>
<center>
<div id="postdetails">
<?php include("posted_by.php"); ?></center>
</div>
<?php include("views.php"); ?>
<html>
<link href="css/Pictures.css" rel="stylesheet" type="text/css">
<body>
<head>
<script type="text/javascript">
function splitString()
{
var myDimen=document.getElementById("dimen").value;
var splitDimen = myDimen.split("*");
document.getElementById("myImage").width=splitDimen[0];
document.getElementById("myImage").height=splitDimen[1];
}
</script>
</head>
</body>
Variables inside of single quotes are not evaluated, so regardless of whether $post_id is 8 or 12, $_SESSION['$post_id'] is setting the key named literally $post_id, rather than the key named 12 or 8. Variables are evaluated inside double quotes, so $_SESSION["$post_id"] would work, but the simplest and best way is to use $_SESSION[$post_id] instead.
Additionally, using $_SESSION here is probably not what you want to do. $_SESSION will be different for every user who visits the site, so when a new visitor comes to the site, it will start over with a count of 1. What you probably want to do is load the views value from the database, add one to it, and then save it back to the database. $_SESSION is for keeping data that is specific to a certain user.
Try to use structure like this
$_SESSION['view'][{resource_name}_{resource_id}]
E.g. for picture with id 8 it will be
$_SESSION['views']['picutures_8']++
I'm new to php and mysql so sorry if i'm doing it wrong. i have a page on my site that lists the reviews that members give to other other users.
Basically i have approved and deleted in my database which means that after a user sends the review it has to be reviewed by the user before it gets displayed.
once the user clicks the approved image which is a tick it goes to approved_review.php and in their i have my sql code to update the value from 0 to 1 in my database.
It should work exactly the same for the delete but obviously instead of updating the approved column it will update deleted.
the code i have tried is not working i have been working on this for quite some time and can;t figure it out.
Can someone please tell me where i'm going wrong?
Heres the code:
<?php
$reviews_set = get_pending_reviews();
while ($reviews = mysql_fetch_array($reviews_set)) {
?>
<p> </p>
<div class="pending-review-content">
<?php
$date = $reviews['date_added'];
?>
<div class="prof-content-pend-reviews" id="reviews">
<div class="message_pic"><?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">
<img width=\"50px\" height=\"50px\" src=\"data/photos/{$reviews['from_user_id']}/_default.jpg\" /></a>";?>
</div>
<div class="reviews-date"><? echo "$date"; ?></div>
<div class="reviews-from">
<?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">{$reviews['display_name']}"; ?>
</a> Wrote:
</div>
<div class="reviews-content">
<?php echo "{$reviews['content']}"; ?>
</div>
</div>
<div class="reviews-approve">
<img src="assets/img/icons/tick.png" width="30" height="25" /></div>
<div class="reviews-delete">
<img src="assets/img/icons/cross.png" width="30" height="25" />
</div>
<? } ?>
approved_review.php function:
<?
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
echo "<div class=\"infobox1\">review approved.</div>";
?>
Your approach seems logical. After you loop through your reviews, you click on the tick or delete pngs to update or delete.
So, in approved_review.php
<?php
//you are missing the connection to your mysql database...
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
//execute the mysql query
$r = mysql_query($sql);
if (!mysql_error())
{
echo "<div class=\"infobox1\">Review Approved.</div>";
}
?>
a little edit rrrfusco's post
// or die for details if mysql_query won't work correct
$r = mysql_query($sql) or die (mysql_error());