How can i show a webpage only for logged in users? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Currently I'm working on a little project for login page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users. i am using php and sql for this. i want also a logout and senf to the index but i can't find te solution. Here is my code.
<?php
require ('sql_connect.php');
if (isset($_POST['submit'])){
$username=mysql_escape_string($_POST['uname']);
$password=mysql_escape_string($_POST['pass']);
if (!$_POST['uname'] | !$_POST['pass'])
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('You did not complete all of the required fields')
window.location.href='index.html'
</SCRIPT>");
exit();
}
$sql= mysql_query("SELECT * FROM `login_users` WHERE `username` = '$username' AND `password` = '$password'");
if(mysql_num_rows($sql) > 0)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Succesfully!.')
window.location.href='homepage.html'
</SCRIPT>");
exit();
}
else{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Wrong username password combination.Please re-enter.')
window.location.href='index.html'
</SCRIPT>");
exit();
}
}
else{
}
?>
this is my control for the correct user and pass.
And here is the page i want to go if the user has logged in.
homepage.index:
<html>
<head>
</head>
<body>
<center><h1>Welcome user!</h1></center>
here some text and other stuff.
<h3>logout here<h3>
</body>
But now i can write www.mysite/homepage.index and i can go to this page without logging in. Can someone explain this?
Thank you.

Your question is part of many many available tutorials, did you try to google it first?
do not use mysql extension (using mysqli in example)
do not redirect via javascript, if you can do it via php
do not redirect to html files, when you need to work with php
do not store password as plain text (using php5.5+ function to crypt it in example)
do not select *
do not echo html code
use isset before getting value from $_POST, $_GET
Feel free to google everything to know the reasons.
<?php
class Connection //not sure what you have in sql_connect.php, I made this so the example is complete
{
static function getConnection(){
if(self::$connection === null)
self::$connection = new mysqli('127.0.0.1', 'root', '', 'so');
return self::$connection;
}
/** #var mysqli */
private static $connection;
}
<?php
class UserAuthenticator
{
function __construct(){
session_start(); //you need to start session when working with $_SESSION
}
function checkLogin(){
if(isset($_POST['submit'])){
$username = $this->getPostEscaped('uname');
$password = $this->getPost('pass'); //no need to escape through mysqli, we do not use it in query
if($username && $password){
$userData = Connection::getConnection()->query("SELECT password FROM login_users
WHERE username = '$username'")->fetch_assoc();
if($this->verifyPassword($password, $userData['password'])){
$this->login($username); //storing username for simplicity, but I do recommend to store id or some generated hash even better
$this->flash('Login succesfull.');
$this->redirect('homepage.php');
}else $this->flash('Wrong username / password combination. Please re-enter.');
}else $this->flash('You did not complete all of the required fields.');
$this->redirect('index.php');
}
}
function isLogged(){ //actual answer to the question - how to check the logged user
return isset($_SESSION['logged']);
}
function verifyPassword($password, $passwordHash){ //public so you can use it elsewhere
return password_verify($password, $passwordHash);
}
function getPasswordHash($password){ //public so you can use it elsewhere
return password_hash($password, PASSWORD_DEFAULT);
}
function showFlashMessages(){
if($flashMessages = $this->getFlashes()): ?>
<script language="JavaScript">
<?php foreach($flashMessages as $message): ?>
alert('<?= $message ?>');
<?php endforeach ?>
</script> <?php
endif;
unset($_SESSION['flashmessage']); //we need to remove messages, so they do not persist
}
function redirect($to = ''){ //you need to ensure you are not echoing any content before redirecting (that's a proper common way - learn it)
$url = 'http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
header('Location: ' . $url .'/'. $to, true, 302);
header('Connection: close');
exit;
}
private function login($userId){ //actual answer to the question - how to store the logged user
$_SESSION['logged'] = $userId;
}
private function flash($message){ //do not repeat yourself
if(!isset($_SESSION['flashmessage']))
$_SESSION['flashmessage'] = array();
$_SESSION['flashmessage'][] = $message;
}
private function getFlashes(){
return isset($_SESSION['flashmessage'])? $_SESSION['flashmessage']: [];
}
private function getPost($name, $default = null){ //do not repeat yourself
return isset($_POST[$name])? $_POST[$name]: $default;
}
private function getPostEscaped($name, $default = null){ //do not repeat yourself
return ($value = $this->getPost($name))?
Connection::getConnection()->real_escape_string($value): $default;
}
}
$ua = new UserAuthenticator();
$ua->checkLogin();
$ua->showFlashMessages();
you need to store passwords with
$ua = new UserAuthenticator();
$password = $ua->getPasswordHash($plainTextPassword); //store this to database
in homepage.php you can check logged status with
$ua = new UserAuthenticator();
if(!$ua->isLogged()){ $ua->redirect('index.php'); } //redirect to login page if not logged in
not tested anything of this, so typo is possible - sorry :)

