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
Related
I have this question about why my form is not posting data to my PHP script. To unsubscribe from an emailing list I've set up, I send the user that has unsubscribed an email with a form that posts some data.
<html>
<body>
<div>
<p>This is a confirmation message to confirm that you unsubscribed from the sci-eng email list.</p>
<p>Click on the button below to confirm your unsubscription.</p>
<form id="unsubform">
<div class="form-in">
<input type="hidden" id="emailkey" name="emailkey" value="key">
<input type="hidden" id="email" name="email" value="email#domain.com">
<button class="btn" id="submit" type="submit" formaction="http://redlinks.ca/sci-eng/db/unsubscribe.php" formmethod="post">Unsubscribe</button>
</div>
</form>
</div>
</body>
</html>
When on the page that the form is POSTed to, I get the "no data" error that I have set up if there is no data in the $_POST["email"] variable. I have tried using var_dump($_POST), but that just returns with array(0) { } and that isn't working for me.
The thing that confuses me the most is when I copy the exact html from the email, and paste it into a blank page, when I click on submit/unsubscribe it posts the data just fine, and elsewhere on my site I have the exact same script, the only different being the formaction is without the /db in it. The page that one is sent to behaves how it should, showing the propper array of data instead of nothing. That's the only difference.
If it makes any difference, I use Thunderbird for Windows 10 as my email client.
Anyone who thinks they can help would be appreciated :)
Due to security issues forms are not supported and not recommended within emails. Most of email clients will warn the user of a risk or simply will disable it and it will not work, like in your case.
The best practice for enabling unsubscribing is by using a link. You can pass any requierd parameter for unsubscribing on the link, for example http://www.example.com/unsubscribe.php?usermail=mail#gmail.com.
TRY WITH:
<html>
<body>
<div>
<p>This is a confirmation message to confirm that you unsubscribed from the sci-eng email list.</p>
<p>Click on the button below to confirm your unsubscription.</p>
<form id="unsubform" action="http://redlinks.ca/sci-eng/db/unsubscribe.php" method="post">
<div class="form-in">
<input type="hidden" id="emailkey" name="emailkey" value="key">
<input type="hidden" id="email" name="email" value="email#domain.com">
<button class="btn" id="submit" type="submit">Unsubscribe</button>
</div>
</form>
</div>
</body>
</html>
IF you won't use POST method so how your form values could be posted to phpScript. Try the following code.
<html>
<body>
<div>
<p>This is a confirmation message to confirm that you unsubscribed
from the sci-eng email list.</p>
<p>Click on the button below to confirm your unsubscription.</p>
<form id="unsubform" method="POST" action="http://redlinks.ca/sci-eng/db/unsubscribe.php">
<div class="form-in">
<input type="hidden" id="emailkey" name="emailkey" value="key">
<input type="hidden" id="email" name="email" value="email#domain.com">
<button class="btn" id="submit" type="submit" >Unsubscribe</button>
</div>
</form>
</div>
</body>
The default method is GET, not POST; you need to specify
<form method="post" ...>
Maybe a link to this form hosted online might be a better idea; some mail clients do not support showing mails; and maybe more clients might refuse to submit or post them due to security concerns (e.g. webmail interfaces).
Do not send form for confirmation.Try these steps :
Generate unique encrypted key for those email who unsubscribe and store in database
Send confirmation link to particular user email with key as (http://domainurl/confirm.php?key=1533c67e5e70ae7439a9aa993d6a3393)
Now check key for corresponding email and unsubscribe and also remove key from database
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.
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.
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.
I have this Contact form that works well. If someone sends me an email I get it. But for whatever reason I keep getting empty emails sent to me. Since no one could access that page im sure its not someone sending me the empty emails. I dont know what the problem is. Any help?
<form method="post" id="contactform" name="contactform" action="comment.php" id="ContactForm" name="ContactForm" method="post">
<fieldset>
<label>Email *</label>
<input class="text" type="text" name="email">
<label>Name *</label>
<input class="text" type="text" name="name" />
</fieldset>
<input class="submit-button" type="submit" name="submit" id="submit" value="Send" />
</form>
and my contact.php
<?php
$email.= "<b>Email : </b>".trim($_POST['company'])."<br/>";
$email.= "<b>Name : </b>".trim($_POST['name'])."<br/>";
//Replace YourEmailAddress#Yourdomain.com with yours, eg:contactus#mywebsite.com
//Both on the next line and on the mail function below.
$headers = "From: email#email.com\r\n";
$headers .= "Content-Type: text/html";
mail(
"Your Name<myname>",
"Header",
$email,
$headers
);
header("www.google.com");
?>
the "header" part in my php form is to redirec the user to a page after sending the form.
Thanks in advance.
You are probably getting visits from bots. Your script will always trigger an E-Mail, even if no POST data is present.
In your contact script, as a basic measure of protection, add something like
if ($_POST["submit"] != "Send")
die();
add further validation (as pointed out in the comments) as needed.
Might be because you don't appear to be validating the form inputs, so it can be submitted blank.
Sometimes I do this to websites (test validation, end up sending blank email), but I usually add a message later to "Validate your input!".
Excuse me if you are indeed doing validation, but that was my gut instinct because I see a lot of people fail to validate even the presence of a required input, let alone the integrity.
Company doesnt exist in your form but you try to parse it.
And maybe 2 form name declaration is not that good but its not your answer.