I know there are quite a few threads out there that deals with this question but every question seems unique (or so...)
I'm having trouble setting a cookie so that I can validate the user against it later
A php newbie....what might be the problem here?
I've checked the php.ini file and cookies are allowed.
<?php
$capt_error = "";
$already_made_post = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
} else {
// validate captcha
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
// write to file but only if cookie is not set
if(isset($_COOKIE[$cookie_value]) && $_COOKIE[$cookie_value] == $cookie_value) {
$already_made_post = "Du har redan ett inlägg i gästboken!";
}
else {
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
}
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
<div>
<span class="error"><?php echo $already_made_post?></span>
</div>
</div>
</form>
</body>
</html>
session_start(); should be at the top of the page for the sessions to work. In your code above it only gets called when the user submits the form. Move it to line 2.
I read your code and now I see this
setcookie($cookie_name, $cookie_value); // IS NOT SET
if(!isset($_COOKIE[$cookie_name])) {
From common pitfalls
Cookies will not become visible until the next loading of a page that
the cookie should be visible for.
You have not set the expire perameter:
Set your cookies like this
$expire=time()+60*60*24*30;
setcookie ("name","value", $expire,"/");
$expire variable holds the value time when our cookies should expire,
Related
Hi so I can't seem to find any help on this topic because there is no error being thrown. I am trying to insert records to a database via php using mysqli_query but after the re-direct no changes are made. I have three files I am working with, index.php, conn.php and new.php. index.php and new.php are located in the same folder but conn.php is one directory below.
index.php:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Khula" rel="stylesheet">
</head>
<script>
$(function()
{
$('.error').fadeOut(10000);
});
</script>
<body>
<header>
<img src="images/logo.png">
<p>The reliable bus company</p>
</header>
<div class="wrapper">
<div class="container">
<div class="titletxt">
<h4>Drivers</h4>
</div>
<?php
include '../conn.php';
mysqli_query($conn, "SET NAMES utf8");
$result = mysqli_query($conn, "SELECT * FROM tbl_employee");
echo "
<div class='table_content'>
<table align='center'>
<tr>
<th>Employee ID</th>
<th>Title</th>
<th>Name</th>
<th>Address</th>
<th>Contact Number</th>
<th>Job Position</th>
<th>Gender</th>
<th>DOB</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['employeeID'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contactNum'] . "</td>";
echo "<td>" . $row['position'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['DOB'] . "</td>";
echo "</tr>";
}
echo "</table></div>";
?>
<!-- Record Insert -->
<br>
<div class="titletxt">
<h4>Insert a Record</h4>
</div>
<h3 style="font-weight: 400; margin-left: 5px;">New Employee</h3>
<form class="insert_form" action="new.php" method="post" name="insert_form">
<label>Title: </label>
<input type="text" name="title" required><br>
<span class="error"><?php echo $titleErr ?></span>
<br>
<label>Name: </label>
<input type="text" name="name" required> <br>
<span class="error"><?php echo $nameErr ?></span>
<br>
<label>Address:</label>
<input type="text" name="address" required><br>
<span class="error"><?php echo $addressErr ?></span>
<br>
<label>Contact Number</label>
<input type="text" name="contactNum" required><br>
<span class="error"><?php echo $contactErr ?></span>
<br>
<label>Job Position</label>
<input type="text" name="position" required><br>
<span class="error"><?php echo $positionErr ?></span>
<br>
<label>Gender: </label>
<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female" required> Female<br>
<span class="error"><?php echo $genderErr ?></span>
<br>
<label>DOB: </label>
<input style="width: 60px;" type="text" name="DOB_year" required>YYYY
<input style="width: 30px;" type="text" name="DOB_months" required>MM
<input type="text" name="DOB_day" style="width: 30px" required>DD<br>
<span class="error"><?php echo $DOBErr ?></span>
<br>
<input type="submit" Value="Insert Entry">
</form>
</div>
</div>
</body>
</html>
conn.php:
<?php
$server = "localhost";
$user = "root";
$password = "";
$db = "bus_db";
global $conn;
$conn = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno())
{
echo "Mysql Error has occured" . mysqli_connect_error;
}
else if(!mysqli_connect_errno())
{
echo "<connection>Connection Established</connection>";
}
function close_connection()
{
global $conn;
mysqli_close($conn);
}
$title = $name = $address = $contact = $position = $gender = $DOB = "";
$titleErr = $nameErr = $addressErr = $contactErr = $positionErr = $genderErr = $DOBErr = "";
mysqli_query($conn, "SET NAMES utf8");
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["title"]))
{
$titleErr = "Title is Required";
}else{
$title = input($_POST["title"]);
}
if (empty($_POST["name"]))
{
$nameErr = "Name is Required";
}else
{
$name = input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid Name";
}
}
if (empty($_POST["address"]))
{
$addressErr = "Address is Required";
}else{
$address = input($_POST["address"]);
}
if (empty($_POST["contactNum"]))
{
$contactErr = "Contact Number is required ";
}else{
$contact = input($_POST["contactNum"]);
$regex = "^([0-9]{10,11})$^";
if (!preg_match($regex, $contact)) {
$contactErr = "Invalid Phone Number";
}
}
if(empty($_POST["position"]))
{
$positionErr = "Position is required";
}else{
$position = input($_POST["position"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is Required";
}else{
$gender = input($_POST["gender"]);
}
if (empty($_POST["DOB_year"]) || empty($_POST["DOB_months"]) || empty($_POST["DOB_day"]))
{
$DOBErr = "Invalid entry for date of birth";
}else
{
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
mysqli_query($conn, "INSERT INTO tbl_employee VALUES(null, '" .$p_title."', '".$p_name."', '".$p_address."', '".$p_contact."', '".$p_position."', '".$p_gender."', '".$p_DOB."')");
}
?>
new.php:
<?php
include '../conn.php';
insert_records($title, $name, $address, $contact, $position, $gender, $DOB);
header( 'Location:index.php');
close_connection();
?>
I would appreciate any, thanks
You should edit your insert_records() to give you feedback if mysqli_query fails.
function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
global $conn;
$result = mysqli_query($conn, 'some query') or die('Query failed: ' . mysqli_error($conn));
return $result;
}
and read about how you can prevent MySQL injection here: How can I prevent SQL injection in PHP?
edit:
$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
in php '+' is used to do calculations. if you want to concatenate strings use '.'
$DOB = input($_POST["DOB_year"] . "/" . $_POST["DOB_months"] . "/" . $_POST["DOB_day"]);
i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>
I am still a beginner at PHP/MYSQL and I am having difficulties inserting data into my MYSQL database. (I've originally tried using my localhost database but once i moved to an online server, everything seems to stop working.)
Right now, as soon as i submit the data from my index.php page.. it only refreshes the page and doesn't add any data.
However, when I go to submit.php, everything works fine and it adds an empty set of data to my results.php.
My codes are as follows. Any help will be greatly appreciated. Thank you!
Index.php
<html>
<head>
<title>POST variables</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="all">
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if (!$con) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo '<div class="container">
<form id="profiles">
<div class="header">
<h3>Hello there!</h3>
<p>We want to know more about you! Share a few interesting details about yourself using the form below!</p>
</div>
<div class="sep"></div>
<div class="inputs">
<form action="submit.php" method="post">
<input id="name" name="name" placeholder="Full Name" required="" autofocus="" autocomplete="on" type="text">
<input id="email" name="email" placeholder="Email Address" required="" autofocus="" autocomplete="on" type="text">
<input id="colour" name="colour" placeholder="Favourite Colour" required="" autofocus="" autocomplete="on" type="text">
<input id="music" name="music" placeholder="Favourite Song" required="" autofocus="" autocomplete="on" type="text">
<input id="superpower" name="superpower" placeholder="If you had a superhero ability, what would it be?" required="" autofocus="" autocomplete="on" type="text">
<button id="submit" type="submit"name="submit" value="added">Submit!</button>
</form> </div>
</div>';
?>
</body>
</html>
Submit.php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_POST["name"])){
$name = $_POST["name"];
} else {
$name = "";
}
if(isset($_POST["email"])){
$email = $_POST["email"];
} else {
$email = "";
}
if(isset($_POST["colour"])){
$colour = $_POST["colour"];
} else {
$colour = "";
}
if(isset($_POST["music"])){
$music = $_POST["music"];
} else {
$music = "";
}
if(isset($_POST["superpower"])){
$superpower = $_POST["superpower"];
} else {
$superpower = "";
}
$sql = "INSERT INTO profiles (name, email, colour, music, superpower) VALUES ('$name', '$email', '$colour', '$music', '$superpower')";
if(mysqli_query($con, $sql)){
header ('location: results.php'.$query_string);
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($con);
}
if($name !== "" && $email !== "" && $colour !== "" && $music !== "" && $superpower !== "") {
$query_string = '?name=' . $name.'&email='.$email.'&colour='.$colour.'&music='.$music.'&superpower='.$superpower;
header('HTTP/1.1 303 See Other');
header ('location: results.php'.$query_string);
}
?>
And my results page.
<html>
<head>
<title>POST Success</title>
</head>
<body>
<?php
$con = mysqli_connect('localhost', 'anas12_test', 'a1b2c3d4', 'anas12_test');
if(isset($_GET["name"])){
$name = $_GET["name"];
} else {
$name = "no name";
}
if(isset($_GET["email"])){
$email = $_GET["email"];
} else {
$email = "no email";
}
if(isset($_GET["colour"])){
$colour = $_GET["colour"];
} else {
$colour = "no colour:";
}
if(isset($_GET["music"])){
$music = $_GET["music"];
} else {
$music = "music";
}
if(isset($_GET["superpower"])){
$superpower = $_GET["superpower"];
} else {
$superpower = "superpower";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM profiles");
echo "<div style='border:solid 1px #ccc;padding:10px;float:left;margin-top:10px;'>";
echo "<table border='1'> <tr> <th>Name</th> <th>Email</th> <th>Favourite Colour</th>
<th>Favourite Music</th>
<th>Superhero Ability</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['colour'] . "</td>";
echo "<td>" . $row['music'] . "</td>";
echo "<td>" . $row['superpower'] . "</td>";
echo "</tr>";}
echo "</table>";
echo "</div>";
mysqli_close($con);
?>
</body>
</html>
Your form has no action, so it'll submit the form to the URL you loaded the page from, which will be index.php.
You need this:
<form id="profiles" action="Submit.php" method="POST">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note the method portion as well - with no method, forms default to using GET
Be careful you have two form in your index.php.
<form id="profiles">
and
<form action="submit.php" method="post">
I think the first one is useless.
I'm trying to clean up my code by "early exits" and keep getting a blank page everytime I use the return statement.
Should I move the php code to a seperate file?
Also I would be happy to get some tips of cleaning up my code.Thanks!!
<?php
$capt_error = "";
$mismatch = "";
$name = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
session_start();
// validate captcha
if (empty($_POST["capt"])) {
$capt_error = "Fältet är obligatoriskt.";
return null; // HERE, I GET A BLANK PAGE
} else {
if($_POST['capt'] != $_SESSION['rand']) {
$name = $_POST["name"];
$message = $_POST['message'];
$mismatch = "Inmatningen av CAPTHA är fel. Vänligen prova igen.";
}
else {
// write to file but only if cookie is not set
$ip_address = $_SERVER['REMOTE_ADDR'];
$time_stamp = date('Y-m-d H:i');
$data = "\n" . $_POST['name'] . ',' . $_POST['message'] . ',' . $ip_address . ',' . $time_stamp;
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if ($ret == false) {
die('Fel vid skrivning till fil. Skrivrättigheter saknas');
}
// set cookie
$cookie_name = $_POST['name'];
$cookie_value = $ip_address;
setcookie($cookie_name, $cookie_value, null, "/");
}
}
}
?>
<link rel="stylesheet" href="labb1.css" type="text/css">
<html>
<head>
<title>Labb 1</title>
</head>
<body>
<h1 class="title">Laboration 1 - Gästboken</h1>
<table border="1">
<thead>
<tr>
<th colspan="3" class="table-title">Min Gästbok</th>
</tr>
</thead>
<tbody>
<tr>
<td class="bold">FRÅN</td>
<td class="bold">INLÄGG</td>
<td class="bold">LOGGNING</td>
</tr>
<?php
// open file
$f = fopen("data.txt", "r");
// while not end of file
while (!feof($f)) {
// split values with -
$arr = explode(",", trim(fgets($f), "\r\n"));
print "<tr>";
print "<td>$arr[0]</td>";
print "<td>$arr[1]</td>";
print "<td>IP: $arr[2]<br>TID: $arr[3]</td>";
print "</tr>";
}
?>
</tbody>
</table>
<form action="" method="post">
<div class="border">
<div>
<span>Namn:</span>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div>
<span>Meddelande:</span>
<textarea name="message" rows="5"><?php echo $message;?></textarea>
</div>
<div>
<?php
$rand = substr(str_shuffle(str_repeat("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
session_start();
$_SESSION["rand"] = $rand;
print "<span>CAPTCHA skriv detta i rutan nedan: </span> <span class='red bold'>$rand</span>"
?>
<span class="error">* <?php echo $capt_error; ?></span>
<input type="text" name="capt">
<span class="error"><?php echo $mismatch?></span>
</div>
<div>
<input type="submit" value="Skicka">
</div>
<div>
<span class="red">*</span> är ett obligatoriskt fält
</div>
</div>
</form>
</body>
</html>
You seem to be using the return statement incorrectly in your code. The following is from the docs:
http://php.net/manual/en/function.return.php
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file.
What you seem to want to do is to capture the error message and then use it later on in your code - which is perfectly fine to do. Just set a variable with the error, continue your code and check the variables later on.
All,
I've been struggling with this and I don't know exactly what I'm doing wrong. I have a PHP file that has multiple scripts in it, including PHP and jquery sections. I'm trying to pass a PHP variable from the html Head section to the Body. Each are each in their own php script section because I have a jquery script in between, also in the Head. Below is the relevant code. How do I pass the $reset_question php variable from the top section to the bottom section?
I just added the button "submit 3" to bring up the form I'm having problems with. Maybe something in my syntax?
<head>
<?php
require_once('../connectvars.php');
session_start();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Clear the error message
$error_msg = "";
// other code that I'm not having a problem with
if (!isset($_SESSION['email'])) {
if (isset($_POST['submit3'])) {
// Grab the user-entered log-in data
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$first_name = mysqli_real_escape_string($dbc, trim($_POST['first_name']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['last_name']));
if (!empty($first_name) && !empty($last_name) && !empty($email) ) {
// Make sure someone isn't already registered using this username
$query = "SELECT * FROM user_database WHERE email = '$email' AND first_name = '$first_name' AND last_name = '$last_name'";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1) {
// The username exists
$query = "SELECT reset_question FROM user_database where email='$email'";
mysqli_query($dbc, $query);
// Confirm success with the user
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
}
exit();
}
else {
// An account doesn't exist for this e-mail
echo '<p class="error">All of your information was not recognized. Please complete the information correctly or sign-up to register.</p>';
$email = "";
}
}
else {
echo '<p class="error">You must enter all of the required data.</p>';
}
$_SESSION['reset_question'] = $reset_question;
}
}
// Insert the page header
require_once('../reference/header_sub.php');
// If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in
if (empty($_SESSION['email'])) {
echo '<p class="error">' . $error_msg . '</p>';
// closing bracket is down below
?>
// other code that I'm not having a problem with
//jquery script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
// jquery isn't having any issues that I can see
</script>
</head>
<body>
<div id="allcontent" style="position:relative;top:-20px;">
<?php
// Insert the tabbed navigation
require_once('../reference/tabs_sub.php');
?>
<br />
<fieldset>
<!-- html forms that I've not having problems with -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table class="reset">
<tr><td colspan="2" ><legend style="font-weight:bold;font-size:15px;height:25px;">Reset your password</legend></td></tr>
<tr><td class="register" ><label for="first_name">First Name:</label></td>
<td><input style="width:200px;" type="text" name="first_name" value="<?php if (!empty($first_name)) echo $first_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="last_name">Last Name:</label></td>
<td><input style="width:200px;" type="text" name="last_name" value="<?php if (!empty($last_name)) echo $last_name; ?>" /><br /></td></tr>
<tr><td class="register" ><label for="email">E-mail:</label></td>
<td><input style="width:200px;" type="text" name="email" value="<?php if (!empty($email)) echo $email; ?>" /><br /></td><td><input type="submit" value="Submit" name="submit3" class="submit3"/></td></tr>
</table>
</form>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<table class="answer">
<tr><td colspan="2" class="remember" >Please answer the following question!</td></tr>
<tr><td class="remember" >What is: <?php $_SESSION['reset_question']; ?>?</td></tr>
<tr><td ><input style="width:200px;" type="text" name="reset_answer" value="<?php if (!empty($reset_answer)) echo $reset_answer; ?>"/></td></tr>
</table>
</form>
</fieldset>
<?php
} // closing bracket from above opening bracket
else {
// Confirm the successful log-in
echo('<p class="login">You are logged in as ' . $_SESSION['email'] . '.</p>');
require_once('/download.php');
}
?>
<?php
// Insert the page footer
require_once('../reference/footer.php');
mysqli_close($dbc);
?>
</div>
</body>
it looks like your variable $reset_question only exists in the scope of the while loop
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Instead initialize the variable outside of the while loop.
$reset_question = '';
while($row = mysqli_fetch_array($data)) {
$reset_question = $row['reset_question'];
//....
}
Declare your variable out of any brackets. Just in php script scope and you will get it anywhere down in file, nothing else is needed to pass (access) it in lower script.
Best place to declare/initialize it is before
$reset_question = 'Defaut Question';
if (!empty($first_name) && !empty($last_name) && !empty($email) )
{
If you do not get anything in $reset_question in your conditions then you will get 'Defaut Question'
Upadte : One more try and i am sure you will get at least "What is Defaut Question?"
write $reset_question = 'Defaut Question'; just after $error_msg = ""; as
$error_msg = "";
$reset_question = 'Defaut Question';