How to use Session in this code. Unable to understand - php

I'm trying to use Session in this basic login page. Where and how do I use Session? Thanks. I saw many examples of use of session but please pinpoint where I can add it. I am new to PHP coding.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1><b><center> Login Form</center></b></h1><br>
<form method="post" action="loginn.php">
<!--class in css can be defined and used here. need to check how?-->
<center><input type="tel" class="form-control" name="Mobile_No" placeholder="Please enter your Mobile No" required="true" style='width:30em' pattern="[0-9]{10}">
<br><br>
<center> <input type="password" class="form-control" name="Password" placeholder="Please enter password here" required="true" style='width:30em' >
<br><br>
<center> <input type="submit" class="btn btn-primary" value="Login">
</form>
<br><br><br><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.
The solution is to store that data server side, give it an "id", and
let the client only know (and pass back at every http request) that
id. There you go, sessions implemented.
You need to add session_start() to your code
session_start();
//then you can save data to your server by - $_SESSION[$key] = $value;
$_SESSION["demo"] = "Hello World";
echo $_SESSION["demo"]; // on every page will print "Hello World"

In your loginn.php page. at the top of the page start the session. like
session_start();//this
then search input Mobile_No and input Password in your data base if found then assign session variable user_id like
$_SESSION['user_id'] = $user->ID;
note: if any page already have session_start(); function then write ob_start(); function.

Related

Simple PHP to process HTML Form

I am sure this is very simple to many of you!! I am trying to learn basic HTML / PHP form processing. The site is hosted on a local Apache server. I have had PHP working correctly and am happy that the server is working fine.
I have two files, one is settings.html, where the user has a form of 3 elements which they can enter some float values into (humidity, temperature and light tolerances). The submit button triggers a separate file called process.php which should display the three values. The code is as follows:
settings.html:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
<div id="logo">
<img style="width: 335px; height: 142px;" alt="ESP8266 Logo" src="images\imgESP8266.png">
</div>
<br>
<form method="post" action="php/process.php">
Humidity Tolerance : <input type="float" name="humTolerance" placeholder="Enter %" /><br />
Temperature Tolerance : <input type="float" name="tempTolerance" placeholder="Enter %" /><br />
Light Tolerance : <input type="float" name="lightTolerance" placeholder="Enter %" /><br />
<input type="submit" value="Submit" />
</form>
</body>
<html>
php/process.php:
<?php //process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$humTolerance = $_POST["humTolerance"];
$tempTolerance = $_POST["tempTolerance"];
$lightTolerance = $_POST["lightTolerance"];
}
echo <<<_END
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
humTolerance is: $humTolerance<br>
tempTolerance is: $tempTolerance<br>
lightTolerance is: $lightTolerance<br>
</body>
</html>
_END;
?>
This is producing the HTTP ERROR 500 and I can't see why. Please can I have some help? Thanks.
As I said in comments:
"the (first) problem is in your heredoc closing identifier it contains spaces before it."
and
"the second one: type="float" isn't a valid type for an input"
You need to replace those input types with ones that are valid.
https://developer.mozilla.org/en/docs/Web/HTML/Element/input
Note that not all browsers support certain HTML5 attributes, see the above as a reference.
So use type="number" or type="text".
PHP with spaces removed before the closing heredoc identifier.
<?php //process.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$humTolerance = $_POST["humTolerance"];
$tempTolerance = $_POST["tempTolerance"];
$lightTolerance = $_POST["lightTolerance"];
}
echo <<<_END
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<meta http-equiv="refresh" content="179" >
<title>Sparks - Settings</title>
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body>
humTolerance is: $humTolerance<br>
tempTolerance is: $tempTolerance<br>
lightTolerance is: $lightTolerance<br>
</body>
</html>
_END;
?>
Use PHP's error reporting also:
http://php.net/manual/en/function.error-reporting.php
If you don't have access to logs, then set that to catch and display.

Can't figure why this INSERT INTO sql doesn't work in HTML Form [closed]