Lets say your login was succesfull. All you have to do is this:
Session_start();
$_SESSION['id']= $row['id']; (make sure you changed mysql_num_rows to fetch assoc aswell)
Then on your index page at the top you add an if statement that checks wether or not the session has been set. For that you first need to call another session_start()
Hope this steers you in the right direction if not ill update my answer

Related

Variable from posted form stops or continues with php code after pop up box (javascript)

I have an issue with php and javascript included.
Sedning form from data index.php to edit.php
this is my edit.php file:
<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>
<?php
session_start();
// connect to database
include("connection.php");
// update records
if (isset($_POST['update'])) {
$chk=$_POST['chk'];
$manyids=implode(",",$chk);
//$id = $_POST['id'];
$name = $_POST['name'];
$time = $_POST['time'];
$user = $_POST['user'];
// if time is NULL ask if you are sure
if ($time == "") {
echo "<script type='text/JavaScript'>
ConfirmNull();
</script>";
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
else {
mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
header('location: index.php');
}
}
?>
Right now if the value time variable is NULL it should run javascript with the question: are you sure?
If YES continue with SQL and update the db.
If Cancell stop the php code and run windows.history.back and do NOT run SQL.
Unfortunately its updating the db when i hit Cancel.
PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.
So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:
document.querySelector('#myForm').addEventListener('submit', evt => {
if (evt.target.querySelector('[name="time"]').value === '') {
if (!confirm('Are you sure?')) evt.preventDefault();
}
});
And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

Trying to change from alert to popup window [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm trying to switch the "success/fail" notifications to my webpage. I've been successful doing this in several parts of my test website, but I'm running into a bit of a problem on my login page. My original way of doing this used an alert popup, which works okay, but doesn't provide the style I'm looking for. I decided to use the template that has been working for me in other parts of the website, but the login is unique since it's here where I establish my session for a user.
Here is my original login code which works as intended but uses a generic alert window...
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
}
}
mysqli_close($link);
?>
Here is the code I'm trying to get to work but comes up with
Parse error: syntax error, unexpected end of file on line 38.... which is my ?> to close out the php.
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
}
mysqli_close($link);
?>
I'm pretty sure this has to do with the quotes but I've tried several different combinations and I still get the error.
The window.open code works great on my other pages if I can keep all the if, else statements within the javascript. In these pages I just use the PHP tags to grab the parameters outside the javascript where needed.
However when I attempt to do with this with the $_Session, it doesn't work.
If this is a quotes problem, I'd appreciate it if someone could point me in the right direction. If this is related to the session, I could use some help formatting the javascript so I call the ?_Session properly.
There are so many quote issues with your code, try to put script separately or use heredoc, nowdoc.
PHP can read multiple lines with heredoc/nowdoc.
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Use delimiters and indentation correctly and you can put actual JS code in between.
Example as per your use case.
echo <<<SCRIPT
<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor="#EFEFEF"/>');
no.document.write('</br>');
no.document.write('<p style="text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px">Your credentials could not be verified</p></br>');
no.document.write('<div style="text-align:center"><button style="width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica" value="Close" onclick="window.close()"">OK</button></div>');
window.location.href = '../default.html';
</script>
SCRIPT;
Remember you can not use same kind of quote in between without escaping properly but you can also double between single and vice-versa.
I think your problem is using ' inside another '
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>...
You need to escape this char like this:
no.document.write('<p style=\'text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px\'>...

PHP script unable to gather filename of calling html page

I'm trying to have the mail.php script identify the page that called the script, and return the user to that page and if the form didn't validate, was empty, etc. When I click on submit, it just 404's.
<?php
/*
This first bit sets the email address that you want the form to be submitted to.
You will need to change this value to a valid email address that you can access.
*/
$webmaster_email = "email#email.com";
/*
This next bit loads the form field data into variables.
If you add a form field, you will need to add it here.
*/
$email_address = $_REQUEST['email'];
$comments = $_REQUEST['comment'];
$fname = $_REQUEST['first-name'];
$lname = $_REQUEST['last-name'];
$filename = debug_backtrace();
$page = $filename[0]['file'];
/*
The following function checks for email injection.
Specifically, it checks for carriage returns - typically used by spammers to inject a CC list.
*/
function isInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str)) {
return true;
}
else {
return false;
}
}
// If the user tries to access this script directly, redirect them to the feedback form,
if (!isset($_REQUEST['email_address'])) {
header( "Location: $page" );
}
// If the form fields are empty, redirect to the error page.
elseif (empty($email_address) || empty($comments) || empty($fname)) {
echo "<script type=\"text/javascript\">window.alert('Please fill in the required fields.');
window.location.href = $page;</script>";
exit;
}
// If email injection is detected, redirect to the error page.
elseif (isInjected($email_address)){
echo "<script type=\"text/javascript\">window.alert('Please, Try Again.');
window.location.href = $page;</script>";
exit;
}
// If we passed all previous tests, send the email then redirect to the thank you page.
else {
mail("$webmaster_email", "Feedback Form Results", $comments, "From: $email_address");
echo "<script type=\"text/javascript\">window.alert('Thank You for contacting us!');
window.location.href = $page;</script>";
exit;
}
?>
No need for debug_backtrace(). To get the referring page, you could replace this:
$filename = debug_backtrace();
$page = $filename[0]['file'];
With this:
$page = $_SERVER['HTTP_REFERER'];
However, $_SERVER['HTTP_REFERER'] is unreliable according to the PHP docs:
This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So another solution is to add an additional field in the referring form and retrieve it in the PHP script e.g.
<input name="referrer" type="hidden" value="<?php echo $_SERVER['PHP_SELF'];?>"/>
Then:
$page = $_REQUEST['referrer'];

