PHP cant get passed on question mark on clean url - php

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.

Related

Send array values in PHP form

I have a HTML form with embedded PHP code that creates a checkbox for each value contained in an array. Just like this:
<?php
$rows = array_map( 'str_getcsv', file( 'file.csv' ) );
$header = array_shift( $rows );
foreach ( $rows as $row ) {
echo '<input type="checkbox" id="'.$row[0].'" name="'.$row[0].'">
<label for="'.$row[0].'">'.$row[0].'</label>
<input type="number" name="'.$row[0].'" placeholder="Some text">';
}
?>
Now, I want to send this form using this code, which is inserted into another PHP file:
<?php
if( isset( $_POST ) == true && empty( $_POST ) == false ) {
$account = $_POST['account'];
$investment = $_POST['row[0]'];
$password = $_POST['password'];
$formcontent=" Account: $account \n $row[0]: $investment \n Password: $password";
$recipient = "my#email.com";
$subject = "My Form";
$mailheader = "From: My Form <my#form.com>";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Some text";
}
?>
But it doesn't work. When you click on submit button the form does nothing.
I've checked it with success with HTML-only code, so I guess I'm making a mistake with PHP.
For those interested, here's a link to my form: Example
EDIT: I've removed preventDefault, as pointed by #DavidJorHpan, but I'm still stuck. I'm unable to make my form.php send $row[0] to my email.
Because you use preventDefault so it will never submit form until you code for submitting form
$("button").click(function(e) {
e.preventDefault();
});
You can remove that code or add code like
$('form').submit();
As David JorHpan pointed out in the second answer, you've got to remove preventDefault() from the button click event. That prevents the form from being submitted.
For every checkbox you have a corresponding number input field. Although possible, its not a good practice to have spaces in your 'name' attribute values. Try replacing those spaces with dashes or underscores. For example you can do something like below:
name="'.str_replace(' ','_',$row[0]).'"
and same can be done to id attribute values.
Your form submit check should work but it will make more sense if you change that as follows:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// process here
}
After doing these changes try loading the page and see how it goes.

PHP echo in a HTML Page

I have a contact.html page I have a form on. The form action goes to .php page to handle the email, nothing special. On that page I have:
<?php
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$FirstName = check_input($_REQUEST['FirstName']);
$LastName = check_input($_REQUEST['LastName']);
$email = check_input($_REQUEST['email']);
$phone = check_input($_REQUEST['phone']);
$message = check_input($_REQUEST['message']);
$human = check_input($_REQUEST['human']);
$webpackage = check_input($_REQUEST['webpackage']);
$webdesign = check_input($_REQUEST['webdesign']);
$customdesign = check_input($_REQUEST['customdesign']);
if ($human == 5) {
$to = "****.com";
$subject = "From ****";
$body = " From: $FirstName $LastName\n\n E-Mail: $email\n\n Phone: $phone\n\n Message:\n\n $message\n\n Web Package:$webpackage\n\n Web Design:$webdesign\n\n Custom Design:$customdesign";
mail ($to, $subject, $body);
header('location: index.html');
}
else {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
}
?>
I have a simple box that equals 5 that I am checking value for. This works and email sent with all info. BUT if not equal to 5 is where the problem starts. The page goes to my action.php page and is blank.
My html on the contact.html page is:
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo($result); ?>
</div>
</div>
Using this to get to my action.php page through form. Everything else is .html:
<form class="form-horizontal" id="contact-form" method="post" action="/action.php">
Is there a way to do this? I have a work around where I just echo the error from the .php page. This works if !=5 but not exactly what I want to do. As you may tell, I am not PHP literate.
You can set a variable in the $_SESSION[] array, and in your "else" section use Header() to redirect to a page where you display the value you stored.
See example in this other answered question:
displaying a message after redirecting the user to another web page
Update your else part with following code :
} else {
header('location: contact.html?status=error');
}
Now check if get method is set on your contact.html page. if yes than set and display your $result value.
<?php
if(isset($_GET['status']) && $_GET['status']=='error' ) {
$result="<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please go back and check your anti-spam answer</div>";
} ?>
on contact.html check if $result has value and print it :)
Add a redirect towards contact.html in your action.php like this
else {
$result="Sorry there was an error sending your message. Please go back and check your anti-spam answer";
$result=str_replace(" ","%20",$result);
header('location: contact.html?result=$result');
}
And then get the result in contact.html with GET
$result= $_GET['result'];
Ideally do the html mark up for result in the destination Contact.html page after you receive the result. That eliminates the nuances of passing html over http

Validating simple RSVP form through PHP

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"];

How to redirect to another page in php?

Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>

How would I go about making this error message appear when form field is not right?

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/

Categories