I am an amateur at php and I made this simply submit form (see bellow). Now, when I click submit, it acts as if it went through it displays that the messages was received but I don't get any msg in my actual e-mail. The 3 form inputs names are: name, email, msg. Am I doing something wrong?
<?php
$message="$msg";
$mail_from="$email";
$header="from: $name <$mail_from>";
$to ='anomanomanom#gmail.com';
$send_contact=mail($to,$message,$header);
if($send_contact){
echo "I've received your message and I will get back to you shortly! You will be redirected in less than 5 seconds!";
header("refresh:5;url=http://google.com");
}
else {
echo "ERROR";
}
?>
You need to access the submitted data either via $_GET or, more likely, via $_POST, e.g., $_POST['msg'].
Whatever you are using to learn PHP is heavily outdated, as it still depends on something called autoglobals. These were deprecated almost 5 years ago. You can find more info here.
Related
I've looked at so many stack overflow questions to find my solution, but none of the questions I try are what I am looking for (so if you know of one that fits my question, please tell me). What I have is a php page that processes a form. It looks like this:
<?php
$var1 = htmlentities($_POST['var1']);
$var2 = htmlentities($_POST['var2']);
$conn = mysqli_connect('localhost','user','pass','db');
$query = "INSERT INTO table (var1,var2) VALUES ('$var2','$var2)";
$doQuery = mysqli_query($conn,$query);
if($doQuery) {
// this is where script should go (i think) to send the variables to the email page
header("Location: /path/to/next/page"); // this just sends the user to the next page. NOT PART OF EMAIL PAGE
}
else {
header("Location: /path/to/back/page");
}
mysqli_close($conn);
?>
so its a basic form handler that sends you to the next page if all goes well.
I have another page that is sends an email notification to someone when they successfully go through the first page. It also processes all of the other email notification worthy forms as well. that's the reason I can't just take the script and put it into the top page.
So, what I am trying to do is figure out a way to send the $var1 and $var2 to the email file without completely redirecting the user. I don't need a response back from the email file.
I hope that made sense.
thanks in advance
Quite simple, really:
// your code above
require 'send-email.php';
And your send-email.php would reference $var1 and $var2.
I am a PHP newb so please bear with me for this rather simplistic question.
I have a PHP form setup like so >>
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$comments = $_POST['comments'];
if($comments)
$error = "There was an error, please give us a call at ### ###-####.";
else{
if($name=="Name" || $email=="Email" || $message=="Message"){
$error = "All fields are required, please fill them out and try again.";
}else
$header = "From: $name <$email>";
$message = "Name: $name\n\nEmail: $email\n\nMessage: $message";
if(mail("email#domain.com", 'Form Submission', $message, $header))
$success = "Thanks for sending us your message, we'll get back to you shortly.";
else
$error = "There was an error, please give us a call at ### ###-####.";
}
if($error)
echo '<div class="msg error">'.$error.'</div>';
elseif($success)
echo '<div class="msg success">'.$success.'</div>';
}
?>
The basic idea is that the form has descriptive text pre-filled in each field but when you click on them they are cleared via Javascript. I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){" bit. However while that message is working the form is still submitting. Why is this. Also please note that the "comments" field is in fact a honeypot. Thanks!
Because php is server-side. You need to look into javascript validation for what you want. To validate with php you HAVE to submit the form.
One tutorial but I recommend Jquery validation
"I want to prevent people from pressing send on the form without filling it out, hence the "if($name=="Name" || $email=="Email" || $message=="Message"){"
All you need to do is disable the submit button client side until the proper validation is met, then also validate server side. As #Iznogood said, that's why your gettin your error
Like lznogood said, PHP validates the form on the server, so you need to send the information to the server before PHP can process it.
If you want the form to be checked on the user side before sending it to the server you should use JavaScript to do that (jQuery is a great tool to use), and after checking it on the user side you can decide whether to send the form to the server or not.
Though this isn't an answer to your question, you might be interest in the new html5 feature placeholder. Read about it here. You can check to see which browsers it works in here (stupid internet explorer!). 5 years ago, I would put those "hints" as the value, which was a pain to validate. placeholder makes it sooooooo much easier. Your tag would look like:
<input type="text" name="email" placeholder="Enter Your Email Here" value="">
Note that value is empty. You can omit the value attribute, I left it in to show it's not needed here.
As far as an answer to your original question, everybody else is correct, javascript is the way to go.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I'm having some difficulty with my php coding.
I have 3 files, add.php, lib.php, and view.php
I created a simple form, and when the user clicks submit, it should direct them to the view.php where it will display the database. Now I'm having a couple issues I can't seem to resolve.
when the user clicks submit and the fields are blank or there is an error no entry should be made into the view page (or database)...however when I click submit a blank entry is made into the database. ALSO if i click "enter product" from the top menu bar anytime I click it, it causes a blank entry into the database. I can't figure out why that's happening.
My next issue is with the header('Location')
and my browser says:
"Warning: Cannot modify header information - headers already sent by (output started at lib.php:13) in add.php on line 16"
However if I click submit on my form it goes away.
Here is the code for the pages:
I truly apologize if the code is really messy.
Any help / advice / solution is greatly appreciated thank you.
And yes this was an assignment---it was due last week but since I couldn't finish it, it's not worth any marks anymore.
Your if statement if (empty($_POST)){ will always fail and the else will run, thus the empty db entries.
$_POST will always have something in it, even for empty text inputs. Each key will be set to an empty string.
To test for whether you should save data or not you'll need to validate all required form fields. Your code will probably look something like this. This is by no means complete or secure, but it'll point you in the right direction.
<?php
// store validation rules for required fields
$requiredFields = array(...);
// Store all validation errors here.
$errors = array();
foreach($requiredFields as $key=>$rule) {
if(empty($_POST[$key])) {
$errors[$key] = true;
}
else {
// you can perform more validation work on the value here.
}
}
if(count($errors) > 0) {
// form submit failure.
}
else {
// form submit success, save to db
}
You are sending output before setting the header, thus the specified headers are not sent.
Hello guys i am newbie to this stuff so i'll try to explain my problem.I am building application that retrieve data after login to php script that looks like this:
https://zamger.etf.unsa.ba/getrssid.php
(see the page source for php scirpt definition)
and definition(source) here:
Korisničko ime (UID):
Šifra:
After i login it shows me data that i must collect like this:
RSSID: 1321B312 (this is only data that it shows and nothing else)
I must do this with httpwebrequest but don't know how i tried to do it with POST(data) but it always give me the defnition of php script as response.But i need response to be like "RSSID: 1321B312" not as script definition mentioned above...please heeelp ASAP....
Define a form action to begin. So if the same page, getrssid.php, will be processing the form, use:
<form action="getrssid.php" method="POST">
After that, you must code getrssid.php to accept the incoming data via POST. POST data is stored in the PHP variables $_POST['inputname']. So if you have the input name as "login", the value entered will be stored in $_POST['login']. Same thing applies for the password.
So, here's a sample of what a basic POST data handling script should look like. Note that this script does not verify the login credentials, sanitize the inputs, or anything of the sort. It is just to show you how to handle POST DATA.
<?php
if (isset($_POST['login']) && isset($_POST['pass'])){
// Form is submitted.
echo 'RSSID: 1321B312';
} else {
// Form is not submitted.
// Display Form.
echo 'Form HTML here';
}
?>
If you are really server conscious, you should put the if ... else statement in the opposite order so the most likely outcome (form not submitted) is evaluated first.
Merry Christmas!
I'm developing a form validation class in PHP. When form validation fails, I can easily redirect again to the form's html page but without error information. I would like to redirect to the form's page with the specific errors about which fields failed and why.
How should I do this? Should I send information back via GET or POST? and in which format? Would really to see some code to see how people tackled this problem.
Thanks!
You could use the header() function. So just check the fields that are posted:
if(!$form->valid()){
$msg = "Form is not valid";
} else {
//Don't know if you want this
$msg = "Form is valid";
}
header("Location: [page where you came from]?msg=" . urlencode($msg));
Then in the page where you're redirecting to use
if(isset($_GET['msg]))
echo urldecode($_GET['msg']);
to echo the message. If you are using other get variables in the location of the header function, of course, use &msg=" . urlencode($msg). (You may also want to return the values that the user submitted, so the user doesn't have to fill out the entire form again if he makes 1 mistake.
I agree with user187291's suggestion of using $_SESSION because:
It doesn't hijack the URI like using $_GET (you would never want a static link to a status message). Users could press "back" to the page with your form and still see a status message because the URI says so.
Print and unset it in the same run, you won't be able to use it more than once (which is what you want?!)
If you're going with AJAX, $_GET is more widely used for retreiving values, which you are doing from the validation controller.
there are number of approaches
pass errors in GET when redirecting back like you said
use sessions to store error info, on the form page check Session for errors
do not redirect after failure, just output form again along with error messages
ajax submits
which one to use depends on the application. For most apps sessions method is most appropriate.
Something like this:
// Pseudo Code
function isValid($parm) {
$return = false;
if(preg_match(/^[a-zA-Z]+$/, $parm) {
$return = true;
}
return $return;
}
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$validFirstName = isValid($firstname);
$validLastName = isValid($lastname);
if($validFirstName == true && $validLastName == true) {
echo "It's all good";
// Do what you need to like, Submit
} else {
echo "Please retry";
// Display error message
}
I use a class to interface with $_POST, similar to the following:
// create the object
$post = new PostData();
// register your requirements... write whatever methods you need
// for each call,read $_POST, check criteria, and mark the field
// as good or bad...
$post->required ('LastName');
$post->required ('FirstName');
$post->numeric ('Age');
$post->optional ('MiddleInitial');
$post->regExp ('/\d{3}/','AreaCode');
$post->email ('Email');
// check the status
if (!$post->isValid ())
{
$_SESSION['FailedPostData'] = $post;
header ('Location: page.php');
}
// normal form processing
Then, on page.php, you can see if FailedPostData is in the session, read it to find the info entered last time, as well as which fields that failed. I use a template engine with macros that let me easily re-populate the form inputs and mark the failures. Otherwise you might end up with lots of code for a simple form...
You'll also need a mechanism to be sure that stale FailedPostData doesn't hang around in the session and confuse things.
I am doing it this way. Beginner in php so not sure if this is the best way to do:
HTML Form Page:
<form id="abc" method="post" action="validate.php">
PHP Page
..validation conditions..call a function if things do not match
function display_error($error) {
echo "<html><body><link href='style.css' rel='stylesheet' type='text/css'><br><center><h2>";
echo "$error";
echo "</h2></center><br><br>";
echo "<center><input type='button' value='Go Back' onClick='history.go(-1)' style='width:100px; height:28px; font-size:16px'></center>";
echo "</body></html>";
}
Clicking on the back button takes you back to the html page with the data intact.