delete a certain comment in comment-reply system in php

I have created a comment-reply system in php. It is similar to wall in facebook. User writes a comment and then post it in "wall". I use the following tables in my database to hold comments: comments(comments_id, comment, comment_date, user, comment_hash, flash) and table users that hold user's details: users(user_id, name, surname). Everything works perfect, the only problem is that I cannot delete a certain comment. Deleting a comment means to set flag=1 for this comment in my database.
On each comment there is a link named "delete". When user press delete, a light box starts in javascript and user by pressing delete, the function "deletepost" is executed. My only problem is that this function sets flag=1 to all comments in my databe and not for the certain comment that I press delete. Any idea how to improve my code?
I use the following function in order to display comments:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
$sql = mysql_query("SELECT * FROM comments WHERE (`flag`=0) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'> Write your first posts ...</div> ";
}
else{
while ($row= mysql_fetch_assoc($sql)) {
$comment_id = $row['comments_id'];
$hash = $row['comment_hash'];
$personal_1 = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE `user_id`='{$row['user']}' ");
while ($run_personal_1= mysql_fetch_assoc($personal_1)) {
$comment_user_id = $run_personal_1['user_id'];
$comment_user_name = $run_personal_1['name'];
$comment_user_surname = $run_personal_1['surname'];
}
// displays comment that includes user's name and surname and hash
$comments .= " $comment_user_surname $comment_user_name $hash";
$comments .= ".$row['comment'].";
//---- at this point I insert a delete link , that when user presses it a javascript light box ask user if wants to delete the comment. If user press the delete button it is called the function named "deletepost".
//---- first checks if the comment is from the user that is logged in ($session_user_id) in order to have the right to delete post
if($comment_user_id == $session_user_id){
if(isset($_POST['submit_2'])) {
deletepost($session_user_id, $comment_id);
header('Location: wall.php');
}
$comments .= <<<EOD
<font color='grey' >Delete</font>
<div id="light" class="white_content">
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="submit" name="submit_2" value="Delete Post ">
</form>
<button>Cancel</button>
</div>
<div id="fade" class="black_overlay"></div>
EOD;
}
}
return $comments;
}
?>
I use the following function in order to post comments:
<?php
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$session_user_id = $_SESSION['user_id'];
$random_num = rand(0, 99999999999);
$sql = mysql_query(" INSERT INTO `comments` (comment, comment_date, user, comment_hash) VALUES ('".$comment."', now(), '$session_user_id', '$random_num') ");
return getComments();
}
?>
I use the following function in order to delete comments. Deleting comments means that I set flag=1, and in my function that displays the comments (function getComments), if flag is equal to 1 I do not display this comment:
<?php
function deletepost($comment_user_id, $comment_id){
$get_hash = mysql_query("SELECT `comment_hash` from `comments` WHERE (`user`='$comment_user_id' AND `comments_id` = '$comment_id') ");
while ($run_hash= mysql_fetch_assoc($get_hash)) {
$hash = $run_hash['comment_hash'];
}
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comment_hash`='$hash')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
?>
My first instinct is to guess that comment_hash isn't working quite right, for whatever reason. Try simplifying your delete function:
function deletepost($comment_user_id, $comment_id){
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comments_id`='$comment_id')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
I'm not sure why your current delete function is querying your database to grab a hash from a table and then using the hash to find the same row from the same table. It seems pointless and inefficient, and introduces more things that can break.
Incidentally, Vascowhite is correct that you shouldn't be using the old mysql library, but I don't think changing that would fix your problem here.
In deletepost why did you run while loop to get the hash , if you are deleting one comment one time . Another thing is that flag=1 happens in all your comment because hash may be common for that users all comment . You need to make hash unique for every comment of a particular user .

Categories

Resources