I have the following PHP code:
<?php
//Connection to PDO Database
?>
<form method="post" action="">
<p>Busisness telephone 1</p><input id="business_telephone_01" name="business_telephone_01" tabindex="auto" value="<?php echo $result['business_telephone_01']; ?>" type="text" />
<input name="submit" type="submit" value="Save Changes"></form>
<?php
//Get from Form
if((empty($_POST['submit']) === false)){
$business_telephone_01 = $_POST['business_telephone_01'];
//Formating of telephone numbers
$message = 'This message I want to display';
echo 'This is another message';
}
echo $message;
//Code to update table through PDO
?>
Regardless of where I do the echo whether it is echo 'This is another message'; within the conditional brackets or _ echo $message;_ outside the brackets nothing is being echoed and no error is being displayed.
The html form and the PDO are working correctly and are being updated but nothing is being echoed. No error is being shown in the error log.
UPDATE:
If I use if((empty($_POST['submit']) === false)){ I get PHP
Notice: Undefined variable: hello
If I use if (isset($_POST['submit'])) { I get PHP Notice:
Undefined variable: hello
If I use if (!isset($_POST['submit']))
{ it gives me a list of undefined variables that I use e.g. from
my code above business_telephone_01
My full code
if((empty($_POST['submit']) === false)){
//Get from Form
$address_building_name = $_POST['address_building_name'];
$address_building_number = $_POST['address_building_number'];
$address_street = $_POST['address_street'];
$address_locality = $_POST['address_locality'];
$address_postcode = $_POST['address_postcode'];
$address_country = $_POST['address_country'];
//Formating of address
$address_building_number = strtoupper($address_building_number);
$address_building_number = str_replace(' ','',$address_building_number);
$address_building_name = ucwords($address_building_name);
$address_street = ucwords($address_street);
$address_locality = ucwords($address_locality);
$address_postcode = strtoupper($address_postcode);
$address_country = ucwords($address_country);
echo 'Hello';
$good = 'Good bye';
}
echo $good;
I'd be willing to bet $message isn't being echo'd because it's never initialized. (The if block, where it is supposed to be initialized, is not being executed because the conditional is failing.)
First off, you should use isset to determine if a POST variable has been submitted:
if (isset($_POST['submit'])) {
Or, to see if it has not been submitted:
if (!isset($_POST['submit'])) {
Secondly, you should enable error reporting on your program and let us know what errors (if any) you are getting:
error_reporting(E_ALL);
ini_set("display_errors", 1);
You can add these two lines to the very top of your script, right after the opening <?php line, which should help shed some light on the situation.
The problem could be that the $message variable is never set within your if statement.
If the 'if' condition is not matched, then $message is never set and you will not be able to echo the value.
To test, you could set the $message variable to some value before you start your if statement.
$message = 'condition failed';
if(isset($_POST['submit'])){
....
$message = 'This message I want to display';
}
echo $message;
If the condition is met, it will echo "This message I want to display".
If the condition fails, it will echo 'condition failed';
A quick dirty test, but it will tell you if the $message variable will be initialized inside your 'if' statement.
Related
I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>
If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.
I need some help with my code as I have got a problem with get pass on the if statement. I am working on the clean url to create a function like create_newsletter.php?template=new when I am on the same page.
When I try this:
if(isset($_POST['submit']))
{
sleep(2)
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
It will not get pass on this line:
if(isset($_GET['template'])
Here is the full code:
<?php
$template = "";
if(isset($_GET['template']))
{
$template = $_GET['template'];
}
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
}
?>
<form method="post">
<input type="text" name="messagename" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
I have got no idea how I can get pass on the if statement when I am using header("Location:). I have also tried if ($template) but it doesn't get pass.
What I am trying to do is to connect to my php page create_newsletter.php. I want to input my full name the textbox called messagename and input the subject in the subject textbox then click on a button. When I click on a button, I want to redirect to create_newsletter.php?template=new as I want to disable on two textbox controls messagename and subjectthen add the iframe to allow me to get access to another php page so I could write the newsletter in the middle of the screen.
Can you please show me an example what is the best way forward that I could use to get pass on the if statement when I click on a submit button to redirect me to create_newsletter.php?template=new so I could disable these controls and add the iframe?
Thank you.
You are checking if(isset($_GET['template']) inside the if(isset($_POST['submit'])) condition, but the redirect doesn't send a post request.
This should work:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
But if you need to make a POST request in the redirect, you would need to print a <form> and submit it in the client side, or use $_SESSION in the example bellow:
session_start();
if(isset($_POST['submit']))
{
sleep(2)
$_SESSION['messagename'] = $_POST['messagename'];
$_SESSION['subject'] = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
// $_SESSION['messagename'] and $_SESSION['subject'] are available here
echo "hello robert now you are working on the template";
}
When you are checking if(isset($_POST['submit'])), you are redirecting before you can reach the if(isset($_GET['template']).
But I am assuming you would expect this to run because $_GET['template'] will be set. Although, the problem with your code is that when you redirect, $_POST['submit'] will not be set, therefor it will not execute anything in the if(isset($_POST['submit'])) block, including if(isset($_GET['template']).This is because a POST request is not persistant, and will not remain if you reload, or redirect
You should consider the following:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new");
}
if(isset($_GET['template'])
{
echo "hello robert now you are working on the template";
}
?>
Accessing the $messagename and $subject in the if(isset($_GET['template'])
If you want to access the $messagename and $subject in the if(isset($_GET['template']), you can pass them in the URL. Because when you redirect, no $_POST variables will be set, they will go away. You can accomplish this by doing:
if(isset($_POST['submit']))
{
sleep(2)
$messagename = $_POST['messagename'];
$subject = $_POST['subject'];
header("Location: http://example.com/newsletters/create_newsletter.php?template=new&messagename=".$messagename."&subject=".$subject);
}
if(isset($_GET['template'])
{
$messagename = $_GET['messagename'];
$subject = $_GET['subject'];
echo "hello robert now you are working on the template";
}
?>
There are two errors in the OP's code which unfortunately the officially accepted answer reflects as well. A semi-colon needs to be appended to the statement that uses sleep() and an extra parenthesis is needed in the statement that tests for $_GET['template'].
In truth, one does not need to complicate the code with signal processing offered by sleep() in order to delay submission of the POSTed data just to determine the value of $_GET['template']. One could omit sleep() and alter the the code slightly, as follows:
<?php
if( isset($_POST['submit']) )
{
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
else
if( isset( $_GET['template']))
{
echo "hello robert now you are working on the template";
exit;
}
Also, instead of using $_GET another alternative is to use $_SERVER['QUERY_STRING'], as follows:
<?php
$qs = parse_url($_SERVER['PHP_SELF'], PHP_URL_QUERY);
if( $qs == 'template=new' ){
$template = split("=",$qs)[1];
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
<html>
<head><title>test</title></head>
<body>
<form method="post" action="">
<input type="text" name="mess" value="">
<input type="text" name="subject" value="">
<input type="submit" name="submit" class="btn btn-primary" value="Next Step">
</form>
</body>
</html>
The component parameter of parse_url() enables this function to return the query string. One may also opt instead to employ parse_str(), as follows:
<?php
$queries = "";
parse_str($_SERVER['QUERY_STRING'], $queries);
if( isset($queries['template']) && ($queries['template'] == 'new'))
{
$template = $queries;
echo "hello robert now you are working on the template";
exit;
}
else
if(isset($_POST['submit']))
{
sleep(2);
$mess = htmlentities($_POST['mess']);
$subject = htmlentities($_POST['subject']);
header("Location: http://localhost/exp/create_newsletter.php?template=new");
exit;
}
?>
Note: it is very important to always treat data from a POST or GET as tainted instead of directly assigning the data to a variable and using that variable. Using htmlentities() is one way to attempt to prevent possible security issues.
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
I have written a code - It takes user input and displays sha1() string for the input.
I get the 'undefined index' notice on local host even after declaring the variables and using isset() function.
Notice: Undefined index: enc in C:\Program Files\EasyPHP-12.1\www\MySQL\localhost_drupal\encrypt.php on line 61
It works fine on the remote (production) server.
What is the fault in the following code?
<?php
//variable declaration
$enc = $len = "";
// checking with isset
if(isset($_POST['enc'])) {
//sha1()
$enc = sha1($_POST['enc']);
// strlen function
$len = strlen($_POST['enc']);
}
?>
//HTML
<!DOCTYPE html>
<html>
<head><title>Generate Password</title></head>
<body>
<form name = "encry" action = "encrypt.php" method = "post">
<input type = "text" name = "enc" >
<input type = "submit" value = "Submit">
</form>
//OUTPUT
<?php
//Line 61
echo "<p> You entered :" . $_POST['enc']."</p>";
echo "<p> Length of the string you entered :" . $len. "<p>";
echo "<p> Your Password is : ". $enc . "</p>";
?>
</body>
</html>
The reason being for the error is that your entire code is inside one page and errors out on initial load. Error reporting is set on one server, but isn't on the other.
You should be using isset() against a named submit button (which I have named) and around where you're using
echo "<p> You entered :" . $_POST['enc']."</p>"; etc..
Change your code to the following:
<?php
//variable declaration
$enc = $len = "";
// checking with isset
if(isset($_POST['enc'])) {
//sha1()
$enc = sha1($_POST['enc']);
// strlen function
$len = strlen($_POST['enc']);
}
?>
//HTML
<!DOCTYPE html>
<html>
<head><title>Generate Password</title></head>
<body>
<form name = "encry" action = "encrypt.php" method = "post">
<input type = "text" name = "enc" >
<input type = "submit" value = "Submit" name = "submit">
</form>
//OUTPUT
<?php
if(isset($_POST['submit'])) {
//Line 61
echo "<p> You entered :" . $_POST['enc']."</p>";
echo "<p> Length of the string you entered :" . $len. "<p>";
echo "<p> Your Password is : ". $enc . "</p>";
}
?>
</body>
</html>
To set error reporting on:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
It's an E_NOTICE. Likely on production you suppress error messages (or at least notices). This is fine, but it does explain why it breaks in development.
Fix the issue and the notice will go away.
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:
if(isset($_POST['submit'])) {
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
$error = "";
} else {
$error = "Please fill in the required fields.";
}
}
In the form, I have a span class like so:
<span class="error">'.$error.'</span>
I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?
Thanks so much for any help or tips!
In order to process the form while staying on the page, you will need to incorporate some AJAX. The easiest way to do this is to use a framework of some sort (recommend jQuery). This should give you some insight into how to develop such functionality. If you get stuck, we're here to help.
http://api.jquery.com/jQuery.post/
Following your current model, I am assuming you do not mean AJAX and that you merely mean the server side code and form cohabitate on the same script. You can set the action of the form to $_SERVER['PHP_SELF'] first to ensure the proper action attribute is set.
Are you echoing out the error message within the span, or is all that output being placed after an echo statement?
echo '<span class="error">'.$error.'</span>'
Or, if not in the PHP context outside of script
<span class="error"><? echo $error; ?></span>
Also, you may want to consider using a mature php mailing solution like PHP Mailer to help set headers and ensure more effective delivery.
You don't need any AJAX.
$error = '';
if (isset($_POST['submit'])) {
if ( <<< insert check for required fields >>> ) {
// handle form, send mail, etc
// you may want to redirect on success to prevent double posting
} else {
$error = "Please fill in the required fields.";
}
}
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.
<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
if (!empty($name) && (!empty($email) || !empty($phone))) {
mail( "EMAIL#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
} else {
$error = "Please fill in the required fields.";
}
}else{ ?>
<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
<span class="error><?php echo $error; ?></span>
Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
Comment: <br/>
<textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
<input type="submit" value="Submit Email"/>
</form></div>
<?php } ?>
When I handle form validations, I tend to create an array to hold the error messages, like so:
<?php
$error = array();
if( $POST ){
# Form is Submitted
if( /* TRUE if "email" is empty */ ){
$error['email'] = 'Please provide an Email Address';
}elseif( /* TRUE if "email" is not a valid address */ ){
$error['email'] = 'Please provide a Valid Email Address';
}elseif( /* TRUE if "email" is already associated with a User */ ){
$error['email'] = 'The Provided Email Address is Already Taken';
}
...
if( count( $error )==0 ){
# No Error has been Recorded
# Do Successful Things
}
} /* Closing if( $_POST ){ */
Then within the presentation/display section, I have something like:
<?php if( count( $error )>0 ){ ?>
<div id="error">
The following Errors have occurred:
<ul>
<?php foreach( $error as $k => $v ){ ?>
<li><?php echo $k; ?>: <?php echo $v; ?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
And within the form, something like:
<input name="email"<?php echo ( $error['email'] ? ' class="error"' : '' ); ?> />
This means that:
Customised, multi-tiered error messages can be recorded.
A summary of the error messages can be shown.
Fields associated with the error messages can be marked.
Has worked well in my experience thusfar.
Yep, I think You have two methods to do that, as already explained above...
When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...
You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..
What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)
Thank You.
ADynaMic
My suggest is to use ajax call when submit,
according to the answer come back, you update the span of error.
you can find a lot of examples in web like
http://jqueryfordesigners.com/using-ajax-to-validate-forms/
http://www.the-art-of-web.com/javascript/ajax-validate/