How can I use data sessions in PHP? - php

I'm trying to use data sessions for checking a form, but, when I send user and password, and programme goes to check password, this return to main page.
I write 1234 on password field, but I can't understand why this don't work correctly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Check</title>
</head>
<body>
<?php
$usuario = trim(htmlspecialchars($_REQUEST['username'], ENT_QUOTES, "UTF-8"));
$clave = trim(htmlspecialchars($_REQUEST['password'], ENT_QUOTES, "UTF-8"));
setcookie("usuario", $usuario, time()+60*60*24*365);
session_start();
$_SESSION['nom_user'] = $usuario;
$_SESSION['pass_user'] = $clave;
header('Location: nacimiento.php');
?>
Volver
</body>
</html>
Second Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fecha de Nacimiento</title>
</head>
<body>
<?php
session_start();
if (($_SESSION['pass_user'])=='1234'){
echo '<form action="check.php" method="POST">';
echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
echo '<input type="submit" name="Enviar" />';
echo '</form>';
} else {`enter code here`
header('Location: index.php');
}
?>
Volver>
</body>

session_start() must be called before any output to the browser.
Please update your code on all php pages that use the session to be included first.
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fecha de Nacimiento</title>
</head>
<body>
<?php
if (($_SESSION['pass_user'])=='1234'){
echo '<form action="check.php" method="POST">';
echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
echo '<input type="submit" name="Enviar" />';
echo '</form>';
} else {`enter code here`
header('Location: index.php');
}
?>
Volver>
</body>

Related

How to check a number is armstrong or not using php?

I made a program to check whether a number is a amstrong number or not in php. But it is not working. Cloud anyone tell me what is wrong in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="New Text Document.php" method="post">
<input type="number" placeholder="number" name="amst">
<input type="submit">
</form>
<?php
if(empty($_POST)){
exit;
}
# storing the input in a variable called amst
$amst = $_POST['amst'];
# storing the length of the input in a variable called len
$len = strlen($amst);
$add = 0;
while($amst<=0){
$div = $amst%10;
$pow = pow($div,$len);
$add+=$pow;
$amst = intval($amst/10);
}
#printing the add.
echo $add;
?>
</body>
</html>
Here I printed add just to see whether it is working properly or not. Here no matter what the input is the answer is 0. I am only getting 0. Could anyone tell me why I am getting the output as 0. I have implemented amstrong number program in other languages. This is the method I use. But here it is not working.
Your loop requires a negative number. It works only if number <0, try :
$add = 0;
while($amst>0){
$div = $amst%10;
$pow = pow($div,$len);
$add+=$pow;
$amst = intval($amst/10);
}
#printing the add.
echo $add;
if ($add=== $_POST['amst']) {
echo ‘This is an amstrong number’;
} else {
echo ‘Nope’;
}
You can check the number is Armstrong not using blow code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="post">
<input type="number" placeholder="number" name="amst">
<input type="submit">
</form>
<?php
if(empty($_POST)){
exit;
}
$num = $originalNum = $remainder = $result = 0;
# storing the input in a variable called amst
$num = (int)$_POST['amst'];
$originalNum = $num;
for($i=1;$i<=strlen($originalNum);$i++){
// remainder contains the last digit
$remainder = (int)$originalNum % 10;
//store sum of each number's cube
$result += (int)($remainder * $remainder * $remainder);
// removing last digit from the orignal number
$originalNum /= 10;
}
if ($result == $num):
echo $num." is an Armstrong number.";
else:
echo $num." is not an Armstrong number.";
endif;
?>
</body>
</html>

Sending a variable from a PHP file to another PHP file

This is a simplified version of a project I'm working on.
The main idea is that test.php sends 'acct-id' to submitData.php and it validates if the account ID already exists in the server. In case it already exists, I want to send an error message to test.php.
I have built this code but I can't get '$err_msg' to change it's value in test.php. This variable changes it's value within the 'while' loop but it does not change outside it.
How can I send $err_msg value to test.php?
Thanks in advance to all possible help.
test.php
<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="submitData.php" method="POST">
<input type="text" name="acct-id">
<input type="submit" name="submit-btn">
<?=$err_msg?>
</form>
</body>
</html>
submitData.php
<?php
include '../tools/db_config.php';
$err_msg = "test";
if(isset($_POST["submit-btn"])){
$acct_id = $_POST["acct-id"];
$sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$err_msg = "This account already exists.";
}
header('Location: test.php');
}
}else {
$output="Error en la consulta: ".$conn->error;
}
}
?>
You can use Session for this.
<?php
include '../tools/db_config.php';
session_start();
$err_msg = "test";
if(isset($_POST["submit-btn"])){
$acct_id = $_POST["acct-id"];
$sql = "SELECT * FROM accounts WHERE acct_id='$acct_id'";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$err_msg = "This account already exists.";
}
$_SESSION['err_msg'] = $err_msg;
header('Location: test.php');
}
}else {
$output="Error en la consulta: ".$conn->error;
}
}
?
<?php
include 'submitData.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="submitData.php" method="POST">
<input type="text" name="acct-id">
<input type="submit" name="submit-btn">
<?=$_SESSION['err_msg']?>
</form>
</body>
</html>

Switching output with sessions

