Displaying error messages based on form data in php - php

I'm trying to create a pretty standard user creation form for a website I'm working on, but my PHP amateur status is preventing me from accomplishing my goal.
Essentially what I want to do is have the user fill out a registration form, and then have a server-side script attempt to register that information. If the registration succeeds, then the user will be redirected to a page telling them to look for a verification email. If that registration fails (the email address is already in the system, not matching passwords, whatever), I would like to reload the page, but display the error message to the user above the form. Currently the form I have is being echoed out of a php file which is separate from the HTML from where the page is stored. My three questions are this.
From what I've read, the way to redirect users on success is to use header("Location: http://foo.com"). Is that correct, or is there a more proper way to do it?
How can I get access to the error(s) that caused the first user to fail? I've read that setting a session variable is a poor idea for a number of different reasons, but without that how can I keep track of the errors thrown by the form validation? Should I just create a global $errors variable that I clear every time I echo the registration form?
For this case, should the page that the registration form is on have a .html extension or a .php extension, or does it not matter? More generally, is there any rule for when a page is .html vs .php/.asp/something else?
Edit: added code below. Note, the form is rendered from a file called in ../views/register_form.php (I assume this is how I'd work on getting something MVC-like in PHP)
The page that the form is rendered on (called index.html)
<body>
<script type="text/javascript"> <!-- put the jquery load stuff into here -->
$(function(){
$("#registration_form").load("views/register_form.php");});
</script>
<div class="topbar"><!-- Create the top bar layout-->
<div class="fill">
<div class="container">
<a class="brand" href="#">Website!</a>
<ul class="nav">
<li class="active">Home</li>
<li> About</li>
</ul>
<form action="scripts/login_user.php" method="post" class="pull-right">
<input class="input-medium" id="login-email" type="text" name="email_addr" placeholder="email" />
<input class="input-medium" id="login-password" type="password" name="password" placeholder="password" />
<button class="btn" type="submit">Login now!</button>
</form>
</div>
</div>
</div>
<div class="container">
<div class="content">
<div class="page header">
Page header!
</div>
<div id="registration_form">
</div>
The script
if(//some of the data in the form isn't set)
{
//Set error conditions based on missing data
}
$confirm_password=$_REQUEST['confirm_password'];
$password=$_REQUEST['password'];
if($confirm_password != $password){
//report passwords don't match}
$email_addr=$_REQUEST['email_addr'];
$first_name=$_REQUEST['first_name'];
$last_name=$_REQUEST['last_name'];
try
{
$successful_creation=create_user_and_send_verification_email($email_addr, $password, $first_name, $last_name);
}
catch(Exception $e)
{
/*SQL errors are caught here*/
}
if($successful_creation==FALSE)
{
//If it couldn't be inserted for a non exception generating reason. If I get here, should I echo a page that has those errors printed, but is otherwise identical to the previous one?
}
else
{
//redirect to a "wait for a verification email" page
}

Yes that is the correct way to do it, but all headers must be sent before you try to render anything to the page. Also, you don't necessarily need to redirect, you can generate the correct output with PHP depending on the form data.
The script that receives the submitted form should check the submitted data for errors and can then output those errors to the page that is generated by that script.
If the page has php code in it then usually it needs a php extension unless your server is set up to process html pages as php. Otherwise, .html is fine.
I hope that helps point you in the right direction, although a more focused question with the code you have up to now would generate a better answer.
There are lots of tutorials on this on the web, you should follow one of those and experiment.

why dont you write the server side code on the same page and for every form input use a flag
for eg: if email is not valid $email=1.
den after submission if any flag is initialized,check for the flag and if $email=1 echo error else redirect.

Related

How can i call my user name after loggin on header in all my pages PHP mysql

I got my user.php, header.php and indexph.php. After i log in, i can show my user data but i want to call it in my header, between every page i explore.. my header is another file on my site, i use "require_once('header.php')" to call it on indexph.php or user.php but when i get out of user.php i lost my username data, here is part of my code..
USER.PHP (not all)
<?php include("conexion.php");
require_once("header.php") ?>
<form action="" method="POST" id="loginform">
<input type="text" placeholder="Usuario" name="usuar">
<input type="password" placeholder="Contraseña" name="pw">
<button type="submit" class="btn" name="logi">Login</button>
Olvidaste la contraseña?
</form>
?>
header.php
<?php
include("conexion.php");
if(isset($_POST['logi'])){
$u=$_POST["usuar"];
$c=$_POST["pw"];
$sql="SELECT * FROM usuario
WHERE usuario='".$u."' AND contr='".$c."' ";
$res=mysql_query($sql,$con);
$can=mysql_num_rows($res);
$b=mysql_fetch_array($res);
if($can == 1)
{
echo "Login OK by ".$u;
//echo"".$_SESSION['id_user'];
//header('location:indexph.php');//te envia luego de logear correctamente
echo "<form action='logout.php' method='POST'>";
echo "<button type='submit' name='logo'>Logout</button>";
echo "</form>";
}
else
{
echo "Login Failed";
}
}
?>
<header id="header">
<div class="navbar">
<nav>
<ul id="menuitems">
<li>Home</li>
<li>Productos</li>
<li>Añadir</li>
<li>D.P☠</li>
<li>Cuenta</li>
</ul>
</nav>
<a href="kart.php" class="nav-item nav-link active">
<img src="../img/cart.png" width="50px" height="50px">
</a>
<!---here i would like to call my username so it shows in every page that calls
header.php---->
</div>
</header>
here is my "indexph.php" one of many pages where i want to show my username just calling header.php
<?php
session_start();
require_once('header.php');
if(isset($_SESSION['usuar']))
{
echo"<br>Logged by ".$_SESSION['usuar'];
}
?>
<html> <!--- here it would be all html, images and everything---> </html>
But i can't, that "echo" is not working, the thing is want the username on header, thats all plz help i cant solve this :c
So in your header.php you need to set the session variable after the login to use it later.
if($can == 1) {
$_SESSION['id_user'] = $b['id']; // or however your id column is called in the database
// of course, you can also save the username or whatever value you want in a session variable
}
The thing about sessions and their variables is, that they get saved server-side, so you can use them in concurrent requests and different files until they are destroyed.
But I see several issues with your posted code:
You are using mysql_* functions, which are long deprecated (since PHP 5.5, June 2013). Check, why you shouldn't use them here.
You are wide open to SQL injection attacks. Read up on it here.
You are saving your passwords in clear, human-readable text to your database. If you ever face a database breach, all username / password combinations are open to the world. Maybe some people used these same credentials on other websites. Try to use password_hash and password_verify functions in your code. But first, get comfortable with your current code :)
Not an issue but a (maybe) personal preference. Write your code in English, it will make it easier to get help - like here on SO. People, who don't speak your language will be better able to understand your code. Also, if at some point you decide to hand off the project to a person that is not too keen or even at all able to understand your language, they will struggle for a bit.

How do I get rid of this notification box in PHP?

I have this problem where when I refresh, a notification box will pop up in the browser(Chrome) just like this.
my code for the sign in is here:
<form class="uk-form">
<fieldset data-uk-margin>
<legend>Sign up here:</legend>
<input type="text" placeholder="username" required>
<input type="password" placeholder="password" required>
<a href="" class="uk-form-password-toggle" data-uk-form-password></a>
<select>
<option>PYP</option>
<option>MYP</option>
<option>DP</option>
<option>Adults/Teachers</option>
</select>
<div><input type="checkbox" name="remember" id="remember" <?php if(isset($_COOKIE["member_login"])) { ?> checked <?php } ?> />
<label for="remember-me">Remember me</label>
</div>
<button type="confirm" class="uk-button uk-button-primary">Sign Up</button>
</fieldset>
</form>
and the result is this:
This is occurring because you previously POSTed to that page, meaning that you've most likely come from a form. If you refresh the page it means the POST data will be posted again to that page which is probably not what you want to do.
My advice would be once you've done what you need to do with the form, is to redirect it to another page (could in theory be back to the form page) and repopulate the data if you need to keep it.
After processing the $_POST data on the previous request you can redirect the user, and clear the Post data by doing this:
header('Location: '.$url);
exit;
Where $url is set to the URL you want to send them to. There are 2 very important things if you do this.
You cannot output anything before calling header, not even 1 single space.
Coincidentally this is why you will see some PHP files that do not include a ?> closing tag. The closing tag is optional if the file only contains PHP, and even a space after the end tag can mess up redirect if it was included before calling them. So by omitting the end tags, there can be no output.
Conciser this:
<?php
...code..
?>
\n
Where \n is a new line. If this is included before doing a header or even a download it can have undesirable effects. Personally I never mix PHP and HTML and so I never use the end tags.
Likewise this can prevent the redirect from working
\n
<?php
... code ...
You call exit immediately following the redirect. After doing the redirect PHP will continue to execute the current script, which is probably not what you want and can have unpredictable results.
It's happend because you come from another form that send POST. When you refresh, it will confirm you that data have been posted before will posted again.
I advice you redirect to another page or same page. Read header in php to redirect

Inconsistent results when using an iPad to access and send HTML/PHP forms

I have built a website that uses HTML, CSS, PHP and MySQL. The purpose of the website is to allow students to build a word bank. The data is sent and stored in a MySQL database via PHP/HTML forms. The information is displayed using HTML/CSS/PHP.
I haven't experienced any problems with the system UNTIL the children have been accessing it in school, using iPads to access/explore the website.
The problem I'm having is simple (and also infuriating!): sometimes the children can't login to the website - every time they press the 'login' form submit button, the form 'refuses' to be submitted (returning them to the same login page, as if it had just been refreshed). The same problem also occurs when they're trying to upload a word to the database - the form submit button 'refuses' to submit the data.
Basically: the submit buttons can be 'clicked', but they don't do what they're supposed to do.
Here's the code that I've written for the login system:
<?php
if($_POST){
if(login( $_POST['user'],$_POST['pass']) ){
echo "<a href=index.php>Continue.</a>";
$_SESSION['user'] = strtolower($_POST['user']);
} else { }
} else {
?>
Please login
<form method="POST">
<input type="text" name="user" value="Username">
<br />
<input type="password" name="pass" value="Password">
<br />
<input type="submit" name="login" value="Login">
</form>
<?php
}
?>
I'm not really sure what the problem could be - I'd guess (and almost hope) that it's a problem with my code (my use of sessions, maybe?) - but if it was, then why does the system work fine sometimes, and then at other times so inconsistently? Is it a problem related to iPads?
I hope I've made myself clear enough for any helpful suggestions.
You should use session_start function to start or resume exist session.
Just append a session_start function at the begin of your code.
<?php
session_start();
if($_POST){

Accessing database for mobile web applications

I have a question about login and accessing database for mobile web applications.
Namely, the fact that all the pages are usually in one page separated by ids, how do you send form data using PHP? There are no separate files to send data to.
Doesn't opening a connection at the top of the HTML file without logging in cause a security problem? If they do not login successfully, you are essentially redirecting to the same HTML file.
If someone could redirect to a tutorial (which I can't seem to find online) or give an overview, that would be awesome.
<?php
//1. Open connection
//2. Select database
?>
<html>
<body>
<section id="page1">
<form action="page2" method="POST"><!-- since the data needs to be send to #page2, do I just POST to the same html file? -->
</form>
</section>
<section id="page2">
<?php
//3.query database
//4. display results
?>
</section>
<section id="page3">
</section>
</body>
</html>
<?php //5. close connection?>
1) You can keep separate files in PHP, they don't have to be in the same page. For example, you have a file named login.php.
<?php ?>
<html>
<form action="index.php" method="post>
<input type="text" name="username"/>
<input type="password" name="pasword"/>
</form>
</html>
Then in your index.php file you would have something like this.
<?php
if($_POST['username']=="admin" && $_POST['password']=="admin")
//query database
//display results
?>
So you don't have just one file containing different pages.
2) You can include a main.php file in all your pages and check if user is logged in, if not, redirect him to some other page. In adition you could learn a little bit about session variables.
<?php
include("main.php");
?>
In your main.php
<?php
session_start();
if(!$_SESSION['islogged'])
header("location: otherpage.php";)
?>
So if the user is logged in there will be no redirection but other way it will.
Hope this helps you.
1)
Check out the following link. http://www.w3schools.com/php/php_post.asp
It explains how to access form data that has been sent to your php page. You need a decent understanding of HTML before you ever start working with PHP.
2)
The user isn't the one logging in. They never see the php code. It stays on the server. What they see is HTML. The connection is so the php page can connect to the database and retrieve information.

