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();
}
});
}
};
Related
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?
I am trying to send a pdf file from database through php Mailer. when I fetch the file from database and save it in $document and echo it. it echos correctly. But when I put the same $document in addAttachment function the email sends but with no attachments. Here is my code
require("PHPMailer-master/class.phpmailer.php");
$link = mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$email = new PHPMailer();
$email->From = 'info#email.com';
$email->FromName = 'xxxxxxxx';
$email->Subject = 'xxxxxxxxxxxxxxxxx';
$email->Body = 'xxxxxxxxxxxxxxxxxxx';
$email->AddAddress( 'saad#gmail.com' );
$result = mysql_query("SELECT file FROM pdf WHERE cnic = 1610209991607", $link) or die("There is an error in the connection");
$document1=mysql_result($result, 0, 'file');
header('Content-type: application/pdf');
//echo $document1;//it works correctly
//$file_to_attach = '$document1';
//$email->AddAttachment($doucment1, 'PayRoll.pdf');//it send the attachment when I attach the file from a folder like AddAttachment(my.pdf);
return $email->Send();`
I am trying to link contact form with thankyouurl.php so customized page will be displayed after sending an email. Everything works in the code except for that one bit. I have tried out a few different things, but php is not my strong side.
<?php
#ini_set('display_errors', 0);
#ini_set('track_errors', 0);
#date_default_timezone_set('Europe/Bucharest'); // Used only to avoid annoying warnings.
if($_REQUEST['action'] = 'email_send') {
$array['name'] = isset($_REQUEST['name']) ? strip_tags(trim($_REQUEST['name'])) : '';
$array['email'] = isset($_REQUEST['email']) ? ckmail($_REQUEST['email']) : '';
$array['subject'] = isset($_REQUEST['subject']) ? strip_tags(trim($_REQUEST['subject'])) : '-';
$array['message'] = isset($_REQUEST['message']) ? (trim(strip_tags($_REQUEST['message'], '<b><a><strong>'))) : '';
// Visitor IP:
$ip = ip();
// DATE
$date = date('l, d F Y , H:i:s');
// BEGIN
require('config.inc.php');
require('phpmailer/5.1/class.phpmailer.php');
$m = new PHPMailer();
$m->IsSMTP();
$m->SMTPDebug = false; // enables SMTP debug information (for testing) [default: 2]
$m->SMTPAuth = true; // enable SMTP authentication
$m->Host = $config['smtp_host']; // sets the SMTP server
$m->Port = $config['smtp_port']; // set the SMTP port for the GMAIL server
$m->Username = $config['smtp_user']; // SMTP account username
$m->Password = $config['smtp_pass']; // SMTP account password
$m->SingleTo = true;
$m->CharSet = "UTF-8";
$m->Subject = ($array['subject'] == '-') ? $config['subject'] : $array['subject'];
$m->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$m->AddAddress($config['send_to'], 'Contact Form');
$m->AddReplyTo($array['email'], $array['name']);
$m->SetFrom($config['smtp_user'], 'Contact Form');
$m->MsgHTML("
<b>Date:</b> {$date} <br>
<b>Name:</b> {$array['name']}<br>
<b>Email:</b> {$array['email']}<br>
<b>Subject:</b> {$array['subject']}<br>
<b>Message:</b> {$array['message']}<br>
---------------------------------------------------<br>
IP: {$ip}
");
if($config['smtp_ssl'] === true)
$m->SMTPSecure = 'ssl'; // sets the prefix to the server
// #SEND MAIL
if($m->Send()) {
header( "http://xyz.ie/thankyouurl.php" );
}
else
{
header( "http://xyz.ie/errorurl.php" );
}
function ip() {
if (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); }
elseif (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); }
elseif (getenv('HTTP_X_FORWARDED')) { $ip = getenv('HTTP_X_FORWARDED'); }
elseif (getenv('HTTP_FORWARDED_FOR')) { $ip = getenv('HTTP_FORWARDED_FOR'); }
elseif (getenv('HTTP_FORWARDED')) { $ip = getenv('HTTP_FORWARDED'); }
else { $ip = $_SERVER['REMOTE_ADDR']; }
return $ip;
}?>
Use header location to redirect to a different page:
header("Location: http://xyz.ie/thankyouurl.php");
So change your code from:
// #SEND MAIL
if($m->Send()) {
header( "http://xyz.ie/thankyouurl.php" );
}
else
{
header( "http://xyz.ie/errorurl.php" );
}
to:
// #SEND MAIL
if($m->Send()) {
header("Location: http://xyz.ie/thankyouurl.php");
} else {
header("Location: http://xyz.ie/errorurl.php");
}
exit();
For more information you can visit: http://php.net/manual/en/function.header.php
Your using header wrong.
header("Location: http://xyz.ie/thankyouurl.php");
exit();
It's
header("Location: http://...");
So a couple of months ago i worked on my registration form with an com code (that is being send through the email) to activate it. The case is that the registration, and the activation of it always worked. But since recently, after some changes, it suddenly wont work anymore. The registration works,the email is being send to me with the com code link, and it also says i can now log in, but as soon as i try to log in with the made account, it sends me to my login error (wrong password or email). As soon as i look in my databse i also see that the data hasnt been inserted (its empty). Ive looked and done multiple things trying to get it fixed but none of it is working. So my last resort: stack;) The code is posted below (left the form code out btw since i dont think that is giving the problem):
The code for connection to the databse is (which is included everywhere):
<?php
$user = "XX";
$host = "XX";
$password = "XX"; //http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html //
$database = "XX";
$conn = new mysqli($host, $user, $password, $database)or die ("Error message");
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
?>
After entering the register button this is the register checking page:
session_start();
include('configdb.php');
if(isset($_SESSION['error']))
{
header("Location: indexresp.php");
exit;
}
else{
if (isset($_POST["submit"])){
$register = $_POST['submit'];
$email2 = strip_tags($_POST['email']);
mysqli_select_db($conn, $database);
$emailcheck = mysqli_query($conn, "SELECT email from user WHERE email='$email2'");
$check = mysqli_num_rows($emailcheck);
if ($check == 0){
}
else {
$_SESSION['error']['email'] = "This Email is already used.";
header("Location: indexresp.php");
exit;
}
}
// the register (form field) data:
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$email = $_POST['email'];
$password = $_POST['wachtwoord'];
$com_code = md5(uniqid(rand()));
$sql2 = "INSERT INTO user (email, password, com_code, voornaam, achternaam) VALUES ('$email', '$password', '$com_code', '$voornaam', '$achternaam')";
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Port = XXX;
$mail->Username = "XXXXX"; // SMTP username
$mail->Password = "XXX"; // SMTP password
$mail->SetLanguage("nl");
$mail->From = "XXXXX";
$mail->FromName = "Oblectare";
$mail->AddAddress("$email");
// name is optional
$mail->AddReplyTo("XXXXX", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Account registratie";
$mail->Body = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code <br>This adress needs to be copyed in the browser and this is your password:<br><br>" .$password;
$mail->AltBody = "http://localhost/debasis/hoofdstuk03/confirm.php?passkey=$com_code. This adress needs to be copyed in the browser and this is your password:" .$password;
if(!$mail->Send())
{
echo "Error mail<p>";
echo "Mail Error: " . $mail->ErrorInfo;
exit;
}
include ('mailconfirmation.php'); // text to say the email has been send
}
So this code sends an email with the activation code (com code). The code for the email confirmation is just plain text so i left it out.
The next being done is setting the activation (with the supplied link) to yes. This is the code that does that:
include('configdb.php');
$passkey = $_GET['passkey'];
$sql = "UPDATE user SET com_code=NULL WHERE com_code='$passkey'";
$result = mysqli_query($conn,$sql) or die(mysqli_error());
if($result)
{
echo '<div>Your account is now active. You may now Log in</div>';
}
else
{
echo "Some error occur.";
}
?>
So when it passes the if (connection) the user gets redirected to the index where he can login with his account info and his info should be activated (by the update). I think the problem is in this piece of code as the sql variable in here doesnt update the com_code anymore for some reason.
After the redirection i try to login with the just inputted (and as it should be: the activated) details.
The code that checks the login (which look if the pass and mail are valid) is as follows:
session_start();
include('configdb.php');
if(isset($_POST['submit_login']))
{
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$result = mysqli_query($conn,"SELECT * FROM user WHERE email='$email' AND password='$password' AND com_code IS NULL"); // was password
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 )
{
$_SESSION['email']=$row['email'];
header("Location: member.php");
exit;
}
else
{
include ('errorlogin.php');
}
}
I hope one of you guys can help me with this problem cause after 2 hours searching it is (for now) enough for me;)
Sorry for my english and some dutch words in the code (try'd to translate some).
Thx in advance!
Your insert part :
$sql2 = "INSERT INTO user ..."
Is never used in the provided code. Maybe you removed the SQL process by error.
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!