I'm similar to php and don't undestand what is the problem.
Sometimes php function send me empty messages like
Vanema nimi
Lapse nimi:
Linn:
Telefoninumber:
Email:
Sünnikuupäev:
Sõnumi tekst:
But it should be filled with values like this
Vanema nimi test
Lapse nimi: test
Linn: test
Telefoninumber: test
Email: test#test
Sünnikuupäev: 21313
Sõnumi tekst:test
Here is my php code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Обратная Связь</title>
</head>
<body>
<?php
if (isset($_POST['parent'])) {$parent = $_POST['parent'];}
if (isset($_POST['child'])) {$child = $_POST['child'];}
if (isset($_POST['contacts'])) {$contacts = $_POST['contacts'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
if (isset($_POST['bbd'])) {$bbd = $_POST['bbd'];}
if (isset($_POST['city'])) {$city = $_POST['city'];}
if (isset($_POST['mess'])) {$mess = $_POST['mess'];}
$to = "info#test.ee"; /*Укажите ваш адрес электоронной почты*/
$headers = "Content-type: text/plain; text/html; charset=utf-8";
$subject = "Kontakti Info";
$message = "Vanema nimi $parent \n Lapse nimi: $child \nLinn:
$city \nTelefoninumber: $contacts \nEmail: $email \nSünnikuupäev: $bbd \nSõnumi tekst: $mess";
$send = mail ($to, $subject, $message, $headers);
if ($send == 'true')
{
echo "<b>Спасибо за отправку вашего сообщения!<p>";
echo "<a href=index.php>Нажмите,</a> чтобы вернуться на главную страницу";
}
else
{
echo "<p><b>Ошибка. Сообщение не отправлено!";
}
?>
</body>
</html>
<?php
header('Location: https://test.ee/aitah.html ');
?>
Please give me advice what is wrong.
If your script is a form processor only, you could e.g. add if(empty($_POST)) { die('No form data!'); } to the top to prevent it from running, except in response to a form submission.
If you require all fields to be filled in, you will have to check each of them before you process your email. You could cram all of those issets into one monster if(isset(...) statement. However, there's a simpler and more readable way to do it. First, let's set up a couple of variables:
// Your required fields:
$fields = ['parent', 'child', 'contacts', 'email', 'bbd', 'city', 'mess'];
// Your data is collected here:
$data = [];
// Any errors are collected here:
$errors = [];
Then, we loop over the fields and if values exist, add to $data, otherwise we add an error note.
// Loop to check your required fields:
foreach($fields as $field) {
// If value exists, add to $data:
if(!empty($_POST[$field])) {
$data[$field] = $_POST[$field];
}
// Else add error:
else {
$errors[] = 'Missing field: ' . $field;
}
}
if(empty($errors)) {
// No errors, send your email
// You can use "Vanema nimi {$data['parent']}...",
// ... otherwise: extract($data) to use $parent etc.
}
else {
// You could report those errors, or redirect back to the form, or whatever.
}
If there are errors (= missing fields), e-mails won't be sent. As a bonus, you now have a reusable piece of code that you can use for other forms with similar functionality simply by modifying the $fields array. (Wrapping it into a function is a good idea if you do need to reuse it; don't copy-paste code. function x($post, $fields) { ... } for a basic helper function.)
Note that here we are using empty in place of isset. If a blank form is submitted, the fields are set (to empty strings ""). Also note that empty returns true for anything that equals false (ie. "", 0, false, null, []). (If "0" is an expected and acceptable value, be aware of its "emptiness"!) On the other hand, isset returns true for anything not null.
P.S. If your code above is the complete code, and your script simply processes the form data and redirects, then you don't really need the HTML wrapper at all. It will never be displayed.
Related
I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>
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.
im getting the "invalid email address"
all is hardcoded for testing, what is missing? thanks!
<html>
<head><title>PHP Mail Sender</title></head>
<body>
<?php
/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$email = $HTTP_POST_VARS['example#example.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
echo "<h4>Invalid email address</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
echo "<h4>No subject</h4>";
echo "<a href='javascript:history.back(1);'>Back</a>";
}
/* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
elseif (mail($email,$subject,$message)) {
echo "<h4>Thank you for sending email</h4>";
} else {
echo "<h4>Can't send email to $email</h4>";
}
?>
</body>
</html>
Change
$email = $HTTP_POST_VARS['jaaanman2324#gmail.com'];
$subject = $HTTP_POST_VARS['subjectaaa'];
$message = $HTTP_POST_VARS['messageeeee'];
to
$email ='jaaanman2324#gmail.com';
$subject ='subjectaaa';
$message = 'messageeeee';
I think you want it to be hardcoded like this:
$email = 'jaaanman2324#gmail.com';
Otherwise you are trying to get the value out of HTTP_POST_VARS with the key of jaaanman2324#gmail.com
First, don't use $HTTP_POST_VARS, it's $_POST now.
Second, by writing $HTTP_POST_VARS['jaaanman2324#gmail.com'] you're looking for table element with juanman234#gmail.com key.
That's not what you wanted to do.
If you want to hardcode it, write
$email = 'jaaanman2324#gmail.com';`
if not, write
$email = $_POST['email'];
to get email field from form.
I read this post: What is a good invisible captcha? about using a hidden field in a web form to stop basic bots from pelting your website with spam mail via your web sites form mail. I'm currently using a php script to process my form mail. I built the script by following a 'bullet proff web form' tutorial I found. It looks like this:
<?php
// Pick up the form data and assign it to variables
$name = $_POST['name'];
$email = $_POST['email'];
$topic = $_POST['topic'];
$comments = $_POST['comments'];
// Build the email (replace the address in the $to section with your own)
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
I'd like to modify this script so that if a hidden field with the identifier 'other_email' was filled in then the form email wouldn't get sent. I'm guess it's as straight forward as wrapping the above code in an if statement to check if the field is complete. I've tried adding this under the "//Pick up the form data and assign it to variables" code:
$testBot = $_POST['other_email'];
then writing:
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
Don't know what I should put here to stop it posting, yet still show the success form so
the spam bot don't know
}
any help much appreciated. I have to say I don't really have a lot of php knowledge, I'm just starting to learn about it and thought form mail would be a good start.
How do I make this work in PhP?
if(other_email == "") //If other_email form section is blank then...
{
run all the code above inserted here;
}
else
{
header("Location: http://foobar/success.html");
}
keeping it very simple, it will work for you..
actually, it will
not submit / mail you anything...so NO SPAM
a simple bot will take it as it did it...
if you can use php on success page, then set a session variable (to make bot think it did its job, something like email_sent=true or success=true) and use that variable in success page, you will do it in else case where bot submitted the form..
Do you mean send message with fields?
Try this:
<?php
// Pick up the form data and assign it to variables
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$topic = $_REQUEST['topic'];
$comments = $_REQUEST['comments'];
// Build the email (replace the address in the $to section with your own)
if($name !== null && $email !== null && $topic !== null && $comments !== null){
$to = 'hello#cipherbunny.com';
$subject = "New message: $topic";
$message = "$name said: $comments";
$headers = "From: $email";
// Data cleaning function
function clean_data($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
$string = strip_tags($string);
return mysql_real_escape_string($string);
}
// Mail header removal
function remove_headers($string) {
$headers = array(
"/to\:/i",
"/from\:/i",
"/bcc\:/i",
"/cc\:/i",
"/Content\-Transfer\-Encoding\:/i",
"/Content\-Type\:/i",
"/Mime\-Version\:/i"
);
$string = preg_replace($headers, '', $string);
return strip_tags($string);
}
// Pick up the cleaned form data
$name = remove_headers($_POST['name']);
$email = remove_headers($_POST['email']);
$topic = remove_headers($_POST['topic']);
$comments = remove_headers($_POST['comments']);
// Send the mail using PHPs mail() function
mail($to, $subject, $message, $headers);
// Redirect
header("Location: http://foobar/success.html");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=shift_jis" />
<title>Send</title>
</head>
<body>
<form action="#" method="POST">
Name : <input type="text" name="name" /><br />
Email : <input type="text" name="email" /><br />
Topic : <input type="text" name="topic" /><br />
Comments : <textarea name="comments"></textarea><br />
<input type="submit" value="Send" />
</form>
</body>
</html>
I've never done that before and simply need a little advice how to do so …
I have a index.php file with a simple contact form.
<form id="contactform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"] ?>">
The index.php file has the following script on top.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<?php
//Vars
$Name = Trim(stripslashes($_POST['author']));
$EmailFrom = Trim(stripslashes($_POST['email']));
$Subject = Trim(stripslashes($_POST['subject']));
$Type = Trim(stripslashes($_POST['type']));
$Comment = Trim(stripslashes($_POST['message']));
$EmailTo = "address#something.com";
//Validation
$valid = true;
if ( $Name == "" ) $valid = false;
if ( isValidEmail( $EmailFrom ) == 0 ) $valid = false;
if ($Subject == "") $valid = false;
if ($Comment == "") $valid = false;
function isValidEmail( $email = null ) {
return preg_match( "/^[\d\w\/+!=#|$?%{^&}*`'~-][\d\w\/\.+!=#|$?%{^&}*`'~-]*#[A-Z0-9][A-Z0-9.-]{1,61}[A-Z0-9]\.[A-Z]{2,6}$/ix", $email );
}
//Body
$Body = $Type;
$Body .= "\n\n";
$Body .= $Comment;
//Headers
$email_header = "From: " . $EmailFrom . "\r\n";
$email_header .= "Content-Type: text/plain; charset=UTF-8\r\n";
$email_header .= "Reply-To: " . $EmailFrom . " \r\n";
//Send
if ($valid)
$success = mail($EmailTo, $Subject, $Body, $email_header);
?>
I have two questions now:
1.)
How exactly can I render/not-render certain stuff when either the validation went wrong or a success or an error comes back when submitting the mail?
e.g. I know that I can do that!
if ( !$valid )
print "Failed to make contact. Enter valid login credentials! <a href='/#contact' title='try again'>try again?</a>";
if ( $success )
print "Successfully made contact.";
else
print "Failed to make contact. <a href='/#contact' title='try again'>try again?</a>"; */
?>
However $valid will always be wrong on page-load when not submitting the form and also the email will always return the error message on the first page load. How can I only render or not render specific stuff when the form is submitted?
E.g. When submitting the form and a success comes back I don't want to render the #contactform anymore. I simply want to print "Successfully made contact" into an h1 or so.
How can I make that happen? It's probably rather simple I just can't find a solution for myself.
2.)
When using $_SERVER["SCRIPT_NAME"] or PHP_SELF as action the url after submitting the form will always change to "mydomain.com/index.php". Can I prevent that from happening? I want to submit the index.php file itself however I just don't like it when /index.php is written into the url. Is it possible to stop that from happening?
Thank you for your help!
Matt,
For the first question as to printing to the screen based on success or failure of the email, your checks seem fine, but you probably aren't going to get an email failure in time to display that to the screen. That said, you just need to wrap your second set of code in an if statement. Something like this:
if( isset($_POST['Submit']) ){ //only attempt to display if form submitted.
//Your code here
}
As for not including the directory in the form action, there are many ways to do this, but here's one:
$scriptString= explode('/',$_SERVER['SCRIPT_NAME']);
$scriptSize = count($scriptString)-1;
$script = $scriptString[$scriptSize];
And then use $script in the form action.