Failed to get data fields inserted into database - php

I have the just forms script that generates data fields from form and insert them to the database.
However, when I try to send the data I got message that the data sent, but I actually don't see it in the database.
I have a table inside my database called cantaki and it contains these columns:
contact_email
contact_filename
contact_id
contact_name
message
mysql_table
subject
token
I try to change the contact_email to email and so with the others but the data won't insert.
Here is the actions.php file:
<?php
header("Content-Type: text/html; charset=utf-8");
if (!$_POST) exit;
require dirname(__FILE__)."/validation.php";
require dirname(__FILE__)."/csrf.php";
/************************************************/
/* Your data */
/************************************************/
/* Your email goes here */
$your_email = "mymail#gmail.com";
/* Your name or your company name goes here */
$your_name = "david";
/* Message subject */
$your_subject = "New message";
/* Define your data to access MySQL database */
define("CON_USER", "myDBuser"); // your username
define("CON_SERVER", "localhost"); // your host
define("CON_PASSWORD", "Mypass"); // your password
define("CON_DATABASE", "myDB"); // your database
/* Your database table goes here */
$mysql_table = "cantaki";
/************************************************/
/* Settings */
/************************************************/
/* Select validation for fields */
/* If you want to validate field - true, if you don't - false */
$validate_name = true;
$validate_email = true;
/* Select the action */
/* If you want to do the action - true, if you don't - false */
$send_letter = true;
$upload_file = true;
$duplicate_to_database = true;
/************************************************/
/* Variables */
/************************************************/
/* Error variables */
$error_text = array();
$error_message = '';
/* Last row ID */
/* In case, if data will not be duplicated to a database */
$row_id = "No data in a database";
/* File name */
/* In case, if a file will not be uploaded to a server */
$file_name = "No file for upload";
/* Allowed file types */
$valid_types = array("image/jpg", "image/jpeg", "image/png", "application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
/* POST data */
$name = (isset($_POST["name"])) ? strip_tags(trim($_POST["name"])) : false;
$email = (isset($_POST["email"])) ? strip_tags(trim($_POST["email"])) : false;
$token = (isset($_POST["token_contact"])) ? strip_tags(trim($_POST["token_contact"])) : false;
$name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$email = htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
$token = htmlspecialchars($token, ENT_QUOTES, 'UTF-8');
$name = substr($name, 0, 50);
$email = substr($email, 0, 40);
/************************************************/
/* CSRF protection */
/************************************************/
$new_token = new CSRF('contact');
if (!$new_token->check_token($token)) {
echo '<div class="error-message unit"><i class="fa fa-close"></i>Incorrect token. Please reload this webpage</div>';
exit;
}
/************************************************/
/* Validation */
/************************************************/
/* Name */
if ($validate_name){
$result = validateName($name, 1);
if ($result !== "valid") {
$error_text[] = $result;
}
}
/* Email */
if ($validate_email){
$result = validateEmail($email);
if ($result !== "valid") {
$error_text[] = $result;
}
}
/* If validation error occurs */
if ($error_text) {
foreach ($error_text as $val) {
$error_message .= '<li>' . $val . '</li>';
}
echo '<div class="error-message unit"><i class="fa fa-close"></i>Oops! The following errors occurred:<ul>' . $error_message . '</ul></div>';
exit;
}
/************************************************/
/* Upload file to the server */
/************************************************/
/* Upload file */
if ($upload_file) {
$file_name = uploadFile();
}
/************************************************/
/* Duplicate info to a database */
/************************************************/
if ($duplicate_to_database) {
/* Select type of connection to a database */
/* If you want to use connection - true, if you don't - false */
/* For proper work you have to select only one type of connection */
/* Mysqli connection to DB */
$mysqli_connect = true;
if ($mysqli_connect) {
require dirname(__FILE__)."/mysql.php";
$row_id = queryMysqli($mysql_table, $name, $email);
}
/* PDO connection to DB */
$pdo_connect = false;
if ($pdo_connect) {
require dirname(__FILE__)."/pdo.php";
$row_id = queryPdo($mysql_table, $name, $email);
}
}
/************************************************/
/* Sending email */
/************************************************/
if ($send_letter) {
/* Send email using sendmail function */
/* If you want to use sendmail - true, if you don't - false */
/* If you will use sendmail function - do not forget to set '$smtp' variable to 'false' */
$sendmail = true;
if ($sendmail) {
require dirname(__FILE__)."/phpmailer/PHPMailerAutoload.php";
require dirname(__FILE__)."/message.php";
$mail = new PHPMailer;
$mail->isSendmail();
$mail->IsHTML(true);
$mail->From = $email;
$mail->CharSet = "UTF-8";
$mail->FromName = "J-forms";
$mail->Encoding = "base64";
$mail->ContentType = "text/html";
$mail->addAddress($your_email, $your_name);
$mail->Subject = $your_subject;
$mail->Body = $letter;
$mail->AltBody = "Use an HTML compatible email client";
}
/* Send email using smtp function */
/* If you want to use smtp - true, if you don't - false */
/* If you will use smtp function - do not forget to set '$sendmail' variable to 'false' */
$smtp = false;
if ($smtp) {
require dirname(__FILE__)."/phpmailer/PHPMailerAutoload.php";
require dirname(__FILE__)."/message.php";
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "your-username"; // SMTP username
$mail->Password = "your-password"; // SMTP password
$mail->SMTPSecure = "tls"; // Enable encryption, 'ssl' also accepted
$mail->Port = 465; // SMTP Port number e.g. smtp.gmail.com uses port 465
$mail->IsHTML(true);
$mail->From = $email;
$mail->CharSet = "UTF-8";
$mail->FromName = "J-forms";
$mail->Encoding = "base64";
$mail->Timeout = 200;
$mail->SMTPDebug = 0;
$mail->ContentType = "text/html";
$mail->addAddress($your_email, $your_name);
$mail->Subject = $your_subject;
$mail->Body = $letter;
$mail->AltBody = "Use an HTML compatible email client";
}
/* Multiple email recepients */
/* If you want to add multiple email recepients - true, if you don't - false */
/* Enter email and name of the recipients */
$recipients = false;
if ($recipients) {
$recipients = array("email#domain.com" => "name of recipient",
"email#domain.com" => "name of recipient",
"email#domain.com" => "name of recipient"
);
foreach ($recipients as $email => $name) {
$mail->AddBCC($email, $name);
}
}
/* if error occurs while email sending */
if(!$mail->send()) {
echo '<div class="error-message unit"><i class="fa fa-close"></i>Mailer Error: ' . $mail->ErrorInfo . '</div>';
exit;
}
}
/************************************************/
/* Success message */
/************************************************/
echo '<div class="success-message unit"><i class="fa fa-check"></i>Your message has been sent</div>';
?>
Here is the mysql.php file:
<?php
/* Duplicate information to DB */
function queryMysqli($mysql_table, $contact_name, $contact_email) {
/* Variables */
$error_exists = false;
$error_mysql = "";
/* Connection to DB */
/* Constants, that defined in action.php, are used */
$link = mysqli_connect(CON_SERVER, CON_USER, CON_PASSWORD, CON_DATABASE);
if (mysqli_connect_error()) {
$error_mysql = ("Error connecting to database (" . mysqli_connect_errno() . ") ". mysqli_connect_error());
return $error_mysql;
}
mysqli_set_charset($link, 'utf8');
/* Query to DB */
/* Add data to DB */
$result = mysqli_query($link, "INSERT INTO ".$mysql_table."(`".$mysql_table."_id`,
`".$mysql_table."_name`,
`".$mysql_table."_email`,
VALUES (NULL, '".mysqli_real_escape_string($link, $name)."',
'".mysqli_real_escape_string($link, $email)."')");
/* Get a last row ID to send in message */
$row_id = mysqli_insert_id($link);
/* If error occurs */
if (!$result){
$error_exists = true;
$error_mysql = "Error database query: ".mysqli_error($link);
}
/* Return result */
mysqli_close($link);
return $error_exists ? $error_mysql : $row_id;
}
?>
Can you tell me what I'm doing wrong?

Related

Multiple requests being send unintentionally

I am using a PHP Script written by me with AWS (Amazon Web Service) PHP Script to send emails using SMTP
Everytime I run this script, say I have 3 user's in my database, then the first user get's mail of the first, second and third person. The second user get's mail to second and third person. And the third user get's the mail to the third person only.
I don't know why this is happening, and been pulling my hair for some time. Maybe I am missing some point, that is why adding a question here.
Pre-Requisites:
func1() = Is used to get emails from DB whom I have not send Emails Yet, return's a single value (ID) only
func2() = Is used to get the data of that particular user whose ID was found in func1()
func3() = Is used to mark "Send" to that particular ID whom we send the mail.
<?php
require 'aws-autoloader.php';
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->setFrom('myemail#address.com', 'My Company Name');
$mail->Username = 'Username';
$mail->Password = 'Password';
$mail->Host = 'email-smtp.us-west-2.amazonaws.com';
class Db {
public function dbconnect(){
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
public function func1()
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func1()");
$stmt->execute();
$result=NULL;
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func2($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func2(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
public function func3($id)
{
$conn=$this->dbconnect();
$stmt = $conn->prepare("CALL func3(?)");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$item=NULL;
while ($row = $result->fetch_array(MYSQLI_NUM))
{
$item[] = $row;
}
return $item;
$stmt->close();
$conn->close();
}
}
$count=0;
$obj=new Db;
$ids=$obj->func1();
while(($ids[0][0]!=0)&&($count<1000)){
$ids=$obj->func1();
$rslt=$obj->func2($ids[0][0]);
if($rslt[0][0]!=NULL)
{
$idno=$rslt[0][0];
$companyname=$rslt[0][2];
$email=$rslt[0][16];
$complete=NULL;
do{
$mail->addAddress($email, $companyname);
$mail->Subject = 'My Subject';
$mail->Body = '<p>Hello</p>';
$mail->AltBody = "Hello";
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->isHTML(true);
if(!$mail->send()) {
echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL;
} else {
$complete=$obj->func3($ids[0][0]);
}
}while($complete[0][0]!=3);
}
$count=$count+1;
//if($count%10==0) Trying to give a small break after each 10 emails are send
sleep(1);
}
$count=$count-1;
echo 'Email Send to: '.$count.' Users.<br>';
?>
After the function is called, I receive emails as described at the start. And all the users are marked "Send"
Any Idea what I may be doing wrong to get result like that.
Your code is using the same PHPMailer object for each email, and it is adding addresses using $mail->addAddress() without resetting the list of email addresses between emails hence the list of recipients is growing each time.
You can call $mail->clearAllRecipients() for each new email or you could create a new PHPMailer object for each email. Note that if you choose the former approach then you should check to see if there are any other things that also need to be reset from one email to the next.

Send a notification after uploading multiple files with Dropzone JS

I have been working on a project where user uploads image on other users profile page. I have been successful in uploading and sending emails also but it sends multiple emails if there are multiple files in a single upload.
$sendmail = true;
if(!empty($_FILES)){
$team_id = $_GET['param1'];
$user_id = $_GET['param2'];
$id = $_GET['param3'];
$sql = "SELECT * FROM team where team_id = '$team_id'" ;
$sql_result = mysqli_query($conn,$sql) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysqli_fetch_assoc($sql_result)){
$abcd = $row;
}
$targetDir = "../user_images/";
$fileName = $_FILES['file']['name'];
$fileNamex = substr($fileName, -3);
$fileName = rand(1000,100000).md5($fileName).'_'.$fileName;
$targetFile = $targetDir.$fileName;
if( move_uploaded_file( $_FILES['file']['tmp_name'] , $targetFile ) ){
mysqli_query($conn, "INSERT INTO gallery (team_id , user_id , id , userPic, token) VALUES('$team_id','$user_id','$id','$fileName','0')") or die(mysqli_error($conn));
if($sendmail === true){
$htmlContent = file_get_contents ("../email_template_header.php");
$registerURL = $siteURL.'/register/';
if($abcd['claimed'] == '1'){
$htmlContent .= "New image(s) has been uploaded to your business. Please <a href='$registerURL'>login</a> and approve them";
}
else{
$htmlContent .= "New image(s) has been uploaded to your business. Please <a href='$registerURL'>register</a> to claim your business";
}
$htmlContent .= file_get_contents ("../email_template_footer.php");
$to = $abcd['b_email'];
require '../PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->SMTPSecure = 'tls';
$mail->Port = 25;
$mail->setFrom('mail#abc.com', 'ABC');
$mail->addAddress($to);
$mail->isHTML(true);
$mail->Subject = 'New Image Uploaded';
$mail->Body = $htmlContent;
$mail->send();
$mail->clearAddresses();
$sendmail = false;
}
}
}
This doesn't work as the complete code is running for every file, there is also no loop in the default examples on http://www.dropzonejs.com/ so that I could've checked with help of a index flag whether a file has been uploaded or not. Any help is appreciated.
Thanks
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
doSomething();
}
});
}
};

