Phpmailer Script Not Executed - javascript

I am writing this code where there is 2 user type : Normal User & Admin User.
Normal User Submit Data To Admin User, Both Admin (More Then 1 Admins In database) & Normal User Should Receive Email Regarding The Submission Of Data.
The submission and retrieving of the data is working fine. But in the Email Part, I reuse the code from my registration part that works for the submission code, Result is, It does not read the $mail.
Both of my registration and submission files are in the same folder. (Path should be working fine).
The logic also seems fine. Maybe i forget or miss something ? Could use a help to check my code.
...//
if ($conn->query($sqlDeleteSelected) === TRUE)
{
require_once "../assets/inc/phpmailer/PHPMailerAutoload.php";
$mail = new PHPMailer(true);
try
{
$sqleMail = "SELECT * FROM users_details WHERE users_Admin_University_Name = '$basket_UniCourse_UniName_1'";
$resultSqleMail = $conn->query($sqleMail);
while($dataResultSqlMail=mysqli_fetch_assoc($resultSqleMail))
{
$mail->AddAddress($dataResultSqlMail['users_Email']);
}
$mail->From = "myemail#gmail.com";
$mail->FromName = "MyName";
$mail->isHTML(true);
$mail->Subject = 'Application Registered';
$mail->Body = 'Congratulations!';
$mail->Send();
if($mail->Send())
{
// echo "Message has been sent successfully";
?>
<script type="text/javascript">
alert("sucesss");
</script>
<?php
}
else
{
?>
<script type="text/javascript">
alert($mail->ErrorInfo);
</script>
<?php
}
}
catch (phpmailerException $e)
{
echo $e->errorMessage();
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
//..
Thank You So Much.

I'm not sure if I understand you 100% correctly but I assume that the java script "success" or the alert is not executed? This is because your if condition is not used properly. Actually you are trying to send the email twice:
$mail->Send();
if($mail->Send())
{...
A better way to see if the email was send successfuly is using a try&catch:
try {
$mail->send();
// print success message
} catch (Exception $e) {
// print error message
}

Related

ajax, jquery contact form with reCAPTCHA v2 - 500 Internal Server Error

I have a jquery/ajax contact form and tried to add the Google reCAPTCHA v2, but it isn't working. The form worked before I included the reCAPTCHA. The reCAPTCHA shows up (although it takes forever to load), and I can verify that I'm not a robot (which takes forever as well), but when I click on my submit button, the spot where I display my status messages shows this, including the code, as text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>500 Internal Server Error</title> </head><body> <h1>Internal Server Error</h1> <p>The server encountered an internal error or misconfiguration and was unable to complete your request.</p> <p>Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.</p> <p>More information about this error may be available in the server error log.</p> </body></html>
I can't figure out what's going wrong. I followed Google's instructions and included this just before my tag:
<script src='https://www.google.com/recaptcha/api.js'></script>
and integrated my form like this:
<div class="g-recaptcha" data-sitekey="6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7"></div>
I tried many different ways to integrate it in my mailer.php file without success, and I couldn't find many tutorials that address v2 specifically (not sure if it even matters). My most recent version of the mailer.php is based on an example I found on Google's recaptcha Github:
<?php
require_once __DIR__ . 'inc/autoload.php';
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$siteKey = '6LeehAsUAAAAAILDfzizJ23GHH7yPGxWBFP_3tE7';
$secret = 'I-removed-this-for-now';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
// If the Google Recaptcha check was successful
if ($resp->isSuccess()){
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
else {
http_response_code(500);
echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
This is the app.js that goes with my contact form (I haven't changed this at all when trying to include the reCAPTCHA):
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, and your message could not be sent.');
}
});
});
});
The autoload.php comes directly from the Google Github, and I didn't make any changes:
<?php
/* An autoloader for ReCaptcha\Foo classes. This should be required()
* by the user before attempting to instantiate any of the ReCaptcha
* classes.
*/
spl_autoload_register(function ($class) {
if (substr($class, 0, 10) !== 'ReCaptcha\\') {
/* If the class does not lie under the "ReCaptcha" namespace,
* then we can exit immediately.
*/
return;
}
/* All of the classes have names like "ReCaptcha\Foo", so we need
* to replace the backslashes with frontslashes if we want the
* name to map directly to a location in the filesystem.
*/
$class = str_replace('\\', '/', $class);
/* First, check under the current directory. It is important that
* we look here first, so that we don't waste time searching for
* test classes in the common case.
*/
$path = dirname(__FILE__).'/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
/* If we didn't find what we're looking for already, maybe it's
* a test class?
*/
$path = dirname(__FILE__).'/../tests/'.$class.'.php';
if (is_readable($path)) {
require_once $path;
}
});
I would really appreciate your help!
Okay, I fixed it. One reason it wasn't working was that I had to enable allow_url_fopen in php.ini.
Then I completely changed the code to get rid of that autoload.php and the class error. I didn't change app.js. The working mailer.php now looks like this:
<?php
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MYKEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
$recipient = "I-removed-this#for-now.com";
$subject = "New message from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
$email_headers = "From: $name <$email>";
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
}
else {
http_response_code(500);
echo "Oops! Something went wrong, and we couldn't send your message. Check your email address.";
}
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again.";
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