I'm having difficulties finding the trouble maker in my codes, when i try to create a "Create a Project" form, after i made a secure login system.
What i'm interested in, is to make a form that can INSERT a project into my database, after you logged in. Like my website is all about crowdfunding, and i want users to be able to create project name and a goal for their projects, at first.
I've been using a wikihow guide to make the secure login system, and it works.
Here is my code and sources:
<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';
$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login: Registration Form</title>
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
<link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
<h1>Project Register</h1>
<?php
if (!empty($error_msg)) {
echo $error_msg;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Project Name: <input type='text' name='pname' id='pname' /><br>
Project Goal: <input type="number" name="pgoal" id="pgoal" /><br>
<input type="submit" value="Create" />
</form>
<p>Return to the login page.</p>
</body>
</html>
SOURCE:
WikiHow - How to create a Secure..
The problem with your code is the follow:
This:
$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";
Doesn't do anything
But this:
$pname = $_POST['pname'];
$pgoal = $_POST['pgoal'];
$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";
$stmt = sqlsrv_query($connection, $query);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
Could do something.
NOTE
I'm not taking injection in consideration, I'm just want you to see that you need a connection.
PLUS
Some of the comments are right, you need to set variables and you are just creating a variable called $query
EDIT
your code could look more organize if you separate html from php
INSERT.PHP
<?php
include_once 'includes/register.inc.php';
include_once 'includes/functions.php';
$sql = "INSERT INTO projects (pname, pgoal) VALUES ('$pname','$pgoal')";
$plus what I added early
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login: Registration Form</title>
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
<link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<!-- Registration form to be output if the POST variables are not
set or if the registration script caused an error. -->
<h1>Project Register</h1>
<form action="insert.php" method="post">
Project Name: <input type='text' name='pname' id='pname' /><br>
Project Goal: <input type="number" name="pgoal" id="pgoal" /><br>
<input type="submit" value="Create" />
</form>
<p>Return to the login page.</p>
</body>
</html>

How to show friendlist in Custom Arrowchat

I am integrating the arrow chat trial. It is working fine for guest chat. But my requirement is chat within my friends only.
Then what type of changes to be done in integration.php file? Config.php is set as per documentation. But the notification is comes up "you must register or login to use chat". Header and footer scripts and css files are already set.
I am testing with a test.php page and set a session for userid. But integration.php is not called. So I need include this page to my test.php page, then how I fix the issue?
TEST.PHP
<?php session_start();
include_once "includes/integration.php";
$_SESSION['userid']='';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="lolkittens" />
<title>test</title>
<link type="text/css" rel="stylesheet" id="arrowchat_css" media="all" href="/development/newchat/external.php?type=css" charset="utf-8" />
<script type="text/javascript" src="/development/newchat/includes/js/jquery.js"></script>
<script type="text/javascript" src="/development/newchat/includes/js/jquery-ui.js"></script>
</head>
<body>
<form action="" method="post">
<input name="userid" type="text">
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$_SESSION['userid']=$_POST['userid'];
$return=get_user_id();
get_online_list($return,time());
}
?>
<script type="text/javascript" src="/development/newchat/external.php?type=djs" charset="utf-8"> </script>
<script type="text/javascript" src="/development/newchat/external.php?type=js" charset="utf-8"></script>
</body>
</html>

Go to next page after login in PHP [duplicate]

