Sorry! my bad..
This code displays a User registration form, does validation on post and saves info to a file.
<html>
<head>
<style>
#main {
width: auto;
padding: 25px;
border: 25px solid green;
margin: 25px;
}
input[type=text]{
display:inline-block;
border: 1px solid #999;
height: 25px;
margin-bottom: 2em;
padding: .75em .5em;
}
input[type=password]{
display:inline-block;
border: 1px solid #999;
height: 25px;
margin-bottom: 2em;
padding: .75em .5em;
}
input[type=submit] {
color:#08233e;
font:bold 2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:90%;
cursor:pointer;
border: 2px solid blue;
}
.error {
color: #FF0000;
font: italic bold 15px arial;
}
</style>
</head>
<body>
<div id="main">
<?php
require_once 'Mail.php';
//dns101.comcast.net, Smtp.comcast.net
$fname = $lname = $uname = $pwd = $cpwd = $email = "";
$firsterr = $lasterr = $unameerr = $pwderr = $pwdmatch = $emailerr = "";
$isError=false;
if (isset($_POST['submit'])) {
validateInput();
if ($isError) {
display_form();
}
else {
process_form();
}
}
else {
display_form();// display form for the first time
}
function display_form() {
global $firsterr, $lasterr, $unameerr, $pwderr, $pwdmatch, $emailerr ;
echo "<h1>Registration</h1>";
echo "<form action = $_SERVER[SCRIPT_NAME] method=post>";
echo "<span class='error'> $pwdmatch </span><br><br>";
$value=isset($_POST['fname'])?$_POST['fname']:'';
echo "First Name:<input type='text' name='fname' size='50' maxlength='80' value=\"$value\" >";
echo "<span class='error'> $firsterr </span><br>";
$value=isset($_POST['lname'])?$_POST['lname']:'';
echo "Last Name:<input type='text' name='lname' size='50' maxlength='80' value=\"$value\" >";
echo "<span class='error'> $lasterr </span><br>";
$value=isset($_POST['email'])?$_POST['email']:'';
echo "Email:<input type='text' name='email' size='50' maxlength='80' value=\"$value\" >";
echo "<span class='error'> $emailerr </span><br>";
$value=isset($_POST['uname'])?$_POST['uname']:'';
echo "User Name:<input type='text' name='uname' size='50' maxlength='80' value=\"$value\" >";
echo "<span class='error'> $unameerr </span><br>";
echo "Password: <input type='password' name='pwd' size='50' maxlength='80' >";
echo "<span class='error'> $pwderr </span><br>";
echo <<<HTML
Confirm Password: <input type="password" name="cpwd" size="50" maxlength="80" ><br>
<input type="submit" name="submit" value="Submit">
</form>
HTML;
}
function cleanData($data) {
$data = stripslashes(trim($data));
$data = htmlspecialchars($data);
return $data;
}
function validateInput(){
global $firsterr, $lasterr, $unameerr, $pwderr, $pwdmatch, $emailerr, $isError;
//check if fname, lname and user name are empty
if(empty(cleanData($_POST['fname']))){
$firsterr="* first name is required";
$isError=true;
}
if(empty(cleanData($_POST['lname']))){
$lasterr=" * last name is required";
$isError=true;
}
if(empty(cleanData($_POST['uname']))){
$unameerr="* user name is required";
$isError=true;
}
// check email format
$pattern = '/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/';
if(preg_match($pattern,cleanData($_POST['email']))==0){
$emailerr="* a valid email-address is required.";
$isError=true;
}
if(strcmp($_POST['pwd'],$_POST['cpwd'])){
$pwdmatch="*** Your password did not match your confirmed password ***";
$isError=true;
}
if(empty($_POST['pwd'])){
$pwderr="* password cannot be empty";
$isError=true;
}
}
function process_form() {
$data_dir = "data";
// the users.txt file stores the users' information
$file = "$data_dir/users.txt";
if ($fh = fopen ($file, 'a+bt')) {
// create directory for user based on time the user registered and a random value.
// This guarantees that the directory is unique and has a valid name.
$dir = time().rand(0, 4596);
// create the data to be written (on Windows add \r\n)
// use the crypt() to encrypt the password.
$data = $_POST['fname']."|".$_POST['lname']."|".$_POST['uname']."|".$_POST['email']."|".$_POST['pwd']."|".crypt($_POST['pwd'],$dir)."|".$dir."\r\n";
// write the data and close the file
fwrite ($fh, $data);
// close the directory in the data directory
mkdir ("$data_dir/$dir");
// print a message
echo "Thank You $_POST[fname] $_POST[lname] for registering. <br>";
// loop through the file by reading 1000 bytes or one line
// whichever comes first with each iteration.
// The data being read is broken into an array using | as delimiter.
rewind($fh);
while ($line = fgetcsv($fh, 1000, "|")) {
// check the file data against the submitted data
if (($line[2] == $_POST['uname']) && ($line[5] == crypt($_POST['pwd'], $line[6]))) {
echo "<p>Here is your information: </p>";
echo $line[0]."|".$line[1]."|".$line[2]."|".$line[3]."|".$line[4];
// stop looking through the file
break;
}
}
fclose ($fh);
}
else {
// couldn't write to the file
echo "<p>You couldn't be registered due to a system error.</p>";
}
$message = "
<html>
<head>
<title>Sending an HTML Message</title>
</head>
<body>
<h2>Thank you for registering</h2>
<h2 align=center>Your user name is {$_POST['uname']}<br><br>Your password is: {$_POST['pwd']}</h2>
</body>
</html> ";
$msgHeader = "From: infoFromRuchi#itu.com\r\n";
$msgHeader .= "MIME-Version: 1.0\n";
$msgHeader .= "Content-type: text/html; charset=us-ascii\n";
// Send email
$test= mail($_POST['email'], 'Registration Confirmation', $message, $msgHeader);
//echo $test;
echo "<p>You will receive an email confirming your registration.</p>";
}
?>
</div>
</body>
</html>
If success, it reads back info from file and sends a confirmation email to the user.
This runs (except the email part) on my local but when I ftp to domain server, it renders a blank page. It is displaying the other pages fine so there has to be some issue in my code on this page.
I have found the answer.
The empty function only takes a variable and cannot be used like:
empty(cleanData($_POST['fname']))
Using (strlen(cleanData($_POST['fname']))==0) has solved the issue.
Related
I hosted my website on a localserver using xampp. So I was trying to access the website from another computer which was on the same network. I could access the index.html file that had to enter login details like the username and password but when I hit submit, I don't get to php page which should show the details of the user by retrieving it from the database. How am I suppose to access the php file too?
I was able to access the phpmyadmin page too from the other computer but can't access the php page as it says "the site can't be reached. localhost refused to connect"
My html code
<!DOCTYPE html>
<html>
<head>
<title>Login to Student's Database</title>
<style>
label {
font: normal 12px courier !important;
}
.sbm{
padding: 10px;
margin-left: 50px;
}
.whole{
background-image: url("images/bg-01.jpg");
background-attachment: fixed;
width: 1340px;
height: 640px;
background-repeat: repeat-x;
}
p {
font: bold 20px sans-serif;
padding: 20px;
}
</style>
</head>
<body>
<div class="whole">
<div align="center">
<form name="hun" method="post" action="http://localhost/exam/retrieve.php">
<p>Welcome To Student's Record</p>
<label for="user" > Username :</label>
<input type="text" name="username"><br><br>
<label for="pass"> Password :</label>
<input type="password" name="pass"> <br><br>
<div class="sbm"><input type="submit" name="submit"></div>
</form>
<div align="center">
</div>
</body>
</html>
My php code
<?php
$puser = $_POST['username'];
$ppass = $_POST['pass'];
$con = mysqli_connect('localhost','root','','student');
if(!$con)
{
die("Could not connect".mysql_error());
}
$pss=$ppass;
$usr=$puser;
$flag=0;
$que = "select * from rec";
$q = mysqli_query($con, $que);
if(!$q)
{
echo "Could not retrieve!";
}
else
{
while($ret = mysqli_fetch_array($q, MYSQLI_NUM))
{
if(($pss==$ret[1])&&($usr==$ret[0]))
{ $flag=1;
echo "Welcome to University<br>";
echo "Name = ";
echo $ret[2] . "<br>";
echo "Roll = ";
echo $ret[3]."<br>";
echo "Physics = ";
echo $ret[4]."<br>";
echo "Chemistry = ";
echo $ret[5]."<br>";
echo "Maths = ";
echo $ret[6];
}
}
}
if(!$flag)
{
echo "Wrong username or password";
}
?>
I'm trying to create a banning system for a chat that I made and it has a separate "console" only seen by admins. Im using Mac OS 10.11.4, I am the owner and am using Mamp with php version 5.6.10
Ban.php
<?php
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
//example ip addresses
if ($ban === '1.1.1.1' || 192.168.1.132) {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
Chat.php:
<?php
require "blocked.php";
require "connect.inc.php";
require "core.inc.php";
require "commands.php";
$sent = $_POST['chat'];
$myfile = fopen("chat.txt", 'a') or die("Unable to open file!");
$txt = ($sent."\n");
$first = getuserfield('username');
$active = ($first.":".$ip_addr);
$activef = fopen("ip-user.txt", 'a');
$myFile = "domains/domain_list.txt";
if (loggedin()) {
echo 'Welcome, '.$first,'<br />';
if ($first != 'SnR' || 'Koi') {
fwrite($activef, $active."\n"."=");
}
} else if (!loggedin()) {
die('Not logged in');
}
if (isset($_POST['chat'])) {
if (!empty($sent)) {
fwrite($myfile, $first.': '.$txt.'=');
fclose($myfile);
} else if (empty($sent)) {
echo 'Cant send an empty message','<br />';
}
}
$file = "chat.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$linecount++;
}
fclose($handle);
if ($linecount > 49) {
unlink($file);
} else {
echo 'Line count: '.$linecount,'<br />';
}
echo 'Chat will reset at 50 lines','<br />';
echo 'Your IP:';
echo $ip_addr,'<br />';
?>
<html>
<head>
</head>
<body>
<!-- <a href='active.txt'>Online users</a><br /> -->
<iframe id='reload' src='refresh.php'>
<fieldset class="field">
<div id="list"><p><?php
$filename = 'chat.txt';
$handle = fopen($filename, 'r');
$detain = fread($handle, filesize($filename));
$chat_array = explode('=', $detain);
foreach($chat_array as $chat) {
echo $chat.'<br />';
}
?></p></div>
</fieldset>
</iframe>
<form action="chat.php" method="POST">
<input type="text" name="chat" class="textbox">
<input type="submit" value="Send" class="button">
</form>
</body>
</html>
<?php
if ($first == 'SnR' && 'Koi') {
include 'AdminCMD.php';
include 'ban.php';
?>
<iframe id='reload' src='refresh2.php' class="field2">
<fieldset class="field">
</fieldset>
</iframe>
<?php
}
?>
The problem is that everything is fine until you give an input, no matter what you put into the box the output is always "Can't ban an Admin" meaning that it doesn't write to the given file
Thank you for any help.
Your code contains an error, preventing the file from being written. The first line of PHP code,$ban = $_POST['ban'];, could fail if no post data was sent. You need to first check if the $_POST['ban'] was set. A fixed version of your code can be found below.
<?php
//Makes sure ip banned it not an admins
if (isset($_POST['ban'])) {
$ban = $_POST['ban'];
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
When i ran your code it returns undefined index ban, you can try this and make sure what is not working for you.
<?php
$ban = isset($_POST['ban']) ? $_POST['ban'] : null;
$mybfile = fopen("banned.txt", 'a');
$txtb = ($ban." , ");
//Makes sure ip banned it not an admins
if(isset($ban)){
if ($ban === '1.1.1.1') {
echo 'Can\'t ban an Admin';
} else {
echo 'IP banned';
fwrite($mybfile, $txtb);
fclose($mybfile);
}
}
?>
<style>
.ban {
background-color: black;
width:30em;
height:5em;
color: #7ACC52;
}
.buttonBAN {
border:1px solid black;
width: 85px;
height: 55px;
background-color: white;
color: black;
position: absolute;
}
</style>
<body>
<form method="POST">
BanCMD<br />
<input type="text" name="ban" class="ban">
<input type="submit" value="Enter" class="buttonBAN">
</form>
</body>
I'm pretty new to html, php, mysql and i have to like learn the basics # my new workplace.
I'm having an annoying problem with my Form Validation. I'm using ubuntu server in combination with PuTTY
My problem is: that my 'Validation' and 'empty Field' check is not working propperly.
So when i go into my browser, my Form (Table) shows up as it should. When I hit the Submit button WITHOUT writing any stuff into the fields, the Form stays on the page and my Errors appear: ("Name is required, email, Nachname") That's right so far.
But when i fill in anything into the field(s), and then hit the Submit button, the form just disappears and i get like a blank page (but still having my CSS background n stuff).
No matter if comes up to the requirements, or not.
I'm trying to find out whats wrong since 3 whole days 9hrs/day # my workplace.
So hopefully anyone of you can help me finally get this thing work.
everything i post now is in the same order as i have it in my PuTTy
(nano)
My script starts like this:
CSS:
<html>
<head>
<title> Formular FINAL </title>
<style>
body {
background-image: url("http://fewpict.com/images/background-pictures/background-pictures-01.jpg");
}
.db_table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
overflow: hidden;
overflow-y: auto;
position: fixed;
top: 80%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
height: 100px;
}
.db_table td, tr {
color: white;
text-align: center;
}
.center_div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.center_div td {
font-family: "Comic Sans", Comic Sans MS, cursive;
color: white;
text-align: left;
}
.error {color: #FF0000;}
</style>
</head>
<body>
PHP-Form Validation:
<?php
$VornameErr = "";
$emailErr = "";
$NachnameErr = "";
$Vorname = $_POST['Vorname'];
$email = $_POST['email'];
$Nachname = $_POST['Nachname'];
$allesok = "";
//input type hidden
if(isset($_POST['action'])){
//ÜBERPRÜFUNGSVARIABLE
$allesok = 1;
$errors = array();
if (empty($_POST) === false) {
$required_fields = array('Vorname', 'Nachname', 'email');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true ){
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
}
//Vorname Überprüfen
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vorname"])) {
$allesok = 0;$VornameErr = "Name is required";
} else {
$Vorname = test_input($_POST["Vorname"]);
if (!preg_match("/[a-zA-Z]{3,}/",$Vorname)) {
$allesok = 0;$VornameErr = "Only letters and atleast 3 alpha characters Allowed";
}
}
}
if (empty($_POST["email"])) {
$allesok = 0;$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$allesok = 0;$emailErr = "Invalid email format";
}
}
//Nachname Überprüfen
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Nachname"])) {
$allesok = 0; $NachnameErr = "Nachname is required";
} else {
$Nachname = test_input($_POST["Nachname"]);
if (!preg_match("/[a-zA-Z]{3,}/",$Nachname)) {
$allesok = 0;$NachameErr = "Only letters and atleast 3 alpha characters Allowed";
}
}
}
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
MySQL:
if ($allesok) {
define('DB_NAME', 'formular');
define('DB_USER', 'David');
define('DB_PASSWORD', '****');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
if(isset($_POST['sent'])) {
$value1 = $_POST['Vorname'];
$value2 = $_POST['Nachname'];
$value3 = $_POST['email'];
$sql = "INSERT INTO formular (Vorname, Nachname, email) VALUES ('$value1', '$value2', '$value3')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
} else {
$msg1='<p> Your information was submitted successfully.</p>';
}
}
Echo Form:
if(isset($_POST['sent'])) {
?>
<div class="center_div">
<table>
<tr>
<td style="width: 200px;">Vorname: </td>
<td style="border-bottom: 1px solid black;"><?php echo $_POST['Vorname']; ?> </br></td>
</tr>
<tr>
<td style="width: 200px;">Nachname: </td>
<td style="border-bottom: 1px solid black;"><?php echo $_POST['Nachname']; ?> </br></td>
</tr>
<tr>
<td style="width: 200px;">E-Mail: </td>
<td style="border-bottom: 1px solid black;"><?php echo $_POST['email']; ?> </br> </td>
</tr>
</table>
<input type="button" value="Zurück" onClick="history.back();">
</div>
<?php
echo $msg1."<br /><br /><br />";
//Liste anzeigen
} elseif(isset($_POST['show_table'])) {
//fake formular <-----was made for still having the possibility to fill out stuff when i view the LIST
echo "<div class='center_div'>";
echo "<form action='toto2.php' method='POST'/>";
echo"<table>";
echo "<tr>";
echo "<th></th>";
echo "<th></th>";
echo "<th>span class='error'>* required field.</span></th>";
echo "<tr>";
echo "<td style= 'width: 200px;' > Vorname:* </td>";
echo "<td> <input type='text' name='Vorname' placeholder='Your Vorname...' /></td>";
echo "<td><span class='error'>*$VornameErr </span></td>";
echo "</tr>";
echo "<tr>";
echo "<td style='width: 200px;'> Nachname:* </td>";
echo "<td> <input type='text' name='Nachname' placeholder='Your Nachname...' /></td>";
echo "<td><span class='error'>*$NachnameErr</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td style='width: 200px;'> E-Mail:* </td>";
echo "<td><input type='email' name='email' placeholder='Your E-Mail address...' /></td>";
echo "<td><span class='error'>*$emailErr</span></td>";
echo "</tr>";
echo "</table>";
echo "<input type='submit' value='SEND' name='sent' />";
echo "<input type='submit' value='Einträge anzeigen' name='show_table' />";
echo "<input type='button' value='Einträge ausblenden' onClick='history.back();'>";
echo "</div>";
echo "</form>";
//DB Tabelle
$query = "SELECT * FROM formular;";
$result = mysql_query($query);
echo '<div class="db_table">';
echo '<table>';
echo '<tr>';
echo '<th>ID</th>';
echo '<th>Vorname</th>';
echo '<th>Nachname</th>';
echo '<th>email</th>';
echo '</tr>';
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "</tr>";
}
echo '<tr>';
echo '<td>';
echo '<input type="button" value="Zurück" onClick="history.back();">';
echo '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
}
} else {
?>
HTML Form:
<div class="center_div">
<span class="error"></span>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<th></th>
<th></th>
<th><span class="error">* required field.</span></th>
<tr>
<td style= "width: 200px;" > Vorname:* </td>
<td> <input type="text" name="Vorname" placeholder="Your Vorname..." /></td>
<td><span class="error">* <?php echo $VornameErr;?></span></td>
</tr>
<tr>
<td style="width: 200px;"> Nachname:* </td>
<td> <input type="text" name="Nachname" placeholder="Your Nachname..." /></td>
<td><span class="error">* <?php echo $NachnameErr;?></span></td>
</tr>
<tr>
<td style="width: 200px;"> E-Mail:* </td>
<td><input type="text" name="email" placeholder="Your E-Mail address..." /></td>
<td><span class="error">* <?php echo $emailErr;?></span></td>
</tr>
</table>
<input type="hidden" name="action" value="1">
<input type="submit" value="SEND" name="sent" />
<input type="submit" value="Einträge anzeigen" name="show_table" />
<input type="button" value="Einträge ausblenden" onClick="history.back();">
</form>
</div>
<?php
}
mysql_close();
?>
</body>
</html>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've checked and re checked and I don't know what I'm doing wrong. No errors are showing up, it just directs me no where after I submit a login page.. any suggestions?
header:
<html>
<head>
<title><?php echo $title; ?></title>
<style type ="text/css">
#top_links a:link, a:visited{
width: 100%;
display: block;
font-weight: bold;
color: #FFFFFF;
background-color: black;
text-align: center;
padding: 4px;
text-decoration: none;
text-transform: uppercase;
border: none;
font-family: "Trebuchet MS", Helvetica, sans-serif;
}
#top_links ul{
display: table-row;
}
#top_links li{
display: table-cell;
margin: 0;
}
#top_links a:hover {
color: pink;
}
</style>
</head>
<body<div id="top_links">
<ul>
<li>Register</li>
<li>Login</li>
</ul>
</div>
LOGIN.php file:
<?php
require_once('../../../secure_files/mysql_connect.php');
$title = 'Login';
include_once('header.php');
if(isset($_POST['validate'])) {
$errors = array();
function validate_func($value, $msg, $val_type) {
global $link;
switch ($val_type) {
case 'string':
if(empty($value)){
$errors[] = "You forgot to enter your email ".$msg;
}else{
$value = mysqli_real_escape_string($link, trim($value));
}
break;
case 'password':
if(empty($value)) {
$errors[] = "You forgot to enter your email ".$msg;
}else{
$value = trim($value);
}
break;
case 'number':
if(!isset($value)||!is_numeric($value)) {
$error[] = "You forgot to enter ".$msg." or the value you entered is not a number.";
}else{
$value = trim($value);
}
break;
}
return $value;
}
$email = validate_func($_POST['email'], "email", "string");
$password = validate_func($_POST['password'], "password", "password");
if(!count($errors) != 0){
foreach($errors as $value) {
echo $value." <br />";
}
}else {
$select_guest = "SELECT GUEST_INFO_ID FROM GUEST_INFO WHERE EMAIL = '$email' AND PASSWORD = sha1('$password') LIMIT 1";
$exec_select_guest = #mysqli_query($link, $select_guest);
if(mysqli_num_rows($exec_select_guest) != 1) {
echo "You are not an authentic user, you are being directed to the registration page...";
mysqli_close($link);
header("Refresh:3; url='REGISTRATION_FORM&HANDLE.php'");
}else{
$one_record = #mysqli_fetch_row($exec_select_guest);
setcookie('GUEST_INFO_ID', $one_record[0], 0, '/', '', 0, 0);
echo "You are an authentic user";
header("Refresh:3; url='GUEST_MAIN_MENU.php'");
}
}
} else{
?>
<div id="LOGIN_MAIN">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method = "post" >
<div>
Email:<input type="text" name="email" id="email" />
</div>
<div>
Password:<input type='password' name='password' id='password' />
</div>
<div>
<input type='submit' name='submit' id='submit' value='Submit' />
<input type='reset' name='reset' id='reset' value='Reset' />
<input type="hidden" name="validate" ID="validate" value="Reset" />
</div>
</form>
</div>
<?php
}
include('footer.php');
?>
and my footer:
</body>
</html>
The reason is, that you echoed something before you set the headers.
Any header MUST be before any other output to be valid.
See the php-manual for header()
So remove
echo $value." <br />";
echo "You are not an authentic user, you a...";
or any output before the header-redirection and it'll work!
If you want to redirect AFTER the user has seen the response, you will have to work with a javascript redirection!
That would then be something like this:
<script>
// redirects after 3 seconds
setTimeout(function(){
window.location.href = "GUEST_MAIN_MENU.php";;
}, 3000);
</script>
Sidecomment:
Anyway, I would recommend to test the user credentials without loading a new (or the same) php-script again. Have a look at javascript ajax! Using this technique the user will stay on the same page and get a more immediate response that your app also can react to with messages and redirections.
I have an inc file (test_form4.inc) which defines the form that collects a user's name and phone number.
<!doctype html>
<?php
/* Program name: form_test4.inc
* Description: Defines a form that collects a user's
* name and phone number.
*/
$labels = array( "first_name" => "First Name",
"middle_name" => "Middle Name",
"last_name" => "Last Name",
"phone" => "Phone");
$radios = array( "New", "Changed");
$submit = "Submit Phone Number";
?>
<html>
<head>
<title>Form 2</title>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
}
.field {padding-bottom: 1em;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
.submit {
margin-left: 35%;
}
-->
</style>
</head>
<body>
<h3>Please enter your phone number below</h3>
<?php
/* loop that displays the form */
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
foreach($labels as $field => $label)
{
echo "<div class='field'><label for='$field'>$label</label>
<input id='$field' name='$field' type='text' value='".#$$field."'
size='50%' maxlength='65' /></div>\n";
}
echo "<div class='field'>
<input type='radio' name='status' checked='checked'
value='new' style='margin-left: 25%'/>$radios[0]
<input type='radio' name='status'
value='changed' style='margin-left: 1em' />$radios[1]</div>\n";
echo "<div><input type='hidden' name='submitted' value='yes' /></div>\n";
echo "<div class='submit'>
<input type='submit' name='phoneButton' value='$submit'></div>";
?>
</form>
</body>
</html>
... and a php file which checks for blanks or validates the form called (checkBlankOnly2.php)
<?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "middle_name")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("form_test4.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$radio_patt = "/(new|changed)/";
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/status/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if(#sizeof($error_array) > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("form_test4.inc");
exit();
}
else
{
echo "Data is all okay";
}
}
else
{
include("form_test4.inc");
}
?>
I can not figure out where my error comes, which I'm certain the problem is with the phone number. My lesson said that the phone number preg_match is for the numbers formats 555-5555 or (888) 555-5555, still when I insert all my data like: first name, last name and phone number in these formats I got the error "not a valid phone number".
Please help me, I can't figure it out.
Thanks.
The field phoneButton is seen as a phone number because it passes your condition if (preg_match("/phone/i",$field)), it's value "Submit Phone Number" then gets validated as a phone number, thus generating the error "Submit Phone Number is not a valid phone number".
Rename your "phoneButton" field to, for example, "submitButton" and you should be fine.
Replace
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
with
$phone_patt = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/";