showing messages using javascript after redirecting to a php page

I'm working on a contact page. It uses Slim 3 framework to redirect. Everything is fine, but I want to add some jQuery code to inform the user whether the email is sent or not.
this is my php code:
<?php
require 'vendor/autoload.php';
$app = new Slim\App();
//... slim views codes
$app->get('/', function ($req, $res, $args) {
return $this->view->render($res, "about.twig");
})->setName('home');
$app->get('/contact', function ($req, $res, $args) {
return $this->view->render($res, "contact.twig");
})->setName('contact');
$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();
$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];
if(!empty($name) && !empty($email) && !empty($msg) ){
$cleanName = filter_var($name,FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg,FILTER_SANITIZE_STRING);
}else {
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
// javascript: please fill the fields.
}
//sending mail
]);
$result=$mailer->send($message);
if ($result > 0) {
// javascript: your email has been sent
$path = $this->get('router')->pathFor('home');
return $response->withRedirect($path);
} else {
// javascript: error sending mail
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
}
});
$app->run();
As you can see there's basically two page: "contact" and "home".
there's a form in contact page, if form submission is successful and a email is sent, page would be redirected to "home", but if not it would redirect to "contact" again. Now I want to add jQuery code so I can tell the user email has been sent or not.
I've got in my HTML something like this:
<div id="feedback" class="success">
<h3>Success!</h3>
<p>You're email has been sent.</p>
</div>
and in my js file:
$(document).ready(function() {
$(".success").click(function() {
$("#feedback").addClass("dismissed");
});
});
Thanks a lot!
$message = "Your text";
echo "<script type='text/javascript'>alert('$message');</script>";

How to correctly connect reCAPTCHA?

Got contact form like this (JSFiddle).
Registered captcha. How to implement the correct integration on the client and server?
In the form inserted just a div. Submit gonna work like this? How to connect submit and captcha?
It refers to the POST request:
How does it send?
There is PHP:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
$recipient = "mail#mail.com";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
I have integrated the google reCaptcha in our website. Here is our implementation.
Front-end Code:
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallBack&render=explicit" async defer></script>
<script type="text/javascript">
var recaptcha_sponsorship_signup_form;
var recaptchaCallBack = function() {
// Render the recaptcha on the element with ID "recaptcha_sponsorship_signup_form"
recaptcha_sponsorship_signup_form = grecaptcha.render('recaptcha_sponsorship_signup_form', {
'sitekey' : 'your_recaptcha_website_key',
'theme' : 'light'
});
};
</script>
<dt>Prove you’re not a robot</dt>
<dd style="height: 78px;">
<div id="recaptcha_sponsorship_signup_form"></div>
</dd>
Server Side Code:
$fileContent = '';
if (isset($_REQUEST['g-recaptcha-response']) && !empty($_REQUEST['g-recaptcha-response'])) {
$fileContent = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=your_recaptcha_secret_key&response=". $_REQUEST['g-recaptcha-response']);
}
$jsonArray = json_decode($fileContent, true);
if (isset($jsonArray['success']) && $jsonArray['success']==true) {
// process your logic here
} else {
echo "Invalid verification code, please try again!";
}
You can use this library ;
https://github.com/google/recaptcha/blob/master/examples/example-captcha.php
First, register keys for your site at https://www.google.com/recaptcha/admin
When your app receives a form submission containing the g-recaptcha-response field, you can verify it using:
<?php
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp);
if ($resp->isSuccess()) {
// verified!
} else {
$errors = $resp->getErrorCodes();
}
You can see an end-to-end working example in examples/example-captcha.php