retrive the emails from my own server email address like manoj#manoj.com

Is it possible to fetch the emails from my own domain mails ? i want to fetch the inbox please help for this , I am using IMAP right now but it is giving me the ssl errors like
Certificate failure for MAIL.enlighten-energy.net: Server name does not match certificate: /OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=*.justhost.com
function fetch_gmail_inbox()
{
$res=array();
/* connect to gmail */
$hostname = '{imap.enlighten-energy.net:143/imap}';
$username = 'abc#enlighten-energy.net';
$password = '*******';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1));
$structure = imap_fetchstructure($inbox,$email_number);
if($structure->parts[0]->encoding == 3 ||$structure->encoding == 3 )
{
$message=imap_base64($message);
}
if($structure->parts[0]->encoding == 4 ||$structure->encoding == 4)
{
$message = imap_qprint($message);
}
$message2= quoted_printable_decode(imap_fetchbody($inbox,$email_number,0));
$date=explode(':',$message2);
$date2= date('d-m-Y h:i:s',strtotime($date[8].':00:00'));
if($overview[0]->subject=="USR:Site01_Comms Complete")
{
$res['date']=$date2;
$res['body']=$message;
}else
{
echo "not a correct mail";
}
}
return $res;
}
/* close the connection */
imap_close($inbox);
}
but it is not working for me any suggestion will appreciable .thanks in advance
Certificate failure for MAIL.enlighten-energy.net: Server name does not match certificate: /OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=*.justhost.com
The error message is actually quite clear if you understand SSL/TLS:
You access imap.enlighten-energy.net (which is a cname to mail.enlighten-energy.net)
But the certificate of the server is issued for *.justhost.com
Since *.justhost.com does not match imap.enlighten-energy.net it will not trust the certificate, because if it would just trust any certificate then the connection would be open to man-in-the-middle attacks which can defeat the encryption.
In summary: if you want to use your own domain name for the IMAP server you have to setup this server with a certificate for your own domain. If this is a shared server between multiple hosts and you don't have access to the configuration of this server, then you cannot do this.
Found the solution , i have to use
$hostname = '{mail.enlighten-energy.net:143/imap/novalidate-cert}INBOX';
instead of this
$hostname = '{imap.enlighten-energy.net:143/imap}';
like , here is the complete solution
function fetch_gmail_inbox()
{
$res=array();
/* connect to gmail */
$hostname = '{mail.enlighten-energy.net:143/imap/novalidate-cert}INBOX';
$username = Yii::app()->getModule('user')->get_config('datalogger_email');
$password = Yii::app()->getModule('user')->get_config('datalogger_email_pwd');
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'UNSEEN');
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1));
$structure = imap_fetchstructure($inbox,$email_number);
if($structure->parts[0]->encoding == 3 ||$structure->encoding == 3 )
{
$message=imap_base64($message);
}
if($structure->parts[0]->encoding == 4 ||$structure->encoding == 4)
{
$message = imap_qprint($message);
}
$message2= quoted_printable_decode(imap_fetchbody($inbox,$email_number,0));
$date=explode(':',$message2);
$date2= date('d-m-Y h:i:s',strtotime($date[8].':00:00'));
if($overview[0]->subject=="USR:Site01_Comms Complete")
{
$res['date']=$date2;
$res['body']=$message;
}
}
return $res;
}
/* close the connection */
imap_close($inbox);
}

