How do you validate a html unicode in php - php

I am passing values from HTML form to a php file for processing
$to_do = $_POST['action'];
Then i can say
<?php
if( $to_do == "delete") {
echo "i will delete for you";
}
?>
Difficulty i am having is when the HTML value is unicode &#10008 for a delete symbol.
instead of the value "delete".
In php i cannot tell how to test it.
<?php
if( $to_do == "&#10008") {
echo "i will delete for you";
}
?>
is not working.
Any one to help me out?

How are you sending this value to begin with - via something like <input type="submit" value="✘">?
In that case, I would recommend you switch to a button element - that can have a separate submission value and display text. So you can keep sending delete, and show ✘ to the user at the same time.
<button type="submit" value="delete">✘</button>
More details on the button element can be found in the MDN, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

Related

Php if Else in form action

Im trying to make an online concert ticket system and this is my problem..
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php $action; ?>" method="post">
And it doesn't work. Thank you in advance!
heres the full codes for the particular file that has a problem.
<html>
<head>
<title>Ariana Grande Concert</title>
</head>
<body>
<br>
<table>
<tr>
<td><img src="ariana2.jpg" height="300" width="260"></td>
<td></td><td></td><td></td>
<td>
<h2>ARIANA GRANDE THE HONEYMOON TOUR</h2><br>
<font face="Lucida Sans Unicode"> March 11, 2017<br>
Grand Ballroom, Solaire Resort & Casino<br>
Due to peoples demand, Ariana Grande is back in the Philippines<br>
Ariana Grande Live in the Philippines on <b> March 11, 2017!</b></font>
<br><br><br><br><br><br><br><br>
</td>
</tr>
</table>
<br><br>
<hr>
<br>
<center>
<table cellspacing="10" cellpadding="10" bgcolor="gray">
<tr>
<td><font face=""><b>TICKET PRICES:</b></font></td>
<td><b>VVIP:</b> <u>Php 25,000.00</u></td>
<td><b>VIP:</b> <u>Php 20,000.00</u></td>
<td><b>Upper Box A:</b> <u>Php 15,000.00</u></td>
<td><b>Upper Box B:</b> <u>Php 15,000.00</u></td>
<td><b>Lower Box A:</b> <u>Php 10,000.00</u></td>
<td><b>Lower Box B:</b> <u>Php 10,000.00</u></td>
<td><b>General Ad:</b> <u>Php 5,000.00</u></td>
</tr>
</table>
</center>
<br><br>
<font face="Lucida Sans Unicode" size="2"><b>Ticket Type: </b></font>
<?php
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
echo '<font face="Lucida Sans Unicode" size="2"><b> Quantity: </b></font>';
$Quantity = range (1, 30);
echo '<select name="Quantity">';
foreach ($Quantity as $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
?>
<form action="<?php echo $action; ?>" method="post">
<br><br><br>
<button class="btnExample" type="submit" value="Submit"/>Next</button>
<style>
.btnExample {
color: #0000;
background: white;
font-weight: bold;
border: 1px solid #0000;
border-radius: 10px 10px 10px;
}
</style>
</form>
</body>
</html>
Heres the full codes of the webpage that has a problem.
You did not echo the variable to show the output:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= "<?php echo $action; ?>" method="post">
Notice the <?php echo $action; ?>
Note: This is not the answer, and you should not accept this as answer, I am posting it here instead of posting in the comment section, because it's to long.
Note - You can solve your problem by your self, but for other it is impossible, as your code is just not making any sense at the moment, but I am pretty sure it will if you are able to read and understood what I am trying to say here in the solution.
First thing first,
Access Denied problem –
Note - you don’t have to fix this problem it will get fix by it self, but you should know why you have this problem, so in the future if you get the problem, you will know what to correct.
The reason it denying the access is this, that you are not allow to give special character for form action so after adding the echo in the form you are going to have this problem, because as soon as you add the echo in our form action you unknowingly giving special character to the action, because you never set the value for your variable $action so value for variable $action is equal to error message. So after adding the echo you are displaying that error message.
before doing any thing run your file in the browser and check the source code,
and see the value in the form action, it will be some thing like this
<br /><b>Notice</b>: Undefined variable: action in <b>C:\in here you are going to have file path\form.php</b> on line <b>1</b><br />
notice how many angle brackets colon you got in the here, you are not even allowed one angle brackets, so browser is thinking you are trying to do some thing malicious and that's why its blocking your access.
If you don’t know how to check source code, just type how to see source code and give your browser name (don’t ask me it just one click away)
so your code is basically generating error message and displaying it for the action after adding the echo and that's why browser is blocking the access
so why it was not doing the same thing before adding the echo, because in php, if you don’t use echo you are not displaying any thing, so before adding the echo, your action was empty, just remove the echo from the form action and check the source code again, you will understand what I am trying to say.
Again you don’t have to fix it, it will get fix by it self, remember this.
Now the solution start from here
First I have to be right about my assumption, that what you are trying to do,
So these are my assumption, what you want to do,
People should be able to buy different different types of ticket, and they can choose the number of ticket from 1 to 30,
Than you want to run different file according to the TicketType, in one case you want to run seat.php and in one case you want to run index.php,
And to achieve your goal, you created a form, use the if statement to set your action value in the form, as I can see you are using variable $action in the form for action, and you set this value through your if statement.
If I am wrong about any thing up until now, don’t read further it will be waste of time.
basically to achieve your goal, you are using form, array and some logic,
in your case you seems to know array and logic, but you lack pre basic knowledge about the form, and that's why your code is not working.
To be honest. In my opinion you know nothing about the form. That's why it is impossible to give you solution(at least for me). But I am quite sure, if you read this fully you will be able to solve your problem by your self,
so give a quick read to the points, and you will be surprised how easy it is to solve your problem for you, and you will also realized why it is impossible for other to solve it for you, at the moment.
Now Start from here
I am dividing the problem in Four part
Some important Notes about the form.
$Ticket_Type is not equal $TicketType - an you can not even use $TiccketType here
Select option only passes the value from the value tag-- Two part solution
Your logic is at the wrong place,
1. Some important point about the form.
When you use form, you have to tell php, that you are submitting the form, and if you want to do it only with php, you have to use submit button for it(I already mention this in my comment other day),
second you need to know, what happened when you click on the submit button in the form, form will run the action file and also will pass the data from. opening form tag <form> to closing form tag </form> to that file
but any data which is out of these opening and closing form tag, form will not pass that data, so point is it only passes the data which is inside the opening form and closing form tag.
Look at the code below to understand it better, and please also run this code, so you can understand it better,
Few points about the code
in the below code, we have two input field location and name, location input field is out of the form tag and name input field is inside the form tag.
and our form action is seat.php, and name for form file is form.php for this example.
as our action is seat.php, so if you click on the submit button, it will pass the data to seat.php, and will run that file.
in seat php, we are just using echo to display both value,
see the code below for form.php and for seat.php,
form.php
Location<input type="text" name="location"/><br><br>//out side of the form tag
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$name = $_POST['name'];
echo $name.'<br>';
$location = $_POST['location'];
echo $location;
Now go and run form.php and type some thing in the location and name box, and click on the submit button, and if you do that, it will only display you the value for name but for location value it will display you the undefined index location error.
And the reason is, because your form never passed that value for location to seat.php1, becauselocationis out ofform` opening and closing tag,
Now put this Location field inside the form tag
now put that location inside the opening and closing form tag,
after doing that our code should look like this
<form action="seat.php" method="post">
Name <input type="text" name="name"/><br><br>
Location <input type="text" name="location"/><br><br>//Now location is inside of the form
<input type="submit" value="Hot Air">
</form>
Now again run your form.php type some thing for name and for location and click on submit button, this time it will display you both the value, as this time both values are inside the form tag so both value get passed.
Note – If you can understand the difference between the first result and second result, you will be able to understand, why you need to have your select tag inside the opening and closing form tag, you can not have them out side of,
$Ticket_Type is not equal to $TicketType – and you can not even use $TicketType in here as it is equal to array you want value from the select option
For Second mistake, pay attention to this portion of your code
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
in here if you read this line echo ' <select name="Ticket_Type">' you give name for select Ticket_Type and than in the if statement You use the variable $TicketType, I am assuming you are checking the value for $TicketType, This problem you can solve it by changing the variable name $TicketType to $Ticket_Type In the if statement.
you have to correct this as well at the same place
So even after apply the above fix, your code wont work, cause you have second problem in this code
Now comes to the second problem, which you made in your if statement , in your if statement in here you checking $TicketType value, but you don’t have value for variable $TicketType because when you use the form php don’t set the variable it set the index so first you have to set the value for $TicketType than only you can use the if statement,
After applying both fixes your code should look like this
Note – (I am changing the name for select to TicketType )
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
$Ticket_Type = $_POST['Ticket_Type']; // Now you set the value for variable
// as your value is set, now you can type your if statement below.
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
3. Select option, pass value only from the value tag
Third mistake you make and this one you will not notice with this code, but if you don’t learn, you will likely to make that mistake in the future, so correct this mistake as well,
Just pay attention to this code
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
echo ' <select name="Ticket_Type">';
foreach ($TicketType as $key => $value) {
echo "<option value=\"$key\">$value</option>";
}
echo '</select>';
In here you have array, and than you are creating select option from your array which is fine, but you are making one fundamental mistakes in here, form will only passes the value form the value tag
so come to this line in your code
echo "<option value=\"$key\">$value</option>";
now change variable to $key to variable $value as well, because when you click on the submit button, again form only passes the value from value.
echo "<option value=\"$key\">$value</option>"; to echo "<option value=\"$value\">$value</option>";
it wont change the out come, for this code, as in your array key and values are same, but you should know what value you are passing for the future.
To Understand what I am trying to say here, run these two code from below, you will understand what I am trying to say.
form.php
<form action="seat.php" method="post">
<select name="Ticket_Type">
<option value="key1">First</option>
<option value="key2">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
seat.php
<?php
$value = $_POST['Ticket_Type'];
echo $value;
run this file in the browser and than select the option, and click on the submit button, it will display you key1 or key2 depending on the option you choose, not the first or second, as form only submit the value from value tag
now change value tag value to One and two, and run your code again,
<form action="seat.php" method="post">
<select name="Ticket_Type">;
<option value="One">First</option>
<option value="Two">Second</option>
</select>
<input type="submit" value="Hot Air">
</form>
Now again run the file in the browser, and chose the option and click on the submit, and see the outcome, and try to understand what is happening.
4 Your logic is at the wrong place
see this code
if($Ticket_Type == 'VIP'){
$action = "index.php";
}else if ($Ticket_Type == 'VVIP') {
$action = "seats.php";
}
What your are trying to do here, in your head it make sense, that you will run the different different file,
according the ticket type, but in reality it does not make any sense, because when you click on the submit button, than only form will pass the value, to the action file,
this one is hard to explain
ok listen you have this variable $TicketType in this code, it only get set after you click on the submit button, and the action file it never going get set in this files, so you can not have these lines in this file. (and that's why it was showing to access forbidden after adding the echo)
Ok let's say you move this line to the different file, but still what you are trying to do with these lines is still silly, just don’t use these silly lines, and don’t try to run different different file, run single file, means give single action, and lets say action in the form is book.php
so our file name is book.php,
so starting shell for your book.php should look like this
if(!empty($_POST['Ticket_Type'])){
// what you are basically saying that if TicketType is not empty run this code,
// if it is empty run the else statement so the user will know that he did not select any ticket,
//now we are going to add some more code In here
}else 'Hey you did not select any ticket';
After adding the code in the middle our code will look like this
if(!empty($_POST['Ticket_Type'])){
$Ticket_Type = $_POST['Ticket_Type']; // set the value
if($Ticket_Type == 'VIP'){ //
// Copy and paste the index.php file code here
}else if ($Ticket_Type == 'VVIP') {
//copy and paste the seat.php file code here
echo $action;
}// if you have another Ticket_Type just add another else if here,
//Note: you can add as many else if you like,
}else 'Hey you did not select any ticket';
so just run single file action
i am still alive, after typing all this, if you have any confusion let me know.
Your Proble is here:
$TicketType = array('VIP' =>'VIP', 'VVIP' =>'VVIP', 'Upper Box A'=>'Upper Box A', 'Upper Box B'=>'Upper Box B', 'Lower Box A'=>'Lower Box A', 'Lower Box B'=>'Lower Box B', 'General Admission'=>'General Admission') ;
And your condition for if statment is
if($TicketType == 'VIP'){
$action = "index.php";
}else if ($TicketType == 'VVIP') {
$action = "seats.php";
}
$TicketType is an array and you can't check it with a string, so your $action variable is not setting. and you have to provide index to check.
I had a similar problem where my error read "Object not found!
The requested URL was not found on this server. The link on the referr..."
Going off of aria_suhail_123's answer, you simply need to remove any php code surrounding your $action variable in your html like so:
<?php
if($tickettype == 'VIP'){
$action = "seats.php";
}else if($tickettype == 'VVIP'){
$action ="seats1.php";
}
?>
<form action= $action method="post">
The reason why is explained by aria_suhail_123, but since his/her response is very long... maybe this will help someone else!
Consider this :
<?php
if(!empty($_POST['tickettype'])){
if($tickettype == "VIP"){
?>
<script type="text/javascript">
window.location = "./seats.php";
</script>
<?php
}else if ($tickettype == "VVIP") {
?>
<script type="text/javascript">
window.location = "./seats1.php";
</script>
<?php
}
}else 'Hey you did not select any ticket';
?>

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

use php to change a html elements inner text

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.

How to send variables from a PHP script to another script using POST without forms?

I'm trying to write my first PHP script (hopefully). I want to send user input from a form inside an HTML page to a PHP script and validate them inside script. then, if there is any problem with input data, return to first page and highlight wrong fields. else go to another page (something like successful).
How do i send feedback from second script to first page without using forms?
In short, you'd have something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$name = $_POST['name'];
if ($name !== 'Fred') {
$errors[] = 'Please enter "Fred"';
}
... validate more fields ...
if (count($errors) == 0) {
... form is ok ...
header('Location: everything_is_ok.php');
exit();
}
}
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
Enter 'Fred': <input type="text" name="name" value="<?php echo htmlspecialchars($name) ?>" /><br />
<input type="submit" />
</form>
Basically: Have the form page submit back to itself. If everything's ok, redirect the user to another page. Otherwise redisplay the form.
Just make your Form POST to itself, then in your PHP check the values and if they are valid, don't display your form and do your submit code. If they are invalid, display the form with the values and errors displaying.
Reload the first page and send the feedback in the session, for example. If session['errors'] exist, echo them. Note you'll have to include some php tags in your html page anyway.
Use a session... here's a link to help you get started: http://www.tizag.com/phpT/phpsessions.php

Retaining values in forms fields when validation of data fails

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>

Categories