Trying to use a class in a php page embedded with javascript

I'm trying to use a class that is already declared.
When the user types in something in the username text box I've used a javascript function to load a php file where it checks wether a username is available. this file is recalled for every keypress.
A connection to my database, which is a class, is already declared on the main page, however, the php file can't actually use the database classes. What can I do?
If I wrote a separate script to connect to the database it works, but I don't want to do that.
Contents of Php File:
$query("SELECT username FROM client WHERE username = :username");
$query_params = array(
':username' => $username
);
$db->DoQuery($query);
$check_num_rows = $db->fetch();
if ($username == NULL)
echo 'Choose a Username';
else if (strlen($username)<=3)
echo 'too short.';
else {
if ($check_num_rows ==0)
echo "Available!";
else if ($check_num_rows >= 1)
echo "Not Available.";
}
?>
body.php
<script type="text/javascript">
$(document).ready(function() {
$('#wowson').load('functions/check_username.php').show();
$('#username_').keyup(function() {
$.get('functions/check_username.php', { username: forms.username.value },
function(result) {
$('#wowson').html(result).show();
});
});
});
</script>
<label>Username:</label><br>
<input id="username_" name="username" required="required" type="text" placeholder="Username"/>
<div id="wowson">
</div>
database class
class database {
public function initiate() {
try
{
$this->database = new PDO("mysql:host='host';dbname='db", 'user, 'pass');
}
catch(PDOException $e)
{
$error = "I'm unable to connect to the database server.";
die("Failed to connect to database: " . $e->getMessage());
}
}
public function DoQuery($query, $query_params) {
try
{
$this->result = $this->database->prepare($query);
if ($query_params != null)
{
$this->result->execute($query_params);
}
else
{
$this->result->execute();
}
}
catch(PDOException $e)
{
die();
}
}
public function fetch() {
return $this->result->fetch();
}
}
When you load your original page, you are creating your object from your database class, right?
Well, when you are using Ajax to query the server about the username, that is a totally new request, and it knows nothing about the previous requests.
As such, just add something like require_once('my/path/database.php'); $db = new database(); to your PHP script which responds to the ajax request.

PHP mysql previous declared function issue

I'll make this as short and sweet as possible.
I have this script called usernameget.php which echos the currently logged in username:
<?php
include 'functions.php';
include 'db_connect.php';
sec_session_start();
$userId = $_SESSION['user_id'];
if(login_check($mysqli) == true) {
$con=mysqli_connect("localhost","myusername","mypass","mysqldb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT members.username FROM members WHERE id= $userId");
while ($row = mysqli_fetch_assoc($result))
{
echo $row['username'];
}
/* free result set */
mysqli_free_result($result);
mysqli_close($con);
} else {
echo 'Null User <br/>';
}
?>
This script uses functions.php (part of a secure login script located here: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL#Create_PHP_Functions ) in order to function. sec_session_start(); is just a custom session_start, but functions.php also makes it possible to get the username via $user_id.
The problem is, when I include usernameget.php in the main page (which also uses functions.php to secure,) it throws errors because it's trying to redeclare sec_session_start();
I can strip usernameget.php of this security but obviously since it banks on functions.php / sec_session_start(); it doesn't work afterwards. I've tried to write a specific USERNAMEGETfunctions.php without the session stuff for usernameget.php to use but I'm not adept enough to get it working, and it feels like an inelegant solution.
So as I understand it: functions.php and sec_session_start(); are used to secure the main page so the includes on the main page can't use functions.php or it will conflict. Would anyone be able to show me how to get this script going without redeclaring/conflicting?
Included below is the entire functions.php
<?php
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
function login($email, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
function checkbrute($user_id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $user_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
function login_check($mysqli) {
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) { // If the user exists
$stmt->bind_result($password); // get variables from result.
$stmt->fetch();
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
?>
Don't use plain include for core function libraries, the kind which tend to get included in ALL your scripts. Use include_once instead, so that PHP will only ever include the file once, and then ignore any further include attempts. This will prevent your function redeclaration errors.
You must use require_once instead include_once because your program not will run without that files...
include_once produce warning when try to include the file and it fails.
require_once produce fatal error when try to include the and it fails.
For core libs, you should use require_once. (http://www.php.net/manual/pt_BR/function.require.php)
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

Categories