Form validating in PHP - error message not displayed - php

I am beginner in PHP and I want to check whether user has filled the input named "jmeno". Name of the corresponding variable is the same. If the input is not entered, then the variable "chybi" should be expanded by text "Zadej jméno!" and that text should appear above the form.
I am getting no errors. If the input is filled, then the form proceeds. If not, then the form doesn't proceed - that works how it's supposed to. But the error message in variable "chybi" doesn't display for some unknown reason in case that the variable "jmeno" is empty (second if).
I have tried many things. It's strange that such a simple script doesn't work. Any ideas? Thank you.
<?php
$chybi = '';
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
echo $zacatek;
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
else {
echo $zacatek;
}
?>

As #jylipaa pointed out you're echoing $chybi before setting it's value. Move your logic above the $zacatek varaible.
<?php
$chybi = '';
if ( isset($_POST['jmeno']) && isset($_POST['pohlavi']) ) {
$jmeno = $_POST['jmeno'];
$pohlavi = $_POST['pohlavi'];
if ( empty($jmeno) ) {
$chybi .= 'Zadej jméno!<br />';
}
else {
echo "Jmenuješ se $jmeno a jsi $pohlavi.";
}
}
$zacatek = '
<p>some long text</p>
<form action="index.php" method="post" class="akce">
<p>' .$chybi.
'<input type="text" name="jmeno" placeholder="Zadej své jméno," /></p>
<p>
vyber pohlaví<br />
<input type="radio" name="pohlavi" value="žena" /> žena<br />
<input type="radio" name="pohlavi" value="muž" /> muž
</p>
<p>a pokud se nebojíš, <input type="submit" value="vstup!" /></p>
</form>
';
echo $zacatek;
?>

you are setting $zacatek in the start of code where $chybi is still empty. It is then handled as a string and setting the value of $chybi later on will not change the content of a string afterwards.

Related

How to create a form that accept number only

How can I create a form that accept number only?
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label>x:</label><br>
<input type="text" name="xx" ><br>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['xx']) || !empty($_POST['xx']) || is_numeric($_POST['xx'])){
$x = $_POST['xx'];
}else{
echo "vous devez taper des chiffres!";
}
echo $x . "<br />";
?>
</body>
</html>
I am new in PHP please an easy answer.
Thank you :-)
If you only want to accept a number, you can also do so using the html element <input>.
Like this:
<input type= "number" name= "xx">
As a precaution, check the server-side $ _POST["xx"] element. Whether the element contains the expected values.
Like this:
check whether the element has been filled in and does not contain only white characters.
And remove any white space before and after the number using trim()
$xx = trim($_POST["xx"]);
if(!empty($xx) && is_numeric($xx)) {
// if "if-condition" true
} else {
// if "if-condition" false
}
I have this message if it is empty
enter image description here
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>">
<label>x:</label><br>
<input type="number" name="xx" ><br>
<input type="submit" value="Submit">
</form>
<?php
$value = trim($_POST["xx"]);
if(!empty($value) && is_numeric($value)) {
$xxx = $_POST['xx'];
} else {
echo "vous devez taper des chiffres!";
}
echo $xxx . "<br />";
?>
</body>
</html>
It is not an answer this, I don't know how to add code in the comment.

Trying to pass variable values from PHP to a new HTML file

using PHP 5.6.27 I'm trying to generate a HTML file by combining
(1) Input from form fields
(2) HTML code (template)
Issue: The file gets created but only has the $template value but not the form field input.
Code is below. Also Live link is at http://fastlaw.in/formv2.html
Sure I'm missing something simple, but would appreciate it if anyone can help out.
formv2.html
<form action="formscriptv2.php" method="POST">
<input id="field1" type="text"/> <br />
<input id="field2" type="text" /> <br />
<input type="submit" name="submit" value="Save Data">
</form>
formscriptv2.php
<?php
$Field1 = $_POST['field1'];
$Field2 = $_POST['field2'];
$onepart = "
<div class='table table-left'>
<section>
<h2 class='table-heading'>";
$twopart = "</h2>
<table class='data'>
<caption>
<p>";
$threepart = "</p>
</caption>
";
$template = $onepart . $Field1 . $twopart . $Field2 . $threepart;
$ret = file_put_contents('tmp/mydata.txt', $template, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
?>
PHP $_POST array are populated via the name HTML attribute:
<input id="field1" name="field1" type="text"/> <br />
<input id="field2" name="field2" type="text" /> <br />

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

Make errors show on top of a form

How do I make error show on top of form so that if $user->success == true, it wont show my form then. Removing that last else would help, but then form shows after success. One way is to redirect that. Maybe tehre
if (isset($_POST["submit"]))
{
if ($_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
$User->signin($_POST['username'], $_POST['password']);
}
else
$User->CheckUser();
if ($User->success == true) {
include ('in.php');
}
if ($User->error)
echo "<p>" . $User->error . "</p>";
else
echo 'Don\'t process form';
$_SESSION["formid"] = md5(rand(0,10000000));
} else {
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input id="username" name="username" type="text" /><br />
Password:
<input id="password" name="password" type="password" /><br />
<input type="hidden" name="formid" value="<?php echo $_SESSION["formid"]; ?>" />
<input type="submit" name="submit" />
<br />
Register
</form>
<?php }?>
Perhaps the simplest approach is to just create a variable $show_form to use to determine whether form is to be shown,
$show_form = true;
if(isset($_POST['submit'])) {
// do your form processing here.
// If you decide everything is good and you don't want to show the form,
// just add this line:
$show_form = false;
} // don't use else here
if (true === $show_form) {
?>
<form>...</form>
<?
}
?>
add this code before your form tag
<?php if (isset($User->error) AND $User->error)?>
<p><?php echo $User->error?></p>
<?php?>

Using strip_tags function

I want to preface this question with the fact that I am a student and this is my first PHP class. So, the following question might be a bit novice...
Okay so the point of this program was for me to filter results from a form through regular expressions along with clean up the text area content...
Well as of right now, all works fine except for the strip_tags bit. I have it set to allow the tags <b> and <p>, and when I enter regular text into the text area, it returns perfectly. If I enter something such as <b>lucky</b> you, all that is returned is 'b'.
I'll post my code. If anyone can give me a hand, I'd love it. At this point I'm overly frustrated. I've studied the examples my instructor supplied (mine is almost identical) and I've looked throught the PHP.net manual and from what I read it should work...
The working code is at http://www.lampbusters.com/~beckalyce/prog3b.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'GET' )
{
echo <<<STARTHTML
<div class="content"><h1>Site Sign Up</h1>
<h3>Enter Information</h3>
<hr />
<form method="post" action="$_SERVER[PHP_SELF]">
<p>Full Name: <input type="text" name="fullName" size="30" /></p>
<p>Password: <input type="password" name="password" size="30" maxlength="12" /></p>
<p>Email: <input type="text" name="email" size="30"/></p>
<p>Tell us about yourself:<br />
<textarea name="aboutYou" rows="5" cols="40"></textarea><br />
<input type="submit" name="submitted" value="submit" /> <input type="reset" /></p>
</form></div>
STARTHTML;
}
elseif ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
$errors = array();
$dirtyName = $_POST['fullName'];
$filterName = '/(\w+ ?){1,4}/';
if (preg_match($filterName, $dirtyName, $matchName))
{
$cleanedName = ucwords(strtolower(trim(strip_tags(stripslashes($matchName[0])))));
}
else
{
$errors[] = "Enter a valid name. <br />";
}
$dirtyPass = $_POST['password'];
$filterPass = '/[a-zA-Z0-91##$%^&*]{8,12}/';
if (preg_match($filterPass, $dirtyPass, $matchPass))
{
$cleanedPass = $matchPass[0];
}
else
{
$errors[] = "Enter a valid password. <br />";
}
$dirtyEmail = $_POST['email'];
$filterEmail = '/^(?:\w+[.+-_]?){1,4}(?:\w+)#(?:\w+\.){1,3}\w{2,4}/';
if (preg_match($filterEmail, $dirtyEmail, $matchEmail))
{
$cleanedEmail = $matchEmail[0];
}
else
{
$errors[] = "Enter a valid email address. <br />";
}
$dirtyText = $_POST['aboutYou'];
$filterText = '/((\w+)[ ."\'?!,-]{0,3})+/';
if (preg_match($filterText, $dirtyText, $matchText))
{
$validText = $matchText[0];
$ignore = '<b><p>';
$notags = strip_tags($validText,$ignore);
$cleanedText = preg_replace('/fuck|shit|ass|bitch|android/i',"*****",$notags);
}
else
{
$errors[] = "Enter information about yourself. <br />";
}
if (count($errors) == 0)
{
echo <<<STARTHTML2
<div class="content"><h1>Site Sign Up</h1>
<h3>Verify your information</h3>
<hr />
Name: <span class="choices"> $cleanedName <br /></span>
Password: <span class="choices">$cleanedPass <br /></span>
Email: <span class="choices">$cleanedEmail <br /></span>
About you: <span class="choices">$cleanedText <br /></span>
STARTHTML2;
}
else
{
echo "<div class=\"content\">Please correct the following errors:<br />\n";
$errnum = 1;
foreach ($errors as $inderr)
{
echo "$errnum. $inderr";
$errnum++;
}
}
echo '<br />Back to Form';
echo '</div>';
echo '<p style="text-align: center">' . date('l, F d, Y') . '</p>';
}
?>
It doesn't look like your regular expression allows for the < and > characters, also, if it was meant to match the entire text, it should start with ^ and end with $, otherwise it will just match on a small section of the input as best it can according to the pattern which is likely what happened to simply return 'b' in $match[0] when supplying <b>TextHere

Categories