PHPMailer: Attach a file located on server

I'm trying to send an (up to 4) attachments using PHPMailer. The files are on my server.
This is how my script works:
User sees a job or resume and contacts them by using the contact form. The contact form stores the data along with the attachments on the server. We will then review the message filtering out spams/scams. If the message is genuine then we will send the message through.
I have the information stored on the server and Im able to send that information via email however the attachments are not sending.
Here is the code used to send the mail:
if ($_GET['status'] == 'approve') {
$id = $_GET['id'];
dbconnect($dbuser, $dbpass, $db);
$sql = "SELECT * FROM $db.mail WHERE id = $id";
$results=mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
$id = $row["id"];
$to = $row["to"];
$from = $row["from"];
$subject = $row["subject"];
$message = $row["message"];
$file1 = $row["file1"];
$file2 = $row["file2"];
$file3 = $row["file3"];
$file4 = $row["file4"];
$result = mysql_query("UPDATE mail SET `status` = '1', `approvedtime` = NOW() WHERE id = " . $_GET['id'])
or die(mysql_error());
header("Location: mail.php");
// PHPMailer - Start
$email = new PHPMailer();
$email->setLanguage('ja');
$email->From = $from;
$email->FromName = 'MySite.com';
$email->Subject = $subject;
$email->Body = $message;
$email->addAddress($to);
if (!empty($file1)) {
$file1 = 'upload/'.$file1;
$email->AddAttachment($file1);
}
if (!empty($file2)) {
$file2 = 'upload/'.$file2;
$email->AddAttachment($file2);
}
if (!empty($file3)) {
$file3 = 'upload/'.$file3;
$email->AddAttachment($file3);
}
if (!empty($file4)) {
$file4 = 'upload/'.$file4;
$email->AddAttachment($file4);
}
return $email->Send();
// PHPMailer - Start
}
} elseif ($_GET['status'] == 'reject') {
dbconnect($dbuser, $dbpass, $db);
$result = mysql_query("UPDATE mail SET `status` = '2', `approvedtime` = NOW() WHERE id = " . $_GET['id'])
or die(mysql_error());
header("Location: mail.php");
}
Why are the attachments not sending? Am I missing a step in my code or have something incorrect?
Thanks for the help!