This question already has an answer here:
How to fix “Headers already sent” error in PHP
11 answers
I'm doing my homework that a webpage.
I created the index page as a login page that have a username input, password input and a login button.
When I click on the button, a php code (it have wroten below) have executed: it uses MySQL for login.
My problem with the login that the redirect. If the typed username and password are okay, the page should go to the next page (for example the next page's link is http://stackoverflow.com).
I use header("location:http://stackoverflow.com"); to go to the next page, but I have got the following error:
Warning: Cannot modify header information - headers already sent by (output started at /users/kzr/www/index.php:60) in /users/kzr/www/index.php on line 14
I've already tried ob_start() with ob_end_flush(), but they didn't changed the situation: the error was same.
Can anybody help me to get work this code?
Note: the PHP and the HTML codes are in once file, but I separated them.
The PHP code:
if(isset($_POST["login"])){
$username=$_POST["username"];
$password=$_POST["password"];
$connect=mysql_connect("127.0.0.1","kzr_zetr","350adagsertesborda");
if($connect){
$db=mysql_select_db("kzr_zetr");
if($db){
$query=mysql_query("SELECT * FROM login WHERE username = '$username' AND password = '$password'");
$rowcount=mysql_num_rows($query);
if($rowcount>0){
$uri="http://kzr.bplaced.de/session/?username=".$username;
header('Location:'.$uri);
print 'sucess';
}else{
echo "<script type='text/javascript'>login_f_val_phperr();</script>";
print 'fail';
}
}
}
}
The HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Bejelentkezés | ZETR</title>
<meta charset="utf-8" />
<meta name="author" content="Kókai Z. Ronald" />
<meta name="contact" content="zr.kokai#gmail.com" />
<meta name="description" content="(Konrad) Zuse Elektronikus Tanulmányi Rendszer" />
<meta name="keywords" content="konrad, zuse, konrad zuse, etr, rendszer, tanulmányi rendszer" />
<meta name="subject" content="Alkalmazott Informatika Házi Feladat Varga István Tanár Úrnak" />
<base href="http://kzr.bplaced.de" />
<link rel="stylesheet" type="text/css" href="/f/font/ubuntu/ubuntu.css" />
<link rel="stylesheet" type="text/css" href="/f/css/zetr.css" />
<link rel="stylesheet" type="text/css" href="/f/css/login.css" />
<link rel="shortcut icon" type="image/x-icon" href="/f/img/favicon.ico" />
<script type="text/javascript" src="/f/script/login-f.js"></script>
</head>
<body>
<div id="container">
<h1>Zuse</h1>
<h2>Elektronikus Tanulmányi Rendszer</h2>
<div id="loginbox">
<form name="login-f" action="" onsubmit="return login_f_val()" method="post">
<input type="text" name="username" id="username" placeholder="Felhasználónév" autocomplete="off" />
<input type="password" name="password" id="password" placeholder="Jelszó" />
<input type="submit" name="login" id="login" value="Bejelentkezés" />
</form>
</div>
</div>
</body>
</html>
It means on line 60 of index.php something is already causing the headers to be sent; make sure the headers() call is the first thing you do before sending any HTML (or plaintext) output.
Try to put an exit after your header like this :
header(...);exit;
headers need to be way above any HTML (even before doctype) and also before echoing ANY html. You will need to do it as high up as possible. And remove PRINT success and fail.

Get variable from PHP file using JQuery/AJAX

This is my first post here and I hope that someone will be able to help me.
For the past week I have been working on a project of mine. Apparently, I have stuck with the last part.
So basically, I have an AJAX chat and when I submit a line I send (using a Post method) the whole line to be analyzed (to a file named analysis.php).
The chat line is being analyzed and find the variable I needed by doing queries on a MySql Database.
All I need now, is to have this variable taken with JQuery-AJAX and put it on a div in my html file(so it can be displayed on the right-left-whatever of the chat).
Here are my files :
analysis.php
<?php
$advert = $row[adverts];
?>
ajax-chat.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX Chat</title>
<link rel="stylesheet" type="text/css" href="js/jScrollPane/jScrollPane.css" />
<link rel="stylesheet" type="text/css" href="css/page.css" />
<link rel="stylesheet" type="text/css" href="css/chat.css" />
</head>
<body>
<div id="chatContainer">
<div id="chatTopBar" class="rounded"></div>
<div id="chatLineHolder"></div>
<div id="chatUsers" class="rounded"></div>
<div id="chatBottomBar" class="rounded">
<div class="tip"></div>
<form id="loginForm" method="post" action="">
<input id="name" name="name" class="rounded" maxlength="16" />
<input id="email" name="email" class="rounded" />
<input type="submit" class="blueButton" value="Login" />
</form>
<form id="submitForm" method="post" action="">
<input id="chatText" name="chatText" class="rounded" maxlength="255" />
<input type="submit" class="blueButton" value="Submit" />
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/jScrollPane/jquery.mousewheel.js"></script>
<script src="js/jScrollPane/jScrollPane.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
So, I am basically trying to get the $advert from the analysis.php file(after the whole analyze is done) , and by using JQuery/AJAX pass it eventually to the ajax-chat.html file.
Any help is really appreciated. I have googled everything but haven't found something to help me.
Thanks in advance.
If I understand right, you need to use JSON. Here is a sample.
In your PHP write:
<?php
// filename: myAjaxFile.php
// some PHP
$advert = array(
'ajax' => 'Hello world!',
'advert' => $row['adverts'],
);
echo json_encode($advert);
?>
Then, if you are using jQuery, just write:
$.ajax({
url : 'myAjaxFile.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['ajax']); // "Hello world!" alerted
console.log(result['advert']) // The value of your php $row['adverts'] will be displayed
},
error : function () {
alert("error");
}
})
And that's all. This is JSON - it's used to send variables, arrays, objects etc between server and user. More info here: http://www.json.org/. :)

Resources