This is how I've been checking to see if variables are set when returned to my view.
<div>
<label for="username">Username</label>
<input type="text" name="username" id="username" <?php if(isset($_POST['username'])) { echo "value=\"". $_POST['username'] . "\""; } ?> />
<?php if(isset($username_error)) { echo "<label>" . $username_error . "</label>"; } ?>
</div>
I feel like there could be a better approach, or even a shorter way to check and echo out these values?
When I deal with form submissions or possibly not initialized variables in PHP I do this:
$username = isset($_POST['username']) ? $_POST['username'] : '';
$username_error = usernameValid($username) ? true : false;
Then just echo out the username and do a quick if($username_error) to determine if you need to display the error. It's probably best to store if a submitted form field is valid or not and the error message separately.
You could build the HTML independently, loading your template with DOMDocument.loadHTML and adding the attributes conditionally (JavaScript-like) via the DOM. That has the advantage of highlighting your HTML structure without as many inline checks.
I'd suggest using a library or framework that does the hard work for you.
See:
A PHP and jQuery form creation and validation library available?
HTML Form Library for PHP 5
Related
I have a piece of php code inside html tag which is supposed to change the tag's style in accordance with the contents of the URL.
There is an html login form which looks like this:
<form class="userdata" action="login.php" method="post">
<input type="text" name="email" placeholder="E-mail" <?php fillin('email'); enlight_unfilled('email');?>><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit" name="login-submit">Login</button>
</form>
Here are the functions fillin and enlight_unfilled:
<?php
function fillin($key) {
if (isset($_GET[$key])) echo "value=".$_GET[$key];
else echo NULL;
}
function enlight_unfilled($key) {
if (isset($_GET['error']))
if (isset($_GET[$key]) and $_GET[$key] !== "") echo NULL;
else echo "style='border-color: red'";
else echo NULL;
}
?>
If I only apply one of the functions within the tag, they both do what they are expected to – either save the email in the field if it has been already typed in or enlighten the email field if it has been left empty. But if I apply them together, when the field is empty, php assigns the field value 'style='border-color:. I also tried to use functions like print and printf, but the result is the same:
I am a beginner at php coding and mixing it with html, so the question may appear to be dumb, but I did not manage to find any sort of a solution to this issue, so thanks for help and patience in advance!
It looks like you don't properly encase value in quotes, so it just renders the 'style='border-color:.
Let's assume that $_GET[$key] has a value of hello#hello.com. What your PHP & HTML renders is the following:
value=hello#hello.com
See the problem? There are no quotes. That's why the renderer goes forward searching for a valid value. To fix the issue you must add quotes around your $_GET[$key] in the fillin function. Something like this should do the job:
if (isset($_GET[$key])) echo "value='".$_GET[$key] . "'";
It works when ran alone because it reaches the end > and just assumes the value to be hello#hello.com
I have a basic form, which i need to put some validation into, I have a span area and I want on pressing of the submit button, for a predefined message to show in that box if a field is empty.
Something like
if ($mytextfield = null) {
//My custom error text to appear in the spcificed #logggingerror field
}
I know i can do this with jquery (document.getElementbyId('#errorlogging').innerHTML = "Text Here"), but how can I do this with PHP?
Bit of a new thing for me with php, any help greatly appreciated :)
Thanks
You could do it it a couple of ways. You can create a $error variable. Make it so that the $error is always created (even if everything checks out OK) but it needs to be empty if there is no error, or else the value must be the error.
Do it like this:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['somevar'])){
$error = "Somevar was empty!";
}
}
?>
<h2>FORM</h2>
<form method="post">
<input type="text" name="somevar" />
<?php
if(isset($error) && !empty($error)){
?>
<span class="error"><?= $error; ?></span>
<?php
}
?>
</form>
If you want change it dynamically in client-side, there is no way but ajax. PHP works at server-side and you have to use post/get requests.
Form fields sent to php in a $_REQUEST, $_GET or $_POST variables...
For validate the field param you may write like this:
if(strlen($_REQUEST['username']) < 6){
echo 'false';
}
else{
echo 'true';
}
You can't do anything client-side with PHP. You need Javascript for that. If you really need PHP (for instance to do a check to the database or something), you can use Javascript to do an Ajax call, and put the return value inside a div on the page.
I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>
How do I pass information between PHP pages?
For example, I have a PHP script to process login input from a form, and then a separate PHP script to process further input for the user. However, I want the second PHP file to receive the input from the login form. In essence, I do not want the same script being run twice for the login.
You are looking for POST and GET variables, it's done in the method parameter of your HTML form:
login.php
<form name="myform" action="secondpage.php" method="post">
<div>Username: <input type="text" name="username" value="" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
Then in this other page:
secondpage.php
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if ($username != '') {
// do your validations here
}
Explanation
When you use the GET method, the parameters are visible in the URL, so let's say we change the method="GET" in login.php, you'll end up with something like secondpage.php?username=jsmith&password=1234. And then you could get the values using $_GET['username'].
Using POST makes it possible to send larger quantity of data (there is a vague limit to the size of a URL) and it's not visible in the URL. You should note though that it's still sent in clear text, so it does not means it's secure.
POST and GET were made for different purposes. GET should be use to extract information that you could want to extract again in the future, information that is not special to this very instant. It's useful to have mypage.php?product=123 because you'll potentially want to send this URL to a friend. A POST should be used when you'll modify the state of data: updating a product, creating a new user, deleting an article and so on. It's something you want to happen once.
Structure
In conclusion, I just want to add that normally you wouldn't necessarily want to use another PHP script just to avoid some code to run or not. So without knowing the specifics of your project, I can nevertheless say that you would probably want to do something like that to benefit from the same code (such as the form's HTML).
Please note it's simplified code.
login.php
<?php
$error = false;
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
// if, and only if something was posted... so not on first display
if ($username != '') {
// do your validations here
if ($properlyLogged) {
session_start();
$_SESSION['loggedAt'] = time();
header('Location: http://localhost/secondpage.php');
exit();
} else {
$error = true;
}
}
?>
<?php if($error): ?>Login failed. Please try again.<?php endif; ?>
<form name="myform" action="login.php" method="post">
<div>Username: <input type="text" name="username" value="<?php echo($username) ?>" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
secondpage.php
<?php
session_start();
if (!isset($_SESSION['loggedAt'])) {
// if not properly logged in, return user to login
header('Location: http://localhost/login.php');
exit();
}
?>
You are now logged in!
Hope that's what you were looking for!
You can pass information between pages using GET or POST methods. GET would append the information you wish to pass as a querystring on the url such as:
loginprocess.php?id=JSmith&pword=HelloThere (this isn't exactly recommended for private information)
The other method is to send the information via POST so that it is hidden from the querystring.
More examples can be seen here: http://www.tizag.com/phpT/postget.php
If the data isn't that large you could redirect the user to the 2nd page with the data passed via the URL (GET variables). Otherwise, just run the seconds method in the same page, and use a function to do the final parsing of the data which can be included as the above user suggests.
Just a small extra to what was written before: the limit on the GET (parametrize URL) is a full URL, which means 1024 characters. If you need more than that, you have to use post.
You can take advantage of PHP sessions to share data amongst your PHP scripts. Basic example below, read more here.
login.php:
<?php
// initializes the session //
session_start();
// save user name and password to session //
$_SESSION["username"] = 'someuser';
$_SESSION["password"] = 'somepassword';
$_sESSION["valid"] = true;
?>
secondpage.php:
<?php
// start session handler //
session_start();
// check for a valid session //
if (!isset($_SESSION["valid"])) header("Location: login.php\n\n");
// continue page code here //
?>
how can I post back the data that are already in the text field?
example:
if I miss one of the required field an error will prompt when i click the submit button.
How can I make an post back data in that form using php or javascript and make the cursor of the mouse directly located to the field that caused an error?
There is no automated ways in PHP to write back the informations of the fields so you just have to echo it back.
Let's say you've got a "username" field ( <input type="text" name="username" /> ) you just need to add this:
value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"
or if you like more:
value="<?php if(isset($_POST['username'])) echo $_POST['username']; ?>"
changed "" to ''
This sounds like basic form validation. I would recommend reading some of these tutorials or looking for some pre-built PHP form validation mechanisms.
Form validation using PHP
PHP/CSS Form validation
PHP Form Validation
Some frameworks such as CodeIgniter will do this for you if you use their own libraries. It's worth checking out such a framework as they provide a lot of other benefits. Of course it's not always possible to transfer an existing application but it's still useful to bear in mind for the future.
If I understand this correctly you want to keep whatever data the user has already entered, tell him what he did wrong and preferably focus on the bad field.
If so then here's a very basic example using a form with two fields where both need to be filled in to proceed.
<?php
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$badField="";
if($_POST['form_action']=="submitted") {
//Check incoming data
if(empty($field1)) {
$badField="field1";
echo 'field1 is empty<br>';
}
elseif(empty($field2)) {
$badField="field2";
echo 'field2 is empty<br>';
}
else { //Everything ok - move to next page
header('Location: <next page>');
}
}
echo '<form name="mybo" action="' . $_SERVER['PHP_SELF'] . '" method="POST">
<input type="text" name="field1" value="' . $field1 . '"><br>
<input type="text" name="field2" value="' . $field2 . '"><br>
<input type="submit" name="Submit" value=" Enter ">
<input type="hidden" name="form_action" value="submitted">
</form>';
//Focus on empty field
if(!empty($badField)) {
echo '<SCRIPT language="JavaScript">
document.mybo.' . $badField . '.focus(); </SCRIPT>';
}
?>
I think the Moav's answer is "philosophically" correct however if you want do that you can:
1) pass via GET or POST the text control id;
2) on the server check that error condition;
3) fill an hidden input field with that value on the page returns
4) if error that with JS you can do:
window.onload = init; // init stuff here
function init()
{
checkForError();
}
function checkForError()
{
var h = document.getElementById("error_field");
var v = h.value;
if(v)
document.getElementById(v).focus();
}
However, if you will do that for every error field there will be a post and this is
by a user perspective very boring...so it is better to adopt other approaches...
I would take a different approach:
Validation should be in JS, and as such you never loose data, as you don't submit.
Any wrong data that was submitted and caught on the server is due to someone trying to pass over your JS validation, which means he has criminal thoughts, usually.