can't send messages and $username isn't displayed - javascript

I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>&period; Image Dump&period;&period;&period;</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>

In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.

Related

How to pass variables to another php file?

I have a PHP file "login.php" That is being called in a html using a js but the elements doesnt pass the variables to another php file "ucheck_com.php" Where it will perform the validations etc. is there an alternative way to do this?
sample.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="displaylogin"></div>
</body>
</html>
<script>
$(document).ready(function() {
$(function(){
$("#displaylogin").load("user/login.php");
});
});
</script>
login.php:
<?php
require_once 'userphp/connect.php';
require_once 'userphp/ucheck_com.php';
require_once 'userphp/errors.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" lang="en-US">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<title></title>
</head>
<body>
<div class="page-container">
<form action="" method="post" class="main">
<label>Alias</label>
<input type="text" name="alias" value="">
<label>Password</label>
<input type="password" name="password">
<br />
<input type="submit" name="login_user" id="login_user" value="Login">
</form>
</div>
</body>
</html>
ucheck_com.php:
if (isset($_POST['login_user'])) {
$alias = mysqli_real_escape_string($connect, $_POST['alias']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$_SESSION['alias'] = $alias;
$_SESSION['password'] = $password;
if (empty($_SESSION['alias'])) {
array_push($errors, "Alias is required");
}
if (empty($_SESSION['password'])) {
array_push($errors, "Password is required");
}
if(count($errors) == 0) {
$result = mysqli_query($connect, "SELECT * FROM `user` WHERE `alias` = '$alias' AND `password` = '$password'");
foreach ($result as $item) {
$_SESSION['email_add'] = $item['email_add'];
$_SESSION['user_id'] = $item['user_id'];
}
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 1) {
header("location: ../index.html");
} else {
array_push($errors, "Wrong alias/password combination");
}
}
}
When you use $_SESSION you need to open the session in the following manner:
session_start();

hide and show div file (logged in)

How I can hide this - "<div class="show1">" when user are not logged in and show only when user are logged in?
This is my code --->>>
<html><head>
<meta charset="utf-8">
<title>100% | Register</title>
<link rel="stylesheet" type="text/css" href="main/home.css"/>
<link rel="stylesheet" type="text/css" href="main/register.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></head><body><div id="container">
<?php include 'header.php'; ?>
<br/><br/><div class="show1">TEXT</div><div class="show1">TEXT</div>
<div class="hidden1"><div class="right-login" id="container-login"><div id="palabi5px">
<form method="post" class="formpost" id="nonono">
<input type="text" class="username" name="username0" placeholder="Username" autocomplete="off">
<input type="password" class="password" name="password0" placeholder="********">
<button type="submit" name="login" class="loging">Login</button>
</form>
---------------------------------
<br/><br/>
Text!<br/><br/>
<br/>
---------------------------------
<br/><br/></div></div></div>
<?php include 'saites.php'; ?></body></html>
<?php
session_start();
require('connect.php');
$username0 = #$_POST['username0'];
$password0 = #$_POST['password0'];
if(isset($_POST['login'])){
if($username0 && $password0) {
$check = mysqli_query($connect," SELECT * FROM users WHERE username='".$username0."'");
$rows = mysqli_num_rows($check);
if(mysqli_num_rows($check) != 0){
while($row = mysqli_fetch_assoc($check)){
$db_username0 = $row['username'];
$db_password0 = $row['password'];
}
if($username0 == $db_username0 && ($password0) == $db_password0){
#$_SESSION["username"] = $username;
echo "<script type='text/javascript'>
$(document).ready(function(){
alert('page loaded'); // alert to confirm the page is loaded
$('.hidden1').hide(); //enter the class or id of the particular html element which you wish to hide.
$('.show1').show(); //SHOW
});
</script>";
}else{
echo "<script>{ alert('Your pass id wrong.');}</script>";
}
}else{
echo "<script>{ alert('Couldn't find username.');}</script>";
}
}else{
echo "<script>{ alert('Please fill in all the fields.');}</script>";
}
}
?>
<div class="show1">TEXT</div><div class="show1">TEXT</div>
Replace with following code
if(isset($_SESSION["username"])){
echo '<div class="show1">TEXT</div><div class="show1">TEXT</div>';
}

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

PhP login redirect stops working after applying CSS and JS to the code

I am trying to write a simple login code. The problem is that the code works and redirects to dashboard.php without any css and js files.
But as soon as include my header file,consisting of css and js, it stops working and gets stuck on auth_check.php.
Here is my code.
main index file ( index.php) - containing the login form
<?php include('header.php');?>
<?php
$message = $_GET['message'];
if($message == 1) {
echo '
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
Invalid username or password.</br> ×</button>
</div>
';
}
if($message == 2) {
echo '
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
You have successfully logged out! </br> ×</button>
</div>
';
}
?>
<div data-role="content">
<div id="loginform" > //Login form code
<form action="auth_check.php" method="post"> // form action="auth_check.php"
<div id="usernameDiv" data-role="field-contain">
<input type="text" id="name" name="username" placeholder="Username">
</div>
<div id="passwordDiv" data-role="field-contain">
<input type="password" id="password" name="password" placeholder="Password">
</div>
<div id="loginbuttonDiv" data-role="field-contain">
<button type="submit" name="submit" id="loginbutton"></button>
</div>
</form>
</div>
<?php include('footer.php'); ?>
Authorisation check (auth_check.php) (here the header(location:) doesnt work after applying js in index.php :(
<?php
include('config.php');
session_start();
include 'PasswordHash.php';
$hasher = new PasswordHash(8, FALSE);
if (!empty($_POST))
{
$username = $sql->real_escape_string($_POST['username']);
$query = "SELECT id, password, UNIX_TIMESTAMP(created) AS salt
FROM users
WHERE username = '{$username}'";
$user = $sql->query($query)->fetch_object();
if ($user && $user->password == $hasher->CheckPassword($_POST['password'],
$user->password))
{
session_register("username"); // session checker for pages
$_SESSION['username']= $username; // storing username in session
header("location: dashboard.php");
exit;
}
else
{
header("location: index.php?message=1");
exit;
}
}
?>
here is the file header.php which is causing the problem.
<?php
include('config.php');
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" type="text/css" href="custom.css">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-
1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script type="text/javascript" src="js/login.js"></script>
<head>

ajax code200 error can't connect to the url

I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>

Categories