get link with imap connection

I connect to my gmail account via this code
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myacount#gmail.com';
$password = 'password';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'all');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$message=strip_tags($message);
/* output the email header information */
$emai=split("<",$overview[0]->from );
echo 'Lus ou pas : '.($overview[0]->seen ? 'lue' : 'Non Lue').'<br>';
echo 'subject : '.$overview[0]->subject.'<br> ';
//echo 'from : '.$overview[0]->from.'<br>';
echo 'from : '.$emai[0].' + '.$emai[1].'<br>';
echo 'date : '.$overview[0]->date.'<br>';
/* output the email body */
echo 'Message '.rawurlencode(utf8_decode(rawurldecode($message))).'<br>';
break;
}
echo "<br><br><br><hr><br><br>";
}
/* close the connection */
imap_close($inbox);
in my account I have one email her body have
http://www.test.com?id=4
but when I execute my script I have her in my browser
Lus ou pas : Non Lue
subject : test
from : =?ISO-8859-1?Q?fai=E7al_name?= + myacount#hotmail.com>
date : Mon, 24 Sep 2012 13:39:11 +0000
Message %0D%0A%0D%0A%0D%0A%3D0A%3D%0D%0A%3D0A%3D%0D%0A%3D0A%3D%0D%0Ahttp%3A%2F%2Fwww.test.com%3Fid%3D3D4%20%09%09%20%09%20%20%20%09%09%20%20%20%09%09%20%09%20%20%20%3D%0D%0A%09%09%20%20%0D%0A%3D%0D%0A
how can I get the link exactly.
Ps : English Is not my mother tongue, sorry for any mistakes.
<?php echo 'Message : '.quoted_printable_decode($message).'<br/>';
Try this:
$s = urldecode('%0D%0A%0D%0A%0D%0A%3D0A%3D%0D%0A%3D0A%3D%0D%0A%3D0A%3D%0D%0Ahttp%3A%2F%2Fwww.test.com%3Fid%3D3D4%20%09%09%20%09%20%20%20%09%09%20%20%20%09%09%20%09%20%20%20%3D%0D%0A%09%09%20%20%0D%0A%3D%0D%0A');
echo $s;
It will output =0A= =0A= =0A= http://www.test.com?id=3D4 = = to the screen.
If have no idea why your message is urlencoded in the first place. But it works in you email client, because the email client will urldecode the message to.

Categories