PHP form validation error messages placement

Is it possible to place error messages resulted from form validation inside the form, using PHP/XHTML/CSS only?
You can put error messages anywhere on the site you wanted. It all depends on where in your scripts you place your code to emit it.
One strategy I've seen used a lot in PHP Frameworks when AJAXy submissions are disabled is to have a field to display the error on the page, and then actually populate that field with the data if the page comes back with an error.
Such as:
<label for="field">Label"><input name="field" type="text" />
<?php if($_POST['errors_field']) echo '<p class="error">'.$errors['field'].'</p>'; ?>
This strategy would only show the <p> tag when the page input box has an error. This method of course involves returning a populated array of all errors to the page when it fails validation.
I would make 2 pages one with the form like this. We will call it form.php. Make sure your form method is "post", and you have named your inputs. create a div that will be used for error callback($error). You can place the Error var anywhere you want not just in the form.
<form method="post">
<input type="text" name="text">
<div><?php echo $error ?></div>
<input type="submit" name="submit">
</form>
Next Make another php page like this and include the form.php page at the bottom. set error as empty string first. See if the button is clicked(isset). If the field is equal to a empty string set the error($error). if no error Process the form. Hope this helps.
<?php
$error = '';
if(isset($_POST['submit'])){
if($_POST['text'] == ''){
$error = "Here is your Error inside the form.";
} else {//"Sanitize and Process the Form";
}}
include 'form.php';
?>

Categories