Why am getting Internal Server Error? - php

I am working on a membership signup/join form. The form data is submitted to another page called join.php on pressing submit button I am getting Internal Server Error message. Can anybody help me find the reason/mistake in my coding? Though the data is successfully entered into database.
<?php
// file name : join.php
$con = mysqli_connect("$DBHOST", "$DBUSER", "$DBPASS","$DBNAME");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$ip = $_SERVER['REMOTE_ADDR'];
$name = mysqli_real_escape_string($con,$name);
$email = mysqli_real_escape_string($con,$email);
$phone = mysqli_real_escape_string($con,$phone);
$city = mysqli_real_escape_string($con,$city);
$state = mysqli_real_escape_string($con,$state);
$check = "SELECT COUNT(*) FROM `members` WHERE phone=".$phone."
OR email=".$email." Limit 1";
if (mysqli_query($con,$check)>=1){
echo ("The phone number <strong>".$phone."</strong> or email <strong>
".$email." </strong> address is already registered with us.");
}else{
$query = mysqli_query($con,"INSERT INTO `members`
(`name`,`email`, `phone`, `city`, `state`,`ip`, `regdate`)
VALUES('".$name."','".$email."','".$phone."','".$city."',
'".$state."','".$ip."', NOW('') )")
or die("MYSQL ERROR :".mysqli_error($con));
/* PREPARE MESSAGE FOR EMAIL TO NEW MEMBER */
header("Refresh=07;URL=./index.php");
$headers4 = "<join#mydomain.com>";
$headers = "Reply-to: $headers4\n";
$headers .= "From: $headers4\n";
$headers .= "Errors-to: $headers4\n";
$headers .= "Content-Type: text/html; charset=utf-8\n";
$message = "<br>Dear ".$name." <br><br>";
$message .= "Thanks for joining.<br> Your details are";
$message .= "<br>Name - ".$name." <br>Mobile No. - ".$phone."<br>";
$message .= "Email - ".$email."<br>City, State - ".$city.",".$state."<br>";
$message .= "<br>Regards,<br>Name";
mail("".$email."", "Thanks for Joining", "".$message."", "".$headers."");
echo "<p>Congratulations!<br>IP-".$ip."<br>Your data has been added
into our membership database.<br><strong>Thank you for joining.</strong>";
}
mysqli_close($con);
?>

So many mistakes in it.. Improve your code style to give its quality a boost.
Start by fixing the quotes, very missleading:
mail("".$email."", "Thanks for Joining", "".$message."", "".$headers."");
Should be
mail($email, 'Thanks for Joining', $message, $headers);
$check = "SELECT COUNT(*) FROM `members` WHERE phone=".$phone."
OR email=".$email." Limit 1";
Has missing quotes too, I don't thinkg email and phone are numbers.
$check = "SELECT COUNT(*) FROM `members` WHERE phone='".$phone."'
OR email='".$email."' Limit 1";
There is no header called Refresh, this is kinda Javascript style, but you need HTTP:
header("Refresh=07;URL=./index.php");
Fixed:
header("Location: index.php");
Finally enable error reporting to see what's really wrong.

Related

Sending email via gmail using php code on Go Daddy Webhost

I want to send a mail using php through Gmail. I've seen many websites how to do it but I don't Understand how to do them. I am still stuck at the code I've written at first. Please help me how to connect my website (hosted on GoDaddy) to gmail account, and tell correct path to do that.
I am writing a code for clearer vision. In this php code, I am trying to add data in database and if the code works, the user should get an email from the company
if (isset($_POST['name']) && isset($_POST['mobile']) && isset($_POST['email']) && isset($_POST['practice']) && isset($_POST['date']) && isset($_POST['time']))
{
include "_credentials.php";
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$practice = $_POST['practice'];
$date = $_POST['date'];
$time = $_POST['time'];
$sql = "INSERT INTO <database> (Name, Number, email, Practice, Time, Date) VALUES ('".$name."', ".$mobile.",'".$email."','".$practice."','".$date."','".$time."');";
if ($conn->query($sql) === TRUE) {
$to = $email;
$host = "ssl://smtp.gmail.com";
$subject = "Appointment Confirmation";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: abc#gmail.com' . "\r\n";
$txt = "Hello ".$name.",\n Your Appointment is booked with Doctor at Clinic on ".$date." at ".$time.".";
mail($to,$subject,$message,$headers);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
First of all you need need to check for error response on mail() function using the following snippet
$success = mail('example#example.com', 'My Subject', $message);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
After the error message , you will be able to sort it out

forgot password there was a error message displayed

I have put together a forgot password page that should insert a token to my lost password db table and send the user a email with a link to reset the password but I am not getting the email and just get there was a error message on the forgot password page after clicking the submit button and bit unsure what the issue is. My code is below
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new mysqli("localhost", "username", "password", "databasename");
if(isset($_POST['submit'])){
$email = $_POST['email'];
$stmt = $db->prepare("SELECT * FROM `users` where `customer_email` = ?");
$stmt->bind_param('s', $email);
$stmt->execute();
$res = $stmt->get_result();
if($res->num_rows < 1){
echo "No such email has been found";
} else{
$fetch = $res->fetch_assoc();
$userid = $fetch['user_id'];
$token = bin2hex(openssl_random_pseudo_bytes(45));
$from = "noreply#domain.co.uk";
$url = 'https://www.domain.co.uk/account/passwordreset.php?token='.$token;
if(mail($email, $url, $from)){
//if(mail($to,$subject,$message,$url,$headers)){
$stmt = $db->prepare("INSERT INTO `lost_password`(user_id, token) values(?,?)");
$stmt->bind_param('is', $userid, $token);
$stmt->execute();
$to = $email;
$subject = "New Password Instructions";
$message = " Please visit $url to reset your password";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <noreply#domain.co.uk>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($stmt->affected_rows == 1){
echo "We have emailed you instructions on how to reset your password";
} else {
echo "there was an error";
}
}
}
}
?>
If you are working on local server then the error will occure. Have you cheched it on live server? If not please check it on live server.
OR
Instead of using mail() function use PHPMailer

how to send email automatically when a value is updated in mysql database

i design an application and build with phonegap all is working but when a value in my mysql database that is attached the app is updated i want an email to be sent automatically to the user. When the counter completes counting the value of "status" in runnindAds table is updated and i want to an email to be sent each time that value is updated, below is the script i wrote for the email to be sent but i don't know how to automate it, please help with what i can should or i can
<?
include('../db_connect.php');
require_once "PHPMailer-master/class.phpmailer.php";
$id=$_GET["rid"];
$status = 3;
mysql_query("update runningAds set status = 3 where id = '$id'");
// get username
$qaz = mysql_query("select * from runningAds where id = $id") or die (mysql_error());
$wsx = mysql_fetch_array($qaz);
$username = $wsx["users"];
$stopTime = $wsx['stopTime'];
sendConfirmationEmail($username, $stopTime);
header("location: ../view_running_ads.php");
function sendConfirmationEmail($username, $stopTime)
{
$result2 = mysql_query("select * from dapUsers where userName='$username'");
$row = mysql_fetch_array($result2);
$to = $row['email'];
//$from = "admin#addirectng.com";
$subject = 'Advert Runtime Alert';
$message = "Dear $username,<br \>
Your display picture advert runtime has ended at $stopTime. <br \>
Advert Direct Team";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <admin#addirectng.com>' . "\r\n";
mail($to,$subject,$message,$headers);
}
?>
Try this:
<?php
include('../db_connect.php');
require_once "PHPMailer-master/class.phpmailer.php";
$id=$_GET["rid"];
$status = 3;
// get username
$qaz = mysql_query("select * from runningAds where id = $id") or die (mysql_error());
$wsx = mysql_fetch_array($qaz);
$username = $wsx["users"];
$stopTime = $wsx['stopTime'];
if (mysql_query("update runningAds set status = 3 where id = '$id'"))
{
sendConfirmationEmail($username, $stopTime);
}
header("location: ../view_running_ads.php");
function sendConfirmationEmail($username, $stopTime)
{
$result2 = mysql_query("select * from dapUsers where userName='$username'");
$row = mysql_fetch_array($result2);
$to = $row['email'];
//$from = "admin#addirectng.com";
$subject = 'Advert Runtime Alert';
$message = "Dear $username,<br \>
Your display picture advert runtime has ended at $stopTime. <br \>
Advert Direct Team";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <admin#addirectng.com>' . "\r\n";
mail($to,$subject,$message,$headers);
}
?>
Tell me if it works or not.

PHP Sending Duplicate Emails

After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>
In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.
You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.

php email approval

I have a small web app where people can send a message via email to a group. Because of spam I will have to make an approval procedure.
The messages are being sent via PHP. How am I doing so I have to accept the message before its send to an email that forward it to the group?
My PHP:
<?php
$errors = '';
$myemail = 'whatever#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n FEJL: Alle felter skal udfyldes";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$email_subject = "Form request";
$times = $_POST["timeslots"];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n FEJL: Ugyldig email adresse";
}
$strTimes = implode($times);
if( empty($errors))
{
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thx.html');
}
?>
ok so this is a fair size project in itself if you want to use a data queue.
ASSUMING you want to use a database you will need to know the basics of setting one up, how to use and setup tables etc. (as long as you have access to a database anyway).
Here is some connection code:
change peter and abc123 to whatever username and password your database has associated with it.
$con = mysql_connect("localhost","peter","abc123");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db");
I will give you some sample code for inserting rows to the database, selecting rows from the database, acting on that info and deleting rows from the database.
Ok lets start with the mail submission:
This section near the bottom of your code is the data we need to manipulate
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
So assuming you have a mysql database connection with a table setup in the database this is how you would insert it: (please note this is a basic insert query)
$query = "INSERT INTO queuemails (to, subject, body, headers) VALUES ('" . $to . "', '" . $email_subject . "', '" . $email_body . "', '" . $headers . "')";
mysql_query($query);
Ok so those 2 lines would be added BELOW your set variables.
You then need to provide a method of approval page.
This can be done on the same page but you have to seperate out your mail() function from the rest of the script.
Ok so here is a select script now to be able to VIEW your queue for approval. Please note that I have added an auto increment column to the table that stored your queued mail. This is to be able to select a line in the table more easily as is generates a unique number for that line of data. This column is called mid (standing for "mail identity").
ok so here is the selection script:
$query = "SELECT * FROM queuemail"; //this is only good if you know you wont get millions else you need to limit it
//limited select:
//$query = "SELECT * FROM queuemail LIMIT 0,10"; //selects the first 10
while($m = mysql_fetch_assoc(mysql_query($query))){
echo $m['to'] . " ";
echo $m['subject'] . " ";
echo '<a href=approve.php?mid=' . $m['mid'] . '>Approve</a><br>';
}
Then finally to clean up afterwards, after you have used your mail() function you should delete the line from the database that you have sent.
Here is the code (including the $_GET variable, this is an unsafe method but is sufficient to display the code you would be using).
mail(); //data can be added either from a new select statement or from POSTING it with the form
$query = "DELETE FROM mailqueue WHERE mid='" . $_GET['mid'] . "'";
mysql_query($query);
echo 'Your mail has been sent and deleted from the queue';
Hope this helps.
You can add timestamps to another column in the database automatically so that you can verify spam posting with something like:
if($_SERVER['REQUEST_TIME'] > ($oldtimeofpost + 100)){ //time is in seconds
//do something
}
else{
//warning
}

Categories