I have a form submission page that POSTS the fields to a confirmation page that sends an email using PHP but I keep getting blank emails when the page is ran as a stand alone page instead of from the form submission page. The form has 'required', but I want to add a statement to the PHP that stops the process if the $email variable is blank/null.
<?php
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = "Thank you for registering you team";
$message = "<html>...
In addition to stopping the process if the $email variable is blank/null, I also want to redirect the user to our home page.
You should be able to do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = 'Thank you for registering you team';
$message = '<html>...';
} else {
header('Location: https://example.com');
}
Simplest way:
...
// variables end
if( ! (!isset($email) || trim($email) === '') ){
header("Location: homepage.php");
exit();
}
// email start
...
Note the exit() statement after the redirection: without exit() or die() the PHP script could be continue the execution resulting in possible unexpected behaviour.
Related
I'm having some problems with this PHP script for managing a db of an elusive travel agency
Basically what I would like to do is:
check that the form fields have all been filled in, if so
then, I check the number of travel packages available for that country...
if there are any then the booking request has been completed successfully and I will reduce the packages available for that country by 1, if there are none then a popup will appear that will warn of unavailability for that country.
The problem is that when I complete the form by putting a country X as a destination, even if there are packages available for that country X, the popup appears that warns me of the unavailability for that country.
<?php
$msg1 = 'You have not filled in all fields!' ;
$msg2 = 'Booking request made successfully' ;
$msg3 = 'There are no packages available for this destination';
$connection = mysqli_connect('localhost','root','','book_db');
if(isset($_POST['send'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$location = $_POST['location'];
$guests = $_POST['guests'];
$arrivals = $_POST['arrivals'];
$leaving = $_POST['leaving'];
$request1 = "SELECT n_package FROM destination
WHERE country= '$location' ";
$res = mysqli_query($connection, $request1);
if(empty($name) || empty($email) || empty($phone)
|| empty($address) || empty($location) || empty($guests)
|| empty($arrivals) || empty($leaving))
{
echo '<script>
alert("'.$msg1.'");
</script>';
} else if($res>0) {
//scala di 1
$request2 = "UPDATE destination
SET n_package=n_package-1
WHERE country= '$location' ";
mysqli_query($connection, $request2);
echo '<script>
alert("'.$msg2.'");
</script>';
}else if($res<1){
echo '<script>
alert("'.$msg3.'");
</script>';
}
} else {
echo 'something went wrong try again';
}
?>
You need to fetch the rows from the resultset created by a query.
You need to watch out for SQL Injection Attack
<?php
$msg1 = 'You have not filled in all fields!' ;
$msg2 = 'Booking request made successfully' ;
$msg3 = 'There are no packages available for this destination';
$connection = mysqli_connect('localhost','root','','book_db');
if(isset($_POST['send'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$location = $_POST['location'];
$guests = $_POST['guests'];
$arrivals = $_POST['arrivals'];
$leaving = $_POST['leaving'];
$request1 = "SELECT n_package FROM destination WHERE country= ?";
$stmt = $connection->prepare($request1);
$stmt->bind_param("s", $_POST['location']);
$stmt->execute($connection, $request1);
$res = $stmt->get_result();
$row = $res->fetch_assoc();
Now $row['n_package'] is the number of packages available. Use that in your number checks.
In your tests though, you echo a little piece of javascript but that is ALL you echo, so that will be the complete content of the page. No <html> no <head> no <body> basically not a valid piece of HTML for the browser to build a page from.
I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....
This is the first time I have been dumbfounded on what to search for to find my answer. I generally don't ever create a post because there are umpteen thousand posts on the internet with my answer; certainly this is no exception. My problem with finding the answer is, I'm not quite sure what to even search for.
The below code works. That's not the problem. My problem is, what if I wanted to run this one thousand times. Surely I do not need to write this entire expression so many times to get the desired affect do I?
I have a feeling it has to do with an array, but I'm still at a point where I understand arrays one day and the next they are greek.
But anyway, long post for a simple question. Hopefully someone can help me out with this.
This is PHP.
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
This is the entire page:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
And the class:
<?php
session_start();
require("../classes/uservalidation.php");
$firstname = $lastname = $email = $password1 = $password2 = "";
if($_SERVER['REQUEST_METHOD'] == "POST") {
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$email = $_POST['email'];
$password1 = $_POST['password'];
$password2 = $_POST['verify'];
}
//create validation object
$validate = new userValidation;
//execite stripExcess method $vaidate
$firstname = $validate->stripExcess($firstname);
$lastname = $validate->stripExcess($lastname);
$email = $validate->stripExcess($email);
$password1 = $validate->stripExcess($password1);
$password2 = $validate->stripExcess($password2);
//
$returnValidate = $validate->register($firstname, $lastname, $email, $password1, $password2);
//check if the variable is an array -- (case when returnValidate has an error)
if (is_array($returnValidate)) {
$url = $returnValidate[0];
$errorMessage = $returnValidate[1];
//echo $url;
//exit();
}else{
$url = $returnValidate;
//echo $url;
//exit();
}
//Set the form values to SESSION vairbale to pass around
$_SESSION['fname'] = $firstname;
$_SESSION['lname'] = $lastname;
$_SESSION['email'] = $email;
$_SESSION['password1'] = $password1;
$_SESSION['password2'] = $password2;
//redirect to the correct page based on validate results
header("Location: " . $url, true, 303);
?>
I don't know what are you want, but maybe:
$values = array("firstname", "lastname", "email", "password1", "password2");
foreach($values AS $value) {
$$value = $validate->stripExcess($$value);
}
Yes. If you have quite a few variables you can use an array of variables. Basically, the array is a very common structure in PHP. When you get values from $_GET and $_POST you also work with arrays. Nested Arrays and Arrays of objects, Nested arrays of objects all of these are widely used in php.
Try to var_dump $_GET and $_POST (when you send some values to the server) and analyze how the are formed when they have values.
I am using registration module in which i first collect data from user and store it to a temporary database('tmp_users') and send a link via email,on clicking link via email user can activate their account(i am moving data to permanent table 'users').i have following files
studentregistration.php(A UI for registration)
processlogin.js (processing form data via jquery)
register.php (script for moving user data to 'tmp_users' and sending them link)
confirm.php(making user permanent,moving 'tmp_users' data to 'users')
in register.php i am seting two session variable $_session['email'],$_session['confirmation'] and i am generating one random unique num via
uniqid(rand()) and sending this in email as passkey which i again use in confirm.php and getting it from url by $_GET['passkey'] if passkey matched than confirming registration otherwise not.
now the problem is that this script executed successfully on my local machine but does not executed on my server.
thank in advance.......
Code for confirm.php
<?php
error_reporting(0);
require 'db/connect.php';
if(session_start())
{
$confirmation = $_GET['passkey'];
$result=$db->query("select * from tmp_users where passkey = '$confirmation'");
$count = $result->num_rows;
if($count == 1)
{
$rows = $result->fetch_all(MYSQLI_ASSOC);
/*print_r($rows);*/
foreach($rows as $row)
{
$eno = $row['eno'];
$fname = $row['fname'];
$lname = $row['lname'];
$sem = $row['sem'];
$branch = $row['branch'];
$mail = $row['mail'];
$contact = $row['contact'];
$password =$row['password'];
}
//making user permenant
$insert=$db->prepare("insert into users(eno,fname,lname,sem,branch,mail,contact,password) values(?,?,?,?,?,?,?,?)");
$insert->bind_param('ississss',$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
$insert->execute();
$rowsaffected = $insert->affected_rows;
if($rowsaffected==1){
if($delete=$db->query("delete from tmp_users where passkey='$confirmation'"))
echo"<script>alert('Activated!!! Login Now');document.location='studentlogin.php';</script>";
else
echo "error";
}else{
echo"<script>alert('Error activating account');document.location='index.php';</script>";
}
}else{
echo"<script>alert('You are not registered');document.location='studentregistration.php';</script>";
}
}else
{
header('location:index.php');
}
?>
code for register.php
<?php
session_start();
require '../db/connect.php';
require '../phpmailer/class.phpmailer.php';
require '../mailfunction.php';
$confirmation = md5(uniqid(rand()));
$eno = $_POST['eno'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sem = $_POST['sem'];
$branch= $_POST['branch'];
$mail = $_POST['mail'];
$contact = $_POST['contact'];
$pw = $_POST['pw'];
$password = md5($pw);
$query = ("insert into tmp_users(passkey,eno,fname,lname,sem,branch,mail,contact,password) values (?,?,?,?,?,?,?,?,?);");
$result = $db->prepare($query);
$result->bind_param('sississss',$confirmation,$eno,$fname,$lname,$sem,$branch,$mail,$contact,$password);
if($result->execute()){
$_SESSION['mail']= $mail;
$_SESSION['confirmation'] = $confirmation;
$ToEmail = $mail;
$subject = "Activate your account";
$header = 'FROM:VGECG-LIBRARY <noreply#vgecg.ac.in>';
$MessageHTML = "Click link below to activate your account \r\n";
$MessageHTML.="<a href='localhost/projectlibrary/confirm.php?passkey=$confirmation'>Click here</a>";
$MessageTEXT='';
if(SendMail($ToEmail, $MessageHTML, $MessageTEXT))
{
print "1";
}
else {
print "";
}
}
?>
I need to change the value of the variable $destination to help validate a form. If none of the fields within the form, the page refreshes with the error message displayed, which works. If the fields are all filled in, the the $destination value should change and the message 'it works!' is printed. However, if all fields are filled in and the user submits the form, the message 'it works!' is printed, but the $destination's value is still set to 'this-page'. What am I missing here?
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!$fname OR !$lname OR !$email OR !$phone) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Hope this is academic. There are better ways to approach this. But here:
$destination = '';
$fname = isset($_POST['fname']) ? $_POST['fname'] : null ;
$lname = isset($_POST['lname']) ? $_POST['lname'] : null ;
$phone = isset($_POST['phone']) ? $_POST['phone'] : null ;
$email = isset($_POST['email']) ? $_POST['email'] : null ;
if (empty($fname) || empty($lname) || empty($phone) || empty($email)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
} else {
print 'It works!';
$destination = 'results-page';
}
Someday take a look at some PHP frameworks and how they handle form validation. for example: http://framework.zend.com/manual/1.12/en/zend.form.elements.html Might give you some insight.
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!empty($fname) || !empty($lname) || !empty($email) OR !empty($phone)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}
Seems like the problems isn't related to the validation part here. You are getting both the print from the else statement and the $destination variable from the if statement? That should be logically impossible. Are you sure you don't have any syntax errors etc. in your code? Is that the exact code you have in your program?