Session is used in my project. After log in successfully, session_start() is called in my login.php page. And then it will go to another page:repair_device.php. In repair_device.php,
isset($_SESSION["admin"])&&$_SESSION["admin"]==true //this can pass
and alert("testInDR") can be showed correctly. But sql did nothing.
If I choose log on directly in repair_device.php, for example:
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
sql= "select * from hpc_repairdevice order by datetime desc" works fine.
Here is the code of login.html
<form class="login" action="index.php" method="post">
<span>account:</span><input type="text" name="username" /><br /><br />
<span>password:</span><input type="password" name="password"/><br /><br />
<span>verificationCode:</span><input type="text" name="code" /><img id="code" src="create_code.php" alt="another" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/><br /><br />
<input type="submit" style="margin-left:35%" value="logon" /><input type="reset" value="" /> </div>
</form>
Here is the code of index.php
<?php
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "wrong verificationCode!<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
}
if(!isset($_GET['log_out']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
if($user!=null & $pwd!=null)
{
try
{
$conn=new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch(PDOException $e)
{
echo "faile<br />".$e->getMessage()."<meta http-equiv='refresh' content='1;url=index.html'>";
}
if($conn)
{
$_SESSION["admin"]=true;
$stas = $conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
.....
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href='http://xx.xx.xx.xx/repair_device.php'";
echo "</script>";
.....
}
}
}
?>
Here is the code of create_code.php
<?php
session_start();
//create pic
header("Content-type: image/png");
.....
$_SESSION['code'] = $verifyCode; //stor verification code in session
......
?>
Here is the code of repair_device.php
<!DOCTYPE html>
<html>
<head>
......
</head>
<body>
<?php
session_start();
// $conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
//$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
$admin=false;
if(isset($_SESSION["admin"])&&$_SESSION["admin"]==true)
{
alert("testInDR");
$sql = "select * from hpc_repairdevice order by datetime desc";
......
$sel=$conn->query($sql);
......
}
?>
</body>
</html>
I suppose session id should be passed to repair_device.php, but I don't know how. Who can help me ?
A database connection isn't passed with the session. One popular way is to have a DB bootstrap file that is included at the head of any page that needs access to the database (Or an autoloader).
<?php //index.php, repair_device.php
require_once('db.php');
//rest of page
And in the db page you setup your connection (and probably start the session)
<?php // db.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
Then the result that would be rendered by PHP would be
<?php // index.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
//rest of page
Including the connection on any page that needs it simply requires the one line of code.
Related
I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
I have my pin.php as:
<?php //connection $db_host="localhost"; $db_username="root";
$db_password="";
$connection =
mysql_connect("$db_host","$db_username","$db_password");
if (!$connection){ die("database connection failed: ".
mysql_error()); }
session_start([
'cookie_lifetime' => 120, ]); //Start a new session (2 minutes)
?> <html> <head> <title>Check Result</title> </head> <body> Check
Result<br /><br /> <?php $dbname = "db";
$db_sel=mysql_select_db($dbname,$connection);
if(!$db_sel) {
echo "<h1>Unable to Connect to the Database</h1><hr />";
exit();
}
// Check submit button click
if(isset($_REQUEST['submit'])) { if (!empty($_POST['uname']) &&
!empty($_POST['pass'])) { $serial =
stripslashes(trim($_POST['serial'])); $pin =
stripslashes(trim($_POST['pin']));
$sign = mysql_query("SELECT * FROM pin WHERE serial='$serial' AND
pin='$pin'");
$no=mysql_num_rows($sign); //if username and password matches if($no!=0)
{
$_SESSION['serial']=$serial; $_SESSION['pin']= $pin;
$logintimes=mktime();
$ipaddress=$_SERVER['REMOTE_ADDR'];
//Redirects the user to the password protected page
header("Location: result.php");
exit();
} else{ // if invalid serial/pin echo "Invalid";
} } else{ // if empty on submit echo "empty";//empty”; } } ?>
<form action="print.php" method="post"> Serial Number: <input
type="text" name="serial" value="" class="style3" size="18"/><br />
PIN: <input type="hide" name="pin" class="style3" size="18"/><br />
<input type="submit" name="submit" value="Login" class="button" />
</form> </body> </html>
and my result.php as:
<?php
session_start([ 'cookie_lifetime' => 120, ]); if(isset($_SESSION['serial']) && ($_SESSION['pin'])) { ?>
<h3>Welcome</h3> <div> This is your result...<br /> <?php
$logintimes=mktime();
$ipaddress=$_SERVER['REMOTE_ADDR'];
echo $logintimes; echo $ipaddress; ?> </div> <?php session_destroy(); } else { //Redirects the user to the login page
if he is not logged in header("Location: index.php"); } ?>
On submit, it's still accessing result.php without checking if serial=$serial AND pin=$pin
Guys I looked into this a little. tried to clean it up so its more readable, and I would suggest at least templating out the page and use replace('tag',function()) method to enter data into the template.
<?php //connection $db_host="localhost"; $db_username="root";
$db_password="";
$connection = mysql_connect("$db_host","$db_username","$db_password");
if (!$connection){
die("database connection failed: ".mysql_error());
}
session_start([
'cookie_lifetime' => 120, ]); //Start a new session (2 minutes)
?> <html> <head> <title>Check Result</title> </head> <body> Check Result<br /><br /> <?php
$dbname = "db";
$db_sel=mysql_select_db($dbname,$connection);
if(!$db_sel) {
echo "<h1>Unable to Connect to the Database</h1><hr />";
exit();
}
// Check submit button click
if( isset($_REQUEST['submit'])) {
if (!empty($_POST['uname']) && !empty($_POST['pass'])) {
$serial = stripslashes(trim($_POST['serial']));
$pin = stripslashes(trim($_POST['pin']));
$sign = mysql_query("SELECT * FROM pin WHERE serial='$serial' AND pin='$pin'");
while ($row = mysql_fetch_array($sign, MYSQL_NUM)) {
$_SESSION['serial'] = $serial;
$_SESSION['pin'] = $pin;
$logintimes = mktime();
$ipaddress = $_SERVER['REMOTE_ADDR'];
//Redirects the user to the password protected page
header("Location: result.php");
exit();
} // if success above will exit, else get to the below error note.
echo "Invalid";
}
} else { // if empty on submit
echo "Please enter you name or password FooL";//empty”;
}
}
?><form action="print.php" method="post"> Serial Number: <input type="text" name="serial" value="" class="style3" size="18"/><br /> PIN: <input type="hide" name="pin" class="style3" size="18"/><br /> <input type="submit" name="submit" value="Login" class="button" /> </form></body> </html>
I didn't test it, but you can see I replaced the n$no with a row pull, the point you need to understand is the row count will be zero because you haven't yet pulled the row, the point is still at the start.
When I click form submit button session variable lost and it shows message that session is not set. I have another confusion that it has only problem when I set session of login variable or those variables which are set in other page of my site.When I set some random session variable on the top of this page it works fine and session variable does not lose anymore. I have also checked some other related links in stack overflow but nothing found solution
Here is the code of addProduct.php page
<?php
//var_dump($_SESSION);
if(!(isset($_SESSION['login']))) {
echo "session is not set";
}
else {
//header("location:index.php");
echo "session is set";
//$user_email=$_SESSION['user_email'];
?>
<html>
<body>
<form action="addproduct.php" method="post">
<input type="text" name="name" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
// $_SESSION['user_email']=$_SESSION['user_email'];
echo $name;
}
?>
<?php }
?>
Code of index.php (header file) page from where I get into this page
<?php
session_start();
include("db.php");
?>
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<title>Home</title>
</head>
<body>
Home</br></br>
<?php if(isset($_SESSION['login']) ) {
if($_SESSION['user_status']=="admin")
{
?>
Post an Ad</br></br>
<?php }
}
?>
<?php if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email']))
{
?>
<?php echo $_SESSION['user_fname'] . " " . $_SESSION['user_lname'] . " " . $_SESSION['user_status']; ?></br></br>
<?php
}
else
{
?>
Login</br></br>
SignIn</br></br>
<?php }
if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email']))
{
?>
Logout</br></br>
<?php }
?>
<div id="content">
<?php
if(isset($_GET['page']))
{
$p=$_GET['page'];
$page = $p . ".php";
//echo $page;
if(file_exists($page))
{include($page);
}
elseif($page=="")
echo "this is home page";
else
{echo "Not found";}
}
else
{
include ("showAds.php");
}
?>
</div>
</body>
</html>
Code of login.php
<?php
session_start();
if(isset($_SESSION['user_fname']) && isset($_SESSION['user_lname']) && isset($_SESSION['user_email'])) {
header("location:index.php");
exit();
}
else
{
?>
<html>
<head><title>Login</title></head>
<body>
<form action="login.php" method="post">
<input type="email" name="user_email" placeholder="USER EMAIL" REQUIRED>
<input type="password" name="user_password" placeholder="USER PASSWORD" REQUIRED>
<input type="submit" name="Go" value="SUBMIT!" placeholder="USER NAME" REQUIRED>
</br></br>SignIn with new account</br>
</form>
<?php
include("db.php");
/*if(isset($_POST['Go'])) { SIGNUP
$user_name = $_POST['user_name'];
$user_password = $_POST['user_password'];
$user_email = $_POST['user_email'];
echo $user_name . "<br>";
echo $user_email . "<br>";
echo $user_password . "<br>";
$sql = "INSERT INTO user(user_name,user_email,user_password) VALUE ('$user_name','$user_email','$user_password')";
if(mysqli_query($conn,$sql))
{
echo "stored";
header("location:http://localhost/window.php");
}
else
{
die(mysqli_error($sql));
}
}*/
if(isset($_POST['Go']))
{
$user_email = $_POST['user_email'];//real_escape_string
$user_password = $_POST['user_password'];
$login_query="SELECT * FROM user WHERE user_email='$user_email' AND user_password='$user_password'";
$run=mysqli_query($conn,$login_query);
if(mysqli_num_rows($run)>0)
{
$res = mysqli_query($conn, "SELECT * FROM ecommerce.user WHERE user_email='$user_email'");
while ($record = mysqli_fetch_array($res)) {
$_SESSION['user_fname']=$record['user_fname'];
$_SESSION['user_lname'] = $record['user_lname'];
$_SESSION['user_status'] = $record['user_status'];
$_SESSION['user_id'] = $record['user_id'];
$_SESSION['user_password'] = $record['user_password'];
}
$_SESSION['user_email']=$user_email;
$_SESSION['login']="true";
//echo $_SESSION['user_fname'] . $_SESSION['user_lname'];
header("location:index.php");
exit();
}
else
echo "<p style='color: red; margin-top: -28px;'>User name or password incorrect</p>";
}
?>
</body>
</html>
<?php }?>
This error you showed in your other question which was marked as an exact duplicate of this one:
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\ecommerce\showAds.php on line 2
Your showAds.php page which you didn't include, (most likely) contains session_start(); and it should be removed from inside that file.
index.php has an include and session_start();
else
{
include ("showAds.php");
}
So one of your if statements failed.
That is why you're getting that error.
All pages using sessions require that session_start(); be included and should be the first line of your script, which isn't shown in addProduct.php.
Also make sure you're not outputting before header. If you are, consult the following on how to fix it:
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
You have to add session_start(); in your addProduct.php to be able to access session contents!
I'm making a php login that will redirect you to "admin.php" when you have logged in, this is my code so far, it worked when I echoed the rows with the username and password in, but when I added in a if and else statement it just gives me a blank screen with no error or anything. Here is my code:
NOTE: I have changed the mysql database details, but I have tested them and they all connect.
<?php
mysql_connect("mysqlserver", "myusername", "mypassword);
mysql_select_db("mydatebase");
?>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$user = $_POST['user'];
$pass = $_POST['password'];
$result = mysql_query("SELECT * FROM user WHERE name='$user' AND pass='$pass'");
$num = mysql_num_rows($result);
if($num == 0) {
echo "Incorrect UserName or Password. Please try again."; session_start();
}else{
session_start();
$_SESSION['user'] = $user;
header("Location: admin.php");
}
?>
<form action='login.php' method='post'>
UserName: <input type='text' name='user' /><br />
Password: <input type='password' name='password' /><br />
<input type='submit' name='submit' value='Login' />
</form>
<?php
}
?>
</body>
</html>
Seems you have syntax error in
mysql_connect("mysqlserver", "myusername", "mypassword);
you have lack in double quote
this should be
mysql_connect("mysqlserver", "myusername", "mypassword");
and the way of connection must be this way
$con = mysql_connect("mysqlserver", "myusername", "mypassword");
mysql_select_db("mydatebase",$con);
P.S
Stop using mysql_connect instead use mysqli or PDO
the reason is mysql is now Deprecated
You have an error in your PHP script and error_reporting (or display_error) is turned off, and therefore you are seeing a white blank page.
This is the error: you forgot a double quote
mysql_connect("mysqlserver", "myusername", "mypassword);
-----------------------------------------------------^
Try this:
mysql_connect("mysqlserver", "myusername", "mypassword");
If this doesn't fix your problem, you must have an error somewhere else.
Try adding these two lines at the begining of your PHP script to find the error:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
upgrade to mysqli_ or at least use mysql_real_escape()
Split the 2 files
Blank page means, you don't have error reporting turned on so enable it.
login.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action='login.php' method='post'>
UserName: <input type='text' name='user' /><br />
Password: <input type='password' name='password' /><br />
<input type='submit' name='submit' value='Login' />
</form>
</body>
</html>
login.php:
<?php
if(isset($_POST['user'], $_POST['password'], $_POST['submit'])){
$con = mysql_connect("mysqlserver","username","password", "mydatebase");
if(!$con)
{
die('Could not connect : ' . mysql_error());
}
$user = $_POST['user'];
$pass = $_POST['password'];
$query = sprintf("
SELECT * FROM user WHERE name='%s' AND pass='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($pass);
$result = mysql_query($query,$con);
if(!$result)
{
die('Could not execute : ' . mysql_error());
}
if(mysql_num_rows($result) > 0){
session_start();
$_SESSION['user'] = $user;
header("Location: admin.php");
}else{
echo "Incorrect UserName or Password. Please try again.";
}
mysql_close($con);
}else{
echo "missing form values";
}
I have a page with a who does a post to the same page. I want that page to be refreshed with new data after a succesful database INSERT.
Let me add some code.
default.php
<?php
session_start();
require("dbconfig.php");
include("head.php");
//if user is not signed in, redirect to login page
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<body>
<div id="menu">
<?php
include("menu.php"); //include the menu
?>
</div>
<div id="page_content">
<?php
include ($p); //Include selection from menu.php
?>
</div>
?>
dbconfig.php
<?php
DEFINE ('DB_USER', 'someuser');
DEFINE ('DB_PASSWORD', 'somepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'somedatabase');
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
die('Connection to the specified database couldn\'t be established');
mysql_select_db(DB_NAME) or
die ('Specified database couldn\'t be selected');
function db_escape ($post)
{
if (is_string($post) ) {
if (get_magic_quotes_gpc() ) {
$post = stripslashes($post);
}
return mysql_real_escape_string ($post);
}
foreach ($post as $key => $val) {
$post [$key] = db_escape($val);
}
return $post;
}
?>
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<?php
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
This code may not be pretty but it works. It succesfully adds a new record to the database however I want the page/cities.php to be refreshed with my ny record after the post. Is this possible?
Let me add that this i my first ever php page. I've only read some books so don't bash me for beeing a bad programmer :)
Yes, just move your insert part to above your select part.
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
You can also refresh a page with javascript :
<script type="text/javascript">
document.location = "URL"
</script>
Read up on the Post-Redirect-Get pattern, and redirect the browser to the same page after saving the record. The redirect should be done through PHP's header function.
As your code works now, someone refreshing through F5 will insert the same value again... P-R-G avoids this problem.
Just do the
if(isset($_POST['submit'])){
//yada yada
before you do the select