I have a bit of code where I try to make a switch program.
Meaning that I want to have one value when clicking on a button and then another if I click it again. But I just can't figure out how.
It should echo "Yes" and then "No", front and back.
Anybody here that knows how I can solve this problem? I have been trying for hours on end, practicing my PHP.
<?php
session_start();
var_dump($_SESSION);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_SESSION['NO']) && $_SESSION['NO'] = true) {
echo "No";
$_SESSION['YES'] = true;
}
if(isset($_POST['submit'])) {
echo "Yes";
$_SESSION['NO'] = true;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="submit" name="submit" value="CHANGE">;
</form>
</body>
</html>
Use ONE session variable, like $_SESSION['STATE'] then the management of its state is simpler.
Also = is an assigment operator and == is for value comparison.
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['submit'])) {
// reverse the state
$_SESSION['STATE'] = ! $_SESSION['STATE'];
}
} else {
// page running for the first time so has not been submitted
// so initialise the session
// this will ensure you get a value output the first time the page is run
$_SESSION['STATE'] = false;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>Current State = <?php echo $_SESSION['STATE'] ? 'YES' : 'NO'; ?></p>
<form method="post">
<input type="submit" name="submit" value="CHANGE">;
</form>
</body>
</html>
Set an initial value for the session variable if it does not exist and use 1- $value ( where $value is either 1 or 0 ) to toggle the value.
<?php
session_start();
if( !isset( $_SESSION['state'] ) ) $_SESSION['state']=0;
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$_SESSION['state'] = 1 - $_SESSION['state'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<?php
if( isset( $_SESSION['state'] ) ){
echo $_SESSION['state'] ? 'Yes' : 'No';
}
?>
<form method="post">
<input type="submit" name="submit" value="CHANGE" />
</form>
</body>
</html>

Call related data with populated select from php database

i mange to populate the select by calling data on database
how will i call other data related from the value of the select using database.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<?php
$conn = new mysqli('localhost', 'root', 'a', 'emp_table')
or die ('Cannot connect to db');
$result = $conn->query("select * from emp");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
</body>
</html>
Try this
As per #Nikhil suggested the link
https://www.w3schools.com/xml/ajax_intro.asp
You can achieve this using AJAX. Time to learn the AJAX now.
For connection
If you are working on the localhost the no need to require the password. It should be blank.
I just added the onchange function to the select tag. So whatever the user selects from the dropdown it will call the function getRole and pass the Id to the process page. Process page will return the value related to the ID and display in the span tag.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "emp_table";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<select name="emp_name" id="emp_name" onchange="getRole(this.value);" >
<option selected disabled>Select</option>
<?php
$result = $conn->query("select * from emp");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['name'];
?>
<option value="<?php echo $id;?>"><?php echo $name;?></option>
<?php }}?>
</select>
<span id="emp_details"></span><!--it will display the emp record from process page-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function getRole(val){
var id=$('#emp_name').val();
$.ajax({
url:'process.php',
type:'POST',
data:'id='+id,
success:function(data)
{
//alert(data);
$("#emp_details").html(data);
},
});
}
</script>
</body>
</html>
Process.php
<?php
if (isset($_POST['id'])) {
echo $country_id=$conn->real_escape_string(trim($_POST['id']));// here you will get the id of the employee
/*your more code here*/
}
?>

Login Page Passing $_SESSION

I am not sure why the $_SESSION variable 'user' is not being passed. I do get a successful login, however when redirected to my home page the session is not kept. I use a login status php file to switch some of the nav bar items to sign/register or first name & Logout.
Login Page:
<?php
session_start();
include_once 'dbconnect_new.php';
if(isset($_SESSION['user'])!="")
{
header("Location: ../index.php");
}
if(isset($_POST['btn-login']))
{
$s_email = mysql_real_escape_string($_POST['email']);
$s_password = mysql_real_escape_string($_POST['password']);
$s_email = trim($s_email);
$s_password = md5(trim($s_password));
$res=mysql_query("SELECT student_id, student_firstname FROM studentdata WHERE student_email='$s_email' AND student_password='$s_password'");
if (!$res) {
// Debug query result by below code
//echo 'Could not run query: ' . mysql_error();
//exit;
echo '<script language="javascript">';
echo 'alert("Username / Password Seems Wrong !")';
echo '</script>';
}else{
$row = mysql_fetch_row($res);
$stu_id = $row[0];
$stu_fname = $row[1];
$_SESSION['user'] = $stu_id;
header("Location: ../index.php");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Reg Page</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td>
<input type="text" name="email" placeholder="Your Email" required />
</td>
</tr>
<tr>
<td>
<input type="password" name="password" placeholder="Your Password" required />
</td>
</tr>
<tr>
<td>
<button type="submit" name="btn-login">Sign In</button>
</td>
</tr>
<tr>
<td>Sign Up Here</td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
Login Status Page:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui">
<link href="favicon.png" type="image/x-icon" rel="shortcut icon">
<link href="assets/css/master.css" rel="stylesheet">
<script src="assets/plugins/jquery/jquery-1.11.3.min.js"></script>
</head>
<?php if(isset($_SESSION['user'])) {
$res=mysql_query("SELECT * FROM studentdata WHERE student_id=".$_SESSION['user']);
$userRow=mysql_fetch_row($res);?>
<li class="dropdown">
<a href="">
<?php echo $userRow['student_firstname'];?><span class="nav-subtitle">Account</span></a</li>
<li>Logout<span class="nav-subtitle">Goodbye</span></li>
<?php } else { ?>
<li>Register<span class="nav-subtitle">for Students</span></li>
<li>Login<span class="nav-subtitle">for Students</span></li>
<?php } ?>
</html>
Pretty sure I am just missing something simple.
I think you forget to add
session_start();
at the beginnig of the Login Status Page:

Categories