Validating information in HTML - Code Positioning - php

I am having trouble getting my code validation to work. I have written validation for a name, surname and email address, however, I don't know where to insert a command for the php code to be called in my main html.
I was thinking I have to add an action into a form like this:
<body>
<div class="logo"></div>
<div class="login-block">
<h1>Create Account</h1>
<form action="insert_data.php" method="post">
<form action="validate_data.php">
<input type="text" value="" placeholder="First Name" name="first_name" />
<input type="text" value="" placeholder="Last Name" name="last_name" />
<input type="email" value="" placeholder="E-mail Address" name="email_address" />
However, I don't know if that is correct. All three of the validation notes are saved in a file called 'validate_data.php'.
My code for name and surname validation is pretty much the same, with the main 'name' spaces changed:
<?php
$first_name = test_input($_POST["first_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
$first_nameErr = "Incorrect name format.";
}
?>
and for my email:
<?php
$email_address = test_input($_POST["email_address"]);
if (!filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
$email_addressErr = "Invalid email format.";
}
?>
Is there any particular place I will have to call this? Or am I just doing some stupid mistake and missing it?

You don't put it in the HTML unless you are sending the page to itself, in which case it is usually best to put the PHP at the top of the page. It would need to be named as a .php page not .html then. That way if, for example, you wanted to make the values of the form stay as what was submitted you could echo them after they are cleaned up by setting the textbox value
value="<?php echo $first_name; ?>"
for example. If you are submitting to insert_data.php all the PHP just lives on that page at the top. You seem to have too many <form actions - you can only submit once. Best to put your cleanup code at the top of insert_data.php and submit to that.
If it is on the same page you would need to wrap it in
if( isset($_POST["first_name"])){
// do the cleanup
}
or you will get messages for the empty inputs which have not had the chance to be submitted as the page loads. And do the same for the email address which you definitely don't want to have blank if you are subsequently going to use it for a mail form's Reply-To: address (the From: should always be an address on your server or you will be back here posting wondering why it doesn't work!)
You could include the validation script but that is possibly a bit risky and for the length of the code there is probably little advantage in having it as an include. Risks of including unsafely: http://www.webhostingtalk.com/showthread.php?t=199419
You would then use - assuming your includes are in a folder called inc/
include "inc/validate_data.php";
at the top of your insert_data.php page - without the brackets shown in that article - it is a declaration, not a function.
Another good article on includes:
http://green-beast.com/blog/?p=144
If you were looping out posts, for example, the code to do that would be somewhere among the HTML inside the div where you wanted them to appear.

Related

Inline PHP Send Mail not working

PHP isn't my strength and when I was asked to implement a modal newsletter subscription popup I cringed because I knew I was going to have to use PHP. I have scoured the internet all day trying various things, but I cannot seem to get anything to work and I am really hoping that someone will be able to point me in the right direction. It is super simple, I only need a name and email address which is then sent to an account I specify. I am sure this is really basic, but with my lack of experience with PHP I am totally lost as to where I am going wrong. My code is below.
<?php
if($_POST["submit"]) {
$recipient="my#emailaddress.com";
$subject="Newsletter Subscription";
$senderName=$_POST["name"];
$senderEmail=$_POST["email"];
$mailBody="Name: $senderName\nEmail: $senderEmail\n\nThis is a test!";
mail($recipient, $subject, $mailBody, "From: $senderName <$senderEmail>");
header('Location:http://www.urltoredirect.com/');
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="sendmail.php">
<div class="rbm_input_txt">
<input type="name" name="name" placeholder="name" required>
</div>
<div class="rbm_input_txt">
<input type="email" name="email" placeholder="email" required>
</div>
<div class="rbm_form_submit">
<button type="submit" class="rbm_btn_x_out_shtr">subscribe</button>
</div>
</form>
</body>
</html>
I save the file as sendmail.php and upload to my server. When I fill out the form, the page just reloads, it isn't redirecting to the URL specified and I am not receiving any email. I suspect the issue is in the send mail and once that is sorted, the redirect will work. Can anyone see anything obvious that I am missing?
EDIT: Added the name attribute to my code as suggested below. Issue is still unresolved.
You're checking to see if $_POST['submit'] is truthy, but your form never actually sets that value. There are two changes you can make to fix this:
In order for the submit key to be present in your request, you need to assign it to a field in your form. You'll likely want to add it to the submit button, which can be done by simply adding the name parameter to your submit button:
<button name="submit" type="submit" class="rbm_btn_x_out_shtr">subscribe</button>
Even with the above change, $_POST['submit'] will still evaluate to false since its value will be empty. (You can see this in the rules for boolean conversions.) You can get around this by checking to see if its set, rather than if it's truthy:
if (isset($_POST['submit']))
Alternatively, you could just look for a different field such as name or email, since you know both of those fields will be set on submit.
there must be name in tags
<div class="rbm_input_txt"><input type="name" placeholder="name" name="name" required><input type="email" placeholder="email" name="email``" required

When clicking submit the form redirects to the registration manager

I am attemping to create a PHP login system using MySQLi.
However I have created an HTML Form:
<form action="register_manager.php" method="post">
<p>Please fill all fields!</p>
<input type="text" name="username" value="<?PHP print $getuser; ?>" maxlength="15" /><br />
<input type="password" name="password" placeholder="Password" maxlength="15" />
<input type="password" name="confirmpassword" placeholder="Confirm Password" /><br />
<input type="text" name="email" placeholder="E-Mail Address" />
<p style="margin: 0; padding: 0;">
(Use a vaid a valid E-Mail Address for activation!)
</p>
<p>
Already got an account?
</p>
<input type="submit" name="regsubmit" value="Register"/><br />
<?PHP echo '<p>'.$errormsg.'</p>'; ?>
</form>
Once I click submit, it redirects me to the registration_manager.php page, which is not what I want it to do. I am new to PHP so I am not aware on why it is doing this, instead of registering the user.
This is the register_manager.php file:
http://pastebin.com/cvbA6L6P
The action specified in your form is register_manager.php so whenever you hit the submit button you will get redirected there. Also, in the link you provided of the source code of register_manager.php, you're generating error messages, depending on the case, but never printing them on the page so the user can see what is wrong, unless of course the html form you provided is included in the register_manager.php. Finally, when testing make sure you fill all the requirements set by the if statements in you register_manager.php file, i.e. pass all wanted fields (username, email (which must be longer than 7 chars, containing the '#' and '.' characters), password, password confirmation). Hope this solves your question!
What you are describing is normal. The browser will send a POST request to the URL defined as action. So you need to render the form there as well. You can either abstract the form out and reuse it in both files or do the initial form rendering and the processing in one file by checking if $_POST['regsubmit'] is set (if it is not set you are rendering the form initially).
Submit button will activate the request of the webpage specified in the attribute action, passing the information inside the form by the method selected. In your example, the information is passed to register_manager.php using POST method.
To retrieve the information passed, you could use the arrays $_POST and $_GET depending the method used. In your example:
<?php
print $_POST['password'];
print $_POST['confirmpassword'];
print $_POST['email'];
?>

Trying to test my post form (debugging)

I have a form, and I'm checking to see if it's submitting properly to post. This is my first foray into POST, so other than rudimentary research and tutorial stuff, I'm having a lot of problems. I wrote a simple script to see if my form is working properly at all. The HTML is clipped to only show you the form; I do have a validation and all that.
There is no naming conflict, whether in the filenames or those of the variables, so I assume it's a syntax error or just me being that guy with no knowledge of post whatsoever.
Here's the HTML:
<html>
<body>
<form name="Involved" method="post" action="postest.php" target="_blank">
Name: <br><input type="text" name="name" title="Your full name" style="color:#000" placeholder="Enter full name"/>
<br><br>
Email: <br><input type="text" name="email" title="Your email address" style="color:#000" placeholder="Enter email address"/>
<br><br>
How you can help: <br><textarea cols="18" rows="3" name="help" title="Service you want to provide" style="color:#000" placeholder="Please let us know of any ways you may be of assistance"></textarea>
<br><br>
<input type="submit" value="Submit" id=submitbox"/>
</form>
</body>
<html>
Here's the post (named postest):
<?php
$name = $_POSTEST['name'];
$email = $_POSTEST['email'];
$help = $_POSTEST['help'];
echo {$name}, {$email}, {$help};
?>
This post was derived from this tutorial.
Also, I might as well ask: How would I go about submitting information to be (semi)permanently stored on a spreadsheet for my later perusal? However, this is a secondary question.
Part of your problem is that you are using a variable you're calling $_POSTEST when really what you want is the $_POST array. $_POST is a special reserved variable in PHP (and needs to be referenced using that exact syntax) which is:
An associative array of variables passed to the current script via the
HTTP POST method.
Reference: PHP Manual - http://php.net/manual/en/reserved.variables.post.php
So whatever input names and values you're passing into the PHP script come in via HTTP POST, and they'll be located in the $_POST array.
So using your example, it would be:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$help = $_POST['help'];
echo {$name}, {$email}, {$help};
?>
There is not any $_POSTTEST array in php.
Use $_POST.

How to stop redirecting to the php page when submitting an HTML form

I've got your run of the mill form, with a PHP script to validate and email it off.
<form id="contactForm" action="contact.php" method="post">
<fieldset>
<p>
<label>NAME:</label>
<input name="name" id="name" type="text" />
</p>
<p>
<label>EMAIL:</label>
<input name="email" id="email" type="text" />
</p>
<p>
<label>COMMENTS:</label>
<textarea name="comments" id="comments" rows="5" cols="20" ></textarea>
</p>
<p><input type="submit" value=" " name="submit" id="submit" /></p>
</fieldset>
<p id="error" class="warning">Message</p>
</form>
The problem is, that when I click submit, it takes me off the page I was on (filling out the form) and takes me to a blank white page - contact.php.
Is there any way I can stay on the original contact.html page after clicking submit and just let the emailing happen in the background?
Ajax is your best best. If not, the quick and dirty way would be to put a php block at the top of you page and put all the stuff from your contact.php in an if(isset($_post['data'])) statement.
Brief example
<?php
if(isset($_POST['variable_from_form']))
{
// send mail, insert in database, etc. stuffs
}
?>
Basically, if there is post data, do something, if not, just write the page as normal
Php is doing the job assigned: it is redirecting to the page you asked for in the action="" tag.
If you need to validate an email or login, you should use the same contact.php form to do both: enter user email and validate and/or login or whatever you want to do.
At the begining of the contact.php use php script to receive submitted fields, validate, sanitize and insert or whatever.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email=$_POST['email'];
$email=filter_var($id_post, FILTER_SANITIZE_EMAIL);
if(empty($email) )
{$error=['email']="enter a valid email"}
else {
$user_email=$email;
}
}
if(empty($errors) && $_POST)
{
//with $user_email defined and sanitized you can do whatever you want: insert, edit, query, email.
}
elseif ($errors || !$_POST)
{
?>
Here, put all the html form, at the end, close the open php.
<?php
}
?>
You could put an iframe on your page that initially loads a blank page within it and have the form's target be the iframe so it will post into the iframe.
Have the iframe large enough so that you can put a simple message like "Your information has been accepted" can be printed by contact.php
Here's a link that tells you how to do it.
How do you post to an iframe?
you might use javascript (Ajax) to communicate with your server, that way it will continue using the same html file.
Another way it is to rename your html file to .php extension and work on this file.
Good luck!

Storing form data with PHP Session

I am working on an HTML form whose data would be saved on a failed submit, or page refresh.
We are using a PHP Session to store this data, and we post the elements back when needed.
The issue is that it's not working. We need the form data to be preserved on a submit with errors, or page refresh. Currently on a failed submit, or page refresh, there is no data being stored in the session.
I'm fairly new to PHP, and most of this code is not mine, so go easy on me.
The PHP Sumbit code being used is:
Software: PHPMailer - PHP email class
Version: 5.0.2
Contact: via sourceforge.net support pages (also www.codeworxtech.com)
Info: http://phpmailer.sourceforge.net
Support: http://sourceforge.net/projects/phpmailer/
SESSION:
<?php
session_name("fancyform");
session_start();
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<div class="message-sent"><p>Message was sent successfully. Thank you! </p></div>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
FORM:
<form id="contact-form" name="contact-form" method="post" action="submit.php">
<p><input type="text" name="name" id="name" class="validate[required]" placeholder="Enter your first and last name here" value="<?=$_SESSION['post']['name']?>" /></p>
<p><input type="text" name="email" id="email" class="validate[required,custom[email]]" placeholder="Enter your email address here" value="<?=$_SESSION['post']['email']?>" /></p>
<p><input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?=$_SESSION['post']['phone']?>" /></p>
<p>
<select name="subject" id="subject">
<option>What event service are you primarily interested in?</option>
<option>Event Creation</option>
<option>Project Management</option>
<option>Promotion</option>
</select>
</p>
<textarea name="message" id="message" class="validate[required]" placeholder="Please include some details about your project or event..."><?=$_SESSION['post']['message']?> </textarea>
<input type="submit" value="" />
</form>
You are outputting $_SESSION['post']['form_element'] to your template but in the above PHP code there is no mention of setting that data. For this to work, you would have to loop through the $_POST array and assign each key pair to $_SESSION['post']
At that point you should be able to access the previously submitted form data from the session just as you have coded above.
add this to your submit.php:
session_start();
foreach ($_POST AS $key => $value) {
$_SESSION['post'][$key] = $value;
}
This will move all the data from $_POST to $_SESSION['post'] for future use in the template, and should be all you need to get it working.
HTTP is stateless, and data that is not submitted will not remain unless you use a client-side approach (webstorage, etc).
You need to parse the post variables and add them to the session super global, right now you are referencing $_SESSION['post']['phone'] which won't work as you expect.
// Assuming same file, this is session section
if (array_key_exists('submit', $_REQUEST)) {
if (array_key_exists('phone', $_REQUEST)) {
$_SESSION['phone'] = $_REQUEST['phone'];
}
}
// Form section
<?php $phone = (array_key_exists('phone', $_SESSION)) ? $_SESSION['phone'] : null;?>
<input type="text" name="phone" id="phone" placeholder="Enter your phone number here" value="<?php echo $phone ?>" />
Either you didn't include the code for submit.php or, if you did, the problem is clear: you're never setting the session values. In order to do that, you'd use
session_start();
// etc...
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['phone'] = $_POST['phone'];
// etc...
on submit.php and then the form page (presumably another page?) could then check if those values have been set
.. value="<?php if (isset($_SESSION['post']['name'])) echo $_SESSION['post']['name']; ?>" ..
I may be wrong, but I think you need to get the posted values from the form by using something like
if ($_POST['errStr']) {
$_SESSION['errStr'] = $POST['errStr'];
}
If i'm right its the way you're trying to access the variables after posting the form
If you look at the METHOD attribute of the form it set as post, so this should return the values you want to pass accross pages.
Maybe this isn't what you were asking though, i'm a little unclear what part the problem is with, i'm assuming its taking values from the form and getting them out on the next page.
If you want to do it when the page is refreshed/exited you'd probably need to use some javascript client side to try and catch it before the action happens.
Don't know if this is possible. PHP wont help you for that as its executed server-side, and the client wont submit anything (useful) to the server when they exit/reload, only the command to perform the action.
This'll probably require using javascript listeners, eg window.onclose (although apparently that doesn't work for safari or firefox 2), and within that an ajax xmlhttprequest to send the data to your server.
For failed submit (ie capture form with invalid data in?) its almost the same case as form that submit worked on. Just re-check the data on the other side when you're processing it.

Categories