I have a page with a contact form.
I'm trying to make some error messages appear next to the fields if the fields are empty/invalid. If all fields are OK the field's contents are sent to a database.
The validation itself works. If the fields are empty or invalid it does not submit them into the database. However no error messages are shown next to the fields.
Here are the codes
Page with the contact form named palaute3.php:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
$servername = "localhost";
$username = "username";
$password = "passwd";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Over</title>
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tyyli1.css"/>
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Press+Start+2P');
</style>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="menuBG">
</div>
<ul class="navlist">
<li>Etusivu
</li>
<li>Leffat
</li>
<li>Pelit
</li>
<li>Ota yhteyttä
</li>
</ul>
<div id="content">
<h3>Palaute</h3>
<p>Anna Palautetta sivujen ulkonäöstä tai vinkkejä uusiksi arvosteluiksi!</p>
<p><span class="error">Kaikki kentät ovat pakollisia</span></p>
<form method="post" action="validointi.php">
<table width="450px">
<tr>
<td valign="top">
<label for="nimi">Nimi</label>
</td>
<td valign="top">
<input type="text" name="nimi" /><span class="error"><?php echo $_SESSION["nimiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="sposti">Sähköposti</label>
</td>
<td valign="top">
<input type="text" name="sposti" /><span class="error"><?php echo $_SESSION["spostiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="palaute">Palaute</label>
</td>
<td valign="top">
<textarea name="palaute" maxlength="1000" cols="30" rows="6"></textarea><span class="error"><?php echo $_SESSION["palauteVirhe"];?> </span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Lähetä" name="submit">
</td>
</tr>
</table>
</form>
<?php
session_unset();
?>
<p>
Palautteet tähän
</p>
<?php
$sql = "SELECT id, palaute FROM dbtable";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Palaute: " . $row["palaute"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
<div id="footer">
<p>© Game Over 2018 All rights reserved</p>
</div>
</div>
</body>
</html>
Here is the validation:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
if (isset($_POST['submit'])) {
if (empty($_POST["nimi"])) {
$_SESSION["nimiVirhe"] = " Nimi on pakollinen.";
}
else {
$nimi = $_POST["nimi"];
$_SESSION["nimi"]=$nimi;
if (!preg_match("/^[a-zA-Z ]*$/",$nimi)) {
$_SESSION["nimiVirhe"] = " Nimi on väärässä muodossa.";
}
}
if (empty($_POST["sposti"])) {
$sposti = $_SESSION["sposti"];
$_SESSION["spostiVirhe"] = " Sähköposti on pakollinen.";
}
else {
$sposti = $_POST["sposti"];
$_SESSION["sposti"]=$sposti;
if (!filter_var($sposti, FILTER_VALIDATE_EMAIL)) {
$_SESSION["spostiVirhe"] = " Sähköpostiosoite on väärässä muodossa.";
}
}
if (empty($_POST["palaute"])) {
$_SESSION["palauteVirhe"] = "<br>Palaute on pakollinen.";
}
else {
$palaute = $_POST["palaute"];
$_SESSION["palaute"]=$palaute;
}
if($_SESSION["nimiVirhe"] == "" && $_SESSION["spostiVirhe"] == "" && $_SESSION["palauteVirhe"] == ""){
header("Location: yhteystesti.php");
return;
} else {
header("Location: palaute3.php");
return;
}
}
?>
The database insertion works fine so I'm not going to include it here.
Any idea what am I doing wrong here?
PS: This is a school assignment and the teacher tried to make it work but couldn't.
Ath the top of your palaute3.php file you have this
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
So you re-init your session error messages before using this them.
Those 3 lines should be in the validation page, but not in your error page !
Remove that and it will work.
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 4 years ago.
Good morning everybody I've made this simple page that should update my database following some tutorials around the internet but still not updating the data when I press the submit button, can somebody help and correct the code ? I just need to update the ID from this table, I think this code can be helpful for many people out there... I'm going to paste the code below. Many thanks.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id_cus = $_GET["id_cus"];
$sql = "SELECT `id_customer`, `firstname`, `lastname`, `email` FROM `customer` WHERE `id_customer` = $id_cus";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row["id_customer"];
$nome = $row["firstname"];
$cognome = $row["lastname"];
$email = $row["email"];
}
} else {
echo "0 results";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</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">
<link rel="stylesheet" href="./panel.css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<main>
<form action="" method="post">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Codice cliente</th>
<th class="col">Nome</th>
<th class="col">Cognome</th>
<th class="col">Indirizzo email</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="id" value="<?php echo $id ?>"/></td>
<td><?php echo $nome; ?></td>
<td><?php echo $cognome; ?></td>
<td><?php echo $email; ?></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Aggiorna" class="pull-right">
</form>
</main>
</div>
</div>
</div>
</body>
</html>
<?php
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
// check that firstname/lastname fields are both filled in
if ($id == '')
{
// generate error message
echo 'ERROR: Please fill in all required fields!';
}
else
{
// save the data to the database
$conn->query("UPDATE customer SET id_customer='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: panel.php?id_cus=$id");
}
}
}
$conn->close();
?>
EDITED CODE TRYING ANOTHER SOLUTION bust still does not update why ? this should be very simple!
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$databaseHost = 'localhost';
$databaseName = 'dbname';
$databaseUsername = 'dbuser';
$databasePassword = 'pass';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
if(isset($_POST['update']))
{
$id = $_POST['id'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
// checking empty fields
if(empty($fistname) || empty($lastname) || empty($email)) {
if(empty($firstname)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($lastname)) {
echo "<font color='red'>lastname field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE customer SET firstname='$firstname',lastname='$lastname',email='$email' WHERE id_customer=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT `id_customer`, `firstname`, `lastname`, `email` FROM `customer` WHERE `id_customer` = $id");
while($res = mysqli_fetch_array($result))
{
$firstname = $res['firstname'];
$lastname = $res['lastname'];
$email = $res['email'];
$id_customer = $res['id_customer'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="panel.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="firstname" value="<?php echo $firstname;?>"></td>
</tr>
<tr>
<td>Lastname</td>
<td><input type="text" name="lastname" value="<?php echo $lastname;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" name="id_customer" value="<?php echo $id_customer;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
</html>
So I'm working on this page and I have an error somewhere in my code as the page is not being displayed.
The code is fine until line 27 as when I try to load the page both echo statements are executed.
The page also loads fine when I comments out the $results statement which is line 28. I just cant seem to fine whats wrong with it.
Code is posted below:
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
if(!empty($_POST))
{
$connect = new mysqli("localhost", "username", "password", "dbname");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
$connect->query($sql);
}
$id = $_SESSION['id'];
echo $id;
$sql = "SELECT * FROM requestedOff where employeeId='".$id."'";
echo $sql;
$result = $connect->query($sql);/*******THIS IS LINE 28********/
if(!$result){
echo $connect->error;
}
?>
<!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>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request Day Off</title>
</head>
<body bgcolor="">
<div id="wrapper">
<div class="float left">
<?php navigation(); ?>
</div>
<div class="float right">
<h3>Request a Day Off</h3>
<form action="dayOffRequest.php" method="post">
<p><?php print $error; ?></p>
<table align="center">
<tr>
<td>Date</td>
<td><input type="text" name="date" placeholder="YYYY/MM/DD"/></td>
</tr>
<tr>
<td>Reason for Request</td>
<td><textarea class="width" type="text" name="reason" height="50px"></textarea></td>
</tr>
</table>
<p><input type="submit" value="Submit" /></p>
</form>
<hr />
<h3>Submitted Requests</h3>
<table align="center">
<tr>
<th>Date</th>
<th>Approved</th>
</tr>
<?php
while($row = $result->fetch_assoc())
{
print "<tr>";
print "<td>".$row['day']."</td>";
print "<td>".$row['approved']."</td>";
print "</tr>";
}
?>
</table>
</div>
</div>
</body>
</html>
try this one -
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
if(!empty($_POST))
{
$connect = new mysqli("localhost", "username", "password", "dbname");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
$connect->query($sql);
}
$id = $_SESSION['id'];
echo $id;
$sql = "SELECT * FROM requestOff where employeeId='".$id."'";
echo $sql;
$result = $connect->query($sql);/*******THIS IS LINE 28********/
if(!$result){
echo $connect->error;
}
?>
<!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>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request Day Off</title>
</head>
<body bgcolor="">
<div id="wrapper">
<div class="float left">
<?php navigation(); ?>
</div>
<div class="float right">
<h3>Request a Day Off</h3>
<form action="dayOffRequest.php" method="post">
<p><?php print $error; ?></p>
<table align="center">
<tr>
<td>Date</td>
<td><input type="text" name="date" placeholder="YYYY/MM/DD"/></td>
</tr>
<tr>
<td>Reason for Request</td>
<td><textarea class="width" type="text" name="reason" height="50px"></textarea></td>
</tr>
</table>
<p><input type="submit" value="Submit" /></p>
</form>
<hr />
<h3>Submitted Requests</h3>
<table align="center">
<tr>
<th>Date</th>
<th>Approved</th>
</tr>
<?php
while($row = $result->fetch_assoc())
{
print "<tr>";
print "<td>".$row['day']."</td>";
print "<td>".$row['approved']."</td>";
print "</tr>";
}
?>
</table>
</div>
</div>
</body>
</html>
So as it turns out I had put the connect function inside the if statement so when the form wasnt being submitted there was no connection to the database. I fixed it by moving the connection function outside of the if
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
$connect = new mysqli("localhost", "username", "password", "db");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
if(!empty($_POST))
{
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
}
$result = $connect->query("SELECT * FROM requestedOff where employeeId='1'");
?>
I have successfully created a form that submits data and a picture of a user into my online folder and the path directory stored in the database.
My question is this how do I get users to see their picture once they are logged in?
Well Guys thanks for everything but still not getting right here is all my code
Sign Up
<!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>Untitled Document</title>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:328px;
height:216px;
z-index:1;
left: 347px;
top: 111px;
}
-->
</style>
</head>
<body>
<div id="apDiv1">
<form method="post" action="logon.php" enctype="multipart/form-data">
<table width="332" height="210" border="0">
<tr>
<td width="155">Email</td>
<td width="167"><input type="text" name="email" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td>Upload Passport</td>
<td><label>
<input type="file" name="photo" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="submit" value="Sign Up" />
</label></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Logon.php
<?php
include('connection.php');
if (!isset($_FILES['photo']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['photo']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['photo']['tmp_name']));
$image_name= addslashes($_FILES['photo']['name']);
move_uploaded_file($_FILES["photo"]["tmp_name"],"photos/" . $_FILES["photo"]["name"]);
$email=$_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
$photo="photos/" . $_FILES["photo"]["name"];
$save=mysql_query("INSERT INTO info (id, email, user_name, password, photo) VALUES ('','$email','$username','$password','$photo')");
/* Redirect visitor to the thank you page */
echo '<script language="javascript">alert("Registration Succesful....")</script>';
echo '<script language="javascript">window.location = "index.php"</script>';
exit();
}
?>
Index.php
<?php
include('login.php'); // Includes Login Script
?>
<!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>Untitled Document</title>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:391px;
height:178px;
z-index:1;
left: 334px;
top: 166px;
}
#apDiv2 {
position:absolute;
width:259px;
height:115px;
z-index:1;
left: 380px;
top: 137px;
}
-->
</style>
</head>
<body>
<div id="apDiv2">
<form method="POST" action="">
<table width="260" height="88" border="0">
<tr>
<td width="131">Username</td>
<td width="119"><label>
<input type="text" name="username" />
</label></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="submit" value="Submit" />
</label></td>
</tr>
</table>
<table width="259" border="0">
<tr>
<td align="center">Sign Up</td>
</tr>
</table>
</form>
<p> </p>
</div>
</body>
</html>
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "User ID or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = #mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("lesson", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from info where password='$password' AND user_name='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: customer_login.php"); // Redirecting To Other Page
} else {
$error = "User ID or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
customer_login.php
<?php
include('session_connect.php');
?>
<html>
<body>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:259px;
height:173px;
z-index:1;
left: 25px;
top: 92px;
}
-->
</style>
<div id="apDiv1">
<p>Email: <?php echo $email; ?> </p>
<p>Username: <?php echo $username; ?> </p>
<p>Password: <?php echo $password; ?> </p>
<p>Passport: <?php echo $photo; ?> </p>
</div>
</body>
</html>
session_connect.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = #mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("lesson", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select * from info where user_name='$user_check'", $connection);
$row=mysql_fetch_array($ses_sql);
$login_session =$row['user_name'];
$email = $row['email'];//." ".$row['vLastName'];
$username = $row['user_name'];
$password = $row['password'];
$photo = $row['photo'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
Instead the above code shows me the pathway in the database i want the actual image to show...thank you
When you store the Image path in the database, there must be a reference (Foreign key or similar) to the corresponding user.
Now, when the user loggs in, you check the table, where your image paths are declared for the specific user:
SELECT imgpath FROM imgpathstable WHERE userid = $loggedInUser["id"]
and then you can display an img tag with:
<?php
echo "<img href='$imgPath' ...
<?php
if(isset($_SESSION['Anyone']))
{
?>
<img src="<?php echo image path ?>"/>
<?php
}
?>
currently I am working on a script that allows you to signup and login. Signup is working perfectly but my Login is showing me an error(i.e. Error - Invalid login. No such user exists(the last line of php script, even the user exists) . My mysql table is users1. My codes for both login form and its processing are as follow--
<?php
include 'dbc.php';
$err = array();
foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}
if ($_POST['doLogin']=='Login')
{
foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}
$email = $data['email'];
$pass = $data['password'];
if (strpos($email,'#') === false) {
$user_cond = "username='$email'";
} else {
$user_cond = "email='$email'";
}
$result = mysql_query("SELECT `id`,`password`,`full_name`,`approved` FROM users1 WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$password,$full_name,$approved) = mysql_fetch_row($result);
if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";
//header("Location: login.php?msg=$msg");
//exit();
}
//check against salt
if ($password === password($pass,substr($password,0,9))) {
if(empty($err)){
// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.
// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['username'] = $full_name;
$_SESSION['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users1 set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("username",$_SESSION['username'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Members' Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#logForm").validate();
});
</script>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td width="160" valign="top"><p> </p>
<p> </p>
<p> </p></td>
<td width="732" valign="top"><p> </p>
<h3 class="titlehdr"><b>Login</b>
</h3>
<p>
<?php
if(!empty($err)) {
echo "<div class=\"msg\">";
foreach ($err as $e) {
echo "$e <br>";
}
echo "</div>";
}
?></p>
<form action="login.php" method="post" name="logForm" id="logForm" >
<table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="38%">Username / Email</td>
<td width="62%"><input name="usr_email" type="text" class="required" id="txtbox" size="25"></td>
</tr>
<tr>
<td>Password</td>
<td><input name="password" type="password" class="required password" id="txtbox" size="25"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input name="remember" type="checkbox" id="remember" value="1">
Remember me</div></td>
</tr>
<tr>
<td colspan="2"> <div align="center">
<p>
<input name="doLogin" type="submit" id="doLogin3" value="Login">
</p>
<p>Register Free<font color="#FF6600">
|</font> Forgot Password <font color="#FF6600">
</font></p>
</div></td>
</tr>
</table>
<div align="center"></div>
<p align="center"> </p>
</form>
<p> </p>
</td>
<td width="196" valign="top"> </td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
</table>
</body>
</html>
If you need more details about problem ask me
instead of the if(strpos($email,'#')) try this instead it will make your search dynamic as you want, you will need to pass to parameters $username and $email like so:
SELECT `id`,`password`,`full_name`,`approved` FROM users1
WHERE 1 = 1
AND ($email IS NULL OR email = $email)
AND ($username IS NULL OR username = $username)
AND `banned` = '0'
Note that you have to use PDO or prepared statements instead of the way you use to connect to mysql databases.
I need some help with my code. It works on XAMPP on my computer but when it's live on my server it won't work all I get is a blank screen. You can have a look what happens at <a href="http://www.redhotessentials.com/prototype/pages/login.php</a> put username allanallan password allanallan and you can see what happens thanks
<?php
if (isset($_POST['email'])) {
//Connect to the database through our include
require("db.php");
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check>0){
while($row = mysql_fetch_array($sql)){
// Get member ID into a session variable
$id = $row['id'];
session_register('id');
$_SESSION['id'] = $id;
// Get member username into a session variable
$username = $row['username'];
session_register('username');
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE members SET lastlogin=now() WHERE id='$id'");
// Print success message here if all went well then exit the script
header("location: endlessnails_blog.php");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br />
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login to your profile</title>
<link rel="stylesheet" type="text/css" href="../../css/main4.css" />
<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) {
valid = true;
if ( document.logform.email.value == "" ) {
alert ( "Please enter your User Name" );
valid = false;
}
if ( document.logform.pass.value == "" ) {
alert ( "Please enter your password" );
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
</head>
<?php include("header.php"); ?>
<?php include("nav.php"); ?>
<body>
<div id="container">
<div id="box3">
<div align="center">
<h3 id="login2"><br />
<br />
Log into Endless Nails Blog<br />
<br />
</h3>
</div>
<div id="loginformmove">
<table class="style7" align="center" cellpadding="5">
<form action="index.php" method="post" enctype="multipart/form-data" name="logform"
id="logform" onsubmit="return validate_form ( );">
<tr>
<td class="style7"><div align="right">Email Address:</div></td>
<td class="style7"><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
</tr>
<tr>
<td class="style7"><div align="right">Password:</div></td>
<td class="style7"><input name="password" type="password" id="password" size="30" maxlength="24" /></td>
</tr>
<tr>
<td class="style7"> </td>
<td id="login3"><input name="Submit" type="submit" value="Login" class="login_pad" /></td>
</tr>
</form>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
Remove the enctype from your FORM attributes, since you are not Uploading files, just use the method="POST"