Get value from another file PHP - php

I'm using PHPMailer inside WordPress for sending mails. For this I have 3 files:
contacts.php - file with html form:
<?php
/*
* Template Name: Contacts
*/
get_header(); ?>
<div class="container page">
<h2>Напиши нам</h2>
<div class="row">
<div class="col-lg-5">
<form action="<?php bloginfo('template_url');?>/mailer.php" method="post">
<label for="fname">Имя*</label>
<input type="text" class="form-control" id="fname" name="first-name" required>
<label for="tel">Телефон*</label>
<input type="tel" class="form-control" id="tel" required name="phone">
<label for="tel">E-mail</label>
<input type="tel" class="form-control" id="email" name="email">
<label for="">Сообщение*</label>
<textarea required class="form-control" rows="8" name="msg"></textarea>
<button type="submit" class="btn btn-success" id="btn-contacts">Отправить</button>
</form>
</div>
<div class="col-lg-7">
</div>
</div>
</div>
<?php get_footer(); ?>
mailer.php - the handler for the form:
<?php
$fname = $_POST["first-name"];
$phone = $_POST["phone"];
$email = $_POST["mail"];
$msg = $_POST["msg"];
require_once("lib/phpmailer/PHPMailerAutoload.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->FromName = "SomeName";
$mail->Host = "smtp.yandex.ru";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->Username = "username";
$mail->Password = "password";
$mail->AddAddress("someaddress#yandex.ru", "Name");
$mail->WordWrap = 50;
$mail->SetFrom("someaddress#ya.ru", "OwnerName");
$mail->IsHTML(true);
$mail->Subject = $fname;
$body = file_get_contents("test.php");
$mail->MsgHTML($body);
if($mail->Send())
echo "Everything is okay";
else
echo "Error!";
?>
test.php - html markup for letter:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<h5>First Name of Person:</h5>
<?php
echo $fname; //how can I get this variable value???
?>
</body>
</html>
And I have faced with a problem.
How can I get this? (see the third snippet and a comment inside). Thank you in advance!

You can store it in session on your POST request and then display it. Also, in WP sessions are not enabled by default. You need to enable them like so.
if (!session_id()) {
session_start();
}
$_SESSION['firstName'] = $_POST['first-name']; // Store
<?php echo $_SESSION['firstName']; // Display ?>

Suggest using herdoc syntax because file_get_contents does not automatically translate VARS unless you run eval() on it(I think). So, simply include('test.php'); which contains...
$body = <<<EOD
....
<h5>First Name of Person:</h5>
$fname
....
EOD;

You can do Heredoc syntax to define the html text along with variables. file_get_contents just read the text source of the file and store in your variable. You have to include this file wherever it needed and use heredoc syntax :
$body = <<<HTML
<h5>First Name of Person:</h5>
{$fname}
HTML;
Of you can define your test.php with some template tags . Use some template variables and replace the value with the actual variable in your form processing code .
In test.php, use
<h5>First Name of Person:</h5>
{first_name}
Then after getting the contents using file_get_contents, replace template variables with the value received from POST .
$body = file_get_contents("test.php");
$body = str_replace("{first_name}",$fname,$body);
Do this for all values to be replaced .

Related

Why PHP PDO bindParam return null if include jQuery file

On every page I have jQuery modal which contains a contact form and which on every page need sent data to different email address. When a form is submitted I need to display successful response using json_encode. Also on every page I use page identifier as $pages_id=1, $pages_id=2, etc., for identify which form is submitted. However, very important, without jQuery file, complete my PHP code it's executed correctly, all data are successfully inserted into database and in Xdebug I also see that code on every line it's executed successfully. But, if I include jQuery file then in Xdebug the value for $pages_id return null. I exactly think at this line of code:
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
However, below is my complete PHP code:
<?php
// set error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
$fname = $tel = $userMail = $userMessage = $email_address_id = "";
$fname_error = $tel_error = $userMail_error = $userMessage_error = "";
$error=false;
//Load the config file
$dbHost = "secret";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "secret";
$dbCharset = "utf8";
$pdo="";
try{
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo "Connection error: " . $e->getMessage();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['submitOwner'])){
$fname = $_POST['fname'];
$tel = $_POST['tel'];
$userMail = $_POST['userMail'];
$userMessage = $_POST['userMessage'];
if(empty($_POST['fname'])){
$error=true;
$fname_error = "Name and surname cannot be empty!";
}else{
$fname = $_POST['fname'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
$fname_error = "Name and surname can only contain letters and spaces!";
}
}
if(empty($_POST['tel'])) {
$tel_error = "Phone number cannot be blank!";
}else{
$tel = $_POST['tel'];
if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$tel_error = "The phone number should contain a minimum of 9 to 15 numbers!";
}
}
if(empty($_POST['userMail'])){
$userMail_error = "Email cannot be blank!";
}else{
$userMail = $_POST['userMail'];
if(!filter_var($userMail, FILTER_VALIDATE_EMAIL)) {
$userMail_error = "Email address is incorrect!";
}
}
if(empty($_POST['userMessage'])) {
$userMessage_error = "The content of the message cannot be empty!";
}else{
$userMessage = $_POST['userMessage'];
if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ0-9 ,.!?\'\"]*$/", $userMessage)){
$userMessage_error = "The content of the message cannot be special characters!";
}
}
if($fname_error == '' && $tel_error == '' && $userMail_error == '' && $userMessage_error == ''){
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret';
$mail->SMTPAuth = true;
$mail->Username = 'secret';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->setFrom('secret#secret.com');
$mail->Subject = "New message from visit-neum.com";
$mail->isHTML(true);
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute(); //in Xdebug this line of code return NULL for $pages_id if include jQuery file
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=array();
if(is_array($emails_other) && count($emails_other)>0){
foreach($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mail->addAddress($email_other['email_address']);
$body_other = "<p>Dear {$email_other['owner_name']}, <br>" . "You just received a message from the site <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Message: </strong>" . $userMessage . "</p>";
$mail->Body = $body_other;
if($mail->send()){
$mail = "INSERT INTO visitneum.contact_owner(fname, tel, userMail, userMessage, email_address_id) VALUES(:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
// Load AJAX
if($error==false){
$information['response'] = "success";
$information['content'] = "Thanks " . ucwords($fname) . "! Your message has been successfully sent to the owner of property! You will get an answer soon!";
$jsonData[] = $information;
}
}//end if mail send
else{
$information['response'] = "error";
$information['content'] = "An error has occurred! Please try again..." . $mail->ErrorInfo;
$jsonData[]=$information;
}
echo(json_encode($jsonData));
} // end foreach($emails_other as $email_other)
} // end if(is_array($emails_other) && count($emails_other)>0)
} // end if validation
} // end submitOwner
} // end REQUEST METHOD = POST
And below you can see submitHandler for my jQuery file which causes me problem:
submitHandler: function(form){
var formData=jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: "/inc/FormProcess.php",
type: "post",
dataType: "json",
data: formData,
success:function(jsonData) {
jQuery("#responseOwner").text(jsonData.content);
console.log(jsonData);
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
}); // Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} // end submitHandler
And the page which contains contact form is below:
<?php
include_once './inc/FormProcess.php';
?>
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name and surname ..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone number..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Your e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope owner_icon" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Your message..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="SENT"/>
</form>
<script defer src="/JS/validateOwner.js"></script>
So, I can not figure out what is the problem and why $pages_id return null when include jQuery file. Also, I was forget to mention that code inside line if(is_array($emails_other) && count($emails_other)>0){ return number 0, so complete seguent code isn't executed, but of course this is normal, because $pages_id is null. However, I hope that somebody understand what is the problem and so, thanks in advance for any kind of help that you can give me.
page_id is null in your script because you dont set it in the script.
So why not just adding an hidden input field in your froms with the page id and then in your PHP code
$page_id = $_POST['pageId'];
i think you did not understood ajax correclty. if you post your data to /inc/FormProcess.php it is not like an include before, where you could create variables first and then include it. AJax is like a sub call to the script. it is like if you would open ONLY this scrirpt provided in URL. so at this point you dont have your variables.
you need to get the variables or send your ajax request NOT to /inc/FormProcess.php but to the script where you define the variable
All you have to do is add input type hidden at the end of the form, so my correct form should look like this:
<form spellcheck="false" autocomplete="off" autocorrect="off" id='contactOwner' class='form ajax' name='contactOwner' action='' method='POST'>
<h4 id="responseOwner" class="success">
<!-- This will hold response from the server --></h4>
<fieldset>
<legend>Vaši podaci</legend>
<div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Vaše ime i prezime..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
<div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Vaš broj telefona..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control -->
<div class="form-control single InputIconBg"><input type="text" class="input mail" name="userMail" placeholder="Vaš e-mail..." value="<?php echo Input::get('userMail'); ?>" autocomplete="email"><i id="" class="fas fa-envelope" aria-hidden="true"></i><span class="error"><?=$userMail_error; ?></span></div><!-- end .form-control -->
<div class="form-control InputIconBg"><textarea maxlength="1000" name="userMessage" class="textinput message" cols="46" rows="8" placeholder="Vaša poruka..."><?php echo Input::get('userMessage'); ?></textarea><i class="fas fa-pencil-alt owner_icon" aria-hidden="true"></i><span class="error"><?=$userMessage_error; ?></span></div><!-- end .form-control -->
</fieldset>
<input type="hidden" name="pages_id" value="<?=$pages_id?>">
<input type="submit" class="btn_submit" id="submitOwner" name="submitOwner" value="POŠALJI"/>
</form>

PHPMailer form not sending attachments

I'm trying to implement a contact form using PHPMailer but I can't make the attachment from the upload field to be sent. The contact form do work and all the other fields are sent.
I followed this tutorial with no luck.
Also tried numerous different PHP scripts such as this, this and this one, among others.
The current code I have that seems to be the most successfully used is this one:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
// Attack #1 preventor - Spam Honeypot
if ($_POST["address"] != "") {
echo "SPAM HONEYPOT";
exit;
}
// Attack #2 preventor - Email header injection hack preventor
foreach($_POST as $value) {
if(stripos($value, 'Content-Type:') !== FALSE) {
echo "There was a problem with the information you entered.";
exit;
}
}
if (isset($_POST['inputNome']) && isset($_POST['inputEmail']) && isset($_POST['inputMensagem'])) {
//check if any of the inputs are empty
if (empty($_POST['inputNome']) || empty($_POST['inputEmail']) || empty($_POST['inputMensagem'])) {
$data = array('success' => false, 'message' => 'Preencha todos os campos requeridos.');
echo ($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "************"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "*************"; // Your full Gmail address
$mail->Password = "*********"; // Your Gmail password
$mail->CharSet = 'UTF-8';
// Compose
$mail->SetFrom($_POST['inputEmail'], $_POST['inputNome']);
$mail->AddReplyTo($_POST['inputEmail'], $_POST['inputNome']);
$mail->Subject = "My Company - " . $_POST['inputAssunto']; // Subject (which isn't required)
$mail->AddAddress('name#myemail.com'); //recipient
//Add attachment
$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) &&
$_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
$mail->addAddress($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
$mail->Body = "Nome: " . $_POST['inputNome'] . "\r\nEmail: " . $_POST['inputEmail'] . "\r\nTelefone: " .$_POST['inputTelefone'] . "\r\nAssunto: " . $_POST['inputAssunto'] . "\r\nMensagem: " . stripslashes($_POST['inputMensagem']);
if(!$mail->send())
{
echo 'An error has occurred.';
exit;
}
echo 'Message successfully sent';
}
?>
And the form:
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php">
<div class="form-group">
<label for="inputNome">Nome Completo *</label>
<input type="text" id="inputNome" name="inputNome" required class="form-control" placeholder="Nome Completo">
</div>
<div class="form-group">
<label for="inputEmail">E-mail *</label>
<input type="email" id="inputEmail" name="inputEmail" required class="form-control" placeholder="Digite seu e-mail">
</div>
<div class="form-group">
<label for="inputTelefone">Telefone</label>
<input type="tel" id="inputTelefone" name="inputTelefone" class="form-control" placeholder="Telefone">
</div>
<div class="form-group">
<label for="inputAssunto">Assunto</label>
<select class="form-control" id="inputAssunto" name="inputAssunto" >
<option disabled selected value> -- Selecione -- </option>
<option value="Orçamento">Orçamento</option>
<option value="Hospedagem">Hospedagem</option>
<option value="Dúvidas">Dúvidas</option>
<option value="Informações">Informações</option>
<option value="Outro">Outro</option>
</select>
</div>
<div class="form-group">
<label for="inputBriefing">Briefing</label>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" id="inputBriefing" name="inputBriefing">
<p class="help-block">Se preferir adicione seus arquivos (.pdf, .docx ou .zip)</p>
</div>
<!--Hpam Sponypot -->
<div class="form-group" style="visibility: hidden">
<label for="address">Address</label>
<input type="text" name="address" id ="address">
<p> Humans, do not fill out this form! </p>
</div>
<div class="form-group">
<label for="inputMensagem">Mensagem *</label>
<textarea class="form-control" rows="3" id="inputMensagem" name="inputMensagem" required placeholder="Escreva sua mensagem"></textarea>
</div>
<p><small>* Campos obrigatórios.</small></p>
<button type="submit" class="btn btn-info">Enviar</button>
</form>
I'm using a shared host on Hostgator.
You were attempting to add the file as a new destination address and not an attachment.
See below for suggested amendment.
//Add attachment
// $_FILES['inputBriefing'] is an array not the file
// adding the file as an attachment before checking for errors is a bad idea also
//$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) && $_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
// this is attempting to add an address to send the email to
//$mail->addAddress($_FILES['inputBriefing']['tmp_name'],$_FILES['inputBriefing']['name']);
$mail->addAttachment($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
You have to add enctype in you form tag like this.
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php" enctype="multipart/form-data">
Try this form tag

PHP Custom Email using PHPMailer

I am designing an email feature for a client,
the main requirements is to keep user on same page if user has some errors
in email, the errors should be shown on the same page.
For that I have created this HTML (PHP)
<?php
session_start();
require_once '../helpers/security.php';
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHPmailer</title>
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="contact">
<?php if(!empty($errors)): ?>
<div class="panel">
<ul>
<li><?php echo implode('</li><li>', $errors); ?></li>
</ul>
</div>
<?php endif; ?>
<form action="contact.php" method="POST">
<label>
Your Name*
<input type="text" name="name" autocomplete="off"<?php echo isset($fields['name']) ? 'value="'.e($fields['name']).'"' : '' ?>>
</label>
<label>
Your Email*
<input type="text" name="email" autocomplete="off"<?php echo isset($fields['email']) ? 'value="'.e($fields['email']).'"' : '' ?>>
</label>
<label>
Your Message*
<textarea name="message" rows="8"><?php echo isset($fields['message']) ? e($fields['message']) : '' ?></textarea>
</label>
<input type="submit" value="Send">
<p class="muted">* means a required field</p>
</form>
</div>
</body>
</html>
<?php
unset($_SESSION['errors']);
unset($_SESSION['fields']);
?>
And this is my PHP code
<?php
session_start();
require_once '../phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
$fields = [
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
];
foreach($fields as $field => $data){
if(empty($data)){
$errors[] = 'The '.$field.' field is required';
}
}
if(empty($errors)){
$m= new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
/*$m->SMTPDebug = 1; */
$m->Host = 'smtp.gmail.com';
$m->Username = 'mymail#gmail.com';
$m->Password = 'mypass';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: '.$fields['name'].' ('.$fields['email'].')<p>'.$fields['message'].'</p>';
$m->FromName = 'Contact';
/*$m->AddReplyTo($fields['email'], $fields['name']);*/
$m->AddAddress('mymail#gmail.com', 'My Name');
if($m->send()){
header('Location: http://facebook.com');
die();
}
else {
$errors[]= 'Error';
}
}
}
else{
$errors[] = 'something went wrong';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: http://google.com');
?>
I have added additional security code
<?php
function e($string){
return htmlentities ($string, ENT_QUOTES, 'UTF-8', false);
}
?>
I have tried this code but it won't work it gives me "500" server error on the index page as well as contact.php page
I have checked with ";" and other general PHP errors
I have checked just by echoing the variables in PHP (PHP works :P )
On the index page if I remove
? $_SESSION['errors'] : [];
? $_SESSION['fields'] : [];
From
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
The index page shows form HTML but when I submit the form I get 500 server error on contact.php
Please help me out this code, Thanks in Advanced
To get rid of the 500 Internal server error:
A) Place this snippet right after
ini_set('display_errors', 'on');
error_reporting(-1);
B) If A is not working, try creating a .htaccess file in the web-root directory with this in it:
php_value error_reporting -1
php_flag display_errors on
C) If B is not working, then your apache\httpd server does not have AllowOverride enabled. You then should change the php.ini (same as B)
(one should never do all the above in production. Only use this while developing)
Now you should be able to see the error, which will be probably that [] is not supported by your PHP version.
Try changing all [] to array().

Phpmailer: multiple dynamic attachments in one form

I am creating a mailing-list service.
I need to attach dynamically one or more files into an email, using php, phpmailer and only one "slot" for adding files in the html form.
I just know how to send one attachment, not two or more, in the same email.
here u are the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div class="main_container">
<form action="phpmailer/sendmail.php" method="post" enctype="multipart/form-data" id="prenota">
<div class="form_title">
<h2>Mailing List</h2>
</div>
<div class="form_title">
<p>Message:</p>
</div>
<label for="message">
<textarea name="message"></textarea>
</label>
<label for="file">
Select one or more file to send
<input name="file" type="file" id="file_ok">
</label>
<div class="submit-container">
<input class="submit-button" type="submit" name="submit" value="Invia"><br>
</div>
</form>
</div>
</body>
</html>
and the php for the phpmailer (sendmail.php, it works with the hosting service I am usign):
<?php
require_once('libs/PHPMailer/PHPMailerAutoload.php');
$db= new PDO('mysql:host=00.000.000.000;dbname=dbname_1', 'dbname', 'dbpass');//connection setup
$m_list = $db->query("
SELECT id, nome, email
FROM mailing_list
")->fetchAll(PDO::FETCH_ASSOC);
$mail = new PHPMailer(true);
$mail->Port = 25;
$mail->CharSet = 'UTF-8';
//variables
$email_receiver = $m_list['email'];
$name_receiver = $m_list['nome'];
$nome_sender= "mr x";
$messagge= stripslashes($_POST['message']);
foreach ($m_list as $eachmail) {
$email_receiver = $eachmail['email'];
$name_receiver = $eachmail['nome'];
$mail->From = "service#email.it";
$mail->FromName = "service";
$mail->AddReplyTo($email_receiver, $name_receiver);
$mail->MsgHTML($body);
$mail->AddAddress($email_receiver, "dynamic name");
$mail->Subject = "Message from website";
$body = '<strong>email send to:</strong> ' . $name_receiver . '<br/>
<strong>email:</strong> ' . $email_receiver . '<br/>
<strong>message:</strong> ' . stripslashes($message) . '<br/><br/>';
$mail->MsgHTML($body);
$mail->Send(true);
$mail->ClearAllRecipients(true);
}
echo "mail sent";
?>
I imagine I need to store the files ito an array and then, for each files, create the relative attachment. Unfortunately I can't. Any help?
First of all I used an "injection" of Jquery, in order to add as much as inputs file I want in the dom of the main form, and to delete them if desired.
$( document ).ready(function() {
$( '#add_more' ).click(function() {
var current_count = $('input[type="file"]').length;
var next_count = current_count +1;
$('#prenota').prepend('<p id="here_' + next_count + '"><input type="file" name="file_' + next_count + '" /></p>')
$('#here_' + next_count + '').append('<a class="delete_this" href="#">delete</a>');
});
$('.delete_this').live('click', function(){
var current_todelete = $(this).closest("p").attr("id");
$('#' + current_todelete + '').remove();
});
});
Then I added some strings in the php file designated to collect post information and sendig emails, making it capable to carry attachments (as Synchro suggested me):
if (isset($_FILES)){
foreach ($_FILES as $file) {
$filename = $file['name'];
$filetype = $file['type'];
$filetmp_name = $file['tmp_name'];
$filesize = $file['size'];
if($filename){
$temPath = '../../../../../public/' . basename($filename);
//var_dump($temPath);
//die();
if (move_uploaded_file($filetmp_name, $temPath)) {
$mail->AddAttachment($temPath, $filename);
}
}
}
}else{
$mail->AddAttachment(false);
}
Hoping to be helpful to people with the same problem of mine.

simple mailto integrating query

OK I have a simple mail to where I am trying to email all my members based on a simple query.
Problem is I must be missing something due to the form just reloads and dose not send anything.
email.php
<form method="post" action="massemail.php">
Subject:</br>
<input type="text" name="subject" /><br />
Message:</br>
<textarea name="details"></textarea><br />
<input type="submit" value="Send"/>
</form>
massemail.php
require 'core/init.php';
require_once "email.php";
$message = check_input($_POST['details']);
$subject = check_input($_POST['subject']);
$results = mysql_query('SELECT email from users');
while(list($email) = mysql_fetch_row($results))
{
mail($email, '$subject', '$message');
}
have tried
<?php
require 'core/init.php';
require_once "email.php";
$message = "test";
$subject = "123";
if ($results = mysql_query('SELECT email from users')) {
while(list($email) = mysql_fetch_row($results)) {
mail($email, '$subject', '$message');
}
?>
First, you need to extract the email addresses from each row instead of using the row itself. That can easily be achieved with $row[0] in your case since your query has always one column, though you should probably try to use mysqli instead of the deprecated mysql.
Second, I would recommend calling mail() once only, to send one message to all people rather than one email per person! Why do you want to send the same email again and again like this? It is possible to use a comma-separated list of emails, as seen on the PHP: mail - Manual.
If you want to use mysql, your code could look something like this with PHP Arrays and the handy implode function:
require 'core/init.php'; // calls mysql_connect(...)
require_once "email.php";
$message = check_input($_POST['details']);
$subject = check_input($_POST['subject']);
if (mysql_ping()) { echo 'Ping worked'; } else { echo 'Ping failed'; } // DEBUG
$results = mysql_query('SELECT email from users');
$emails = array();
while($row = mysql_fetch_row($results))
{
array_push($emails, $row[0]);
}
echo implode(", ", $emails); // DEBUG
if (!empty($emails)) {
mail(implode(", ", $emails), $subject, $message);
}
It seems to me (while chatting with you) that the whole mechanism of HTML Forms + PHP (GET and/or POST) is not clear to you. You should probably read about all this a bit more, and hopefully the code below helps you:
<?php
// Put requires here
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Demo form methods</h1>
<?php
if ((isset($_POST['subject']) && isset($_POST['body'])) || (isset($_GET['subject']) && isset($_GET['body']))) {
// Your code for sending an email could be here
?>
<h2>RESULTs</h2>
<ul>
<li>POST
<ul>
<li>suject: <?php echo $_POST['subject']; ?></li>
<li>suject: <?php echo $_POST['body']; ?></li>
</ul>
</li>
<li>GET
<ul>
<li>suject: <?php echo $_GET['subject']; ?></li>
<li>suject: <?php echo $_GET['body']; ?></li>
</ul>
</li>
</ul>
<?php
// The code above is just to show you how the variables in GET/POST work
} else {
// Below are two formulaires, you can keep one only of course!
?>
<h2>FORMs</h2>
<h3>GET method</h3>
<form method="get" action="email.php">
Subject: <input name="subject" type="text"><br>
Body: <input name="body" type="text"><br>
<input type="submit" value="Send with GET">
</form>
<h3>POST method</h3>
<form method="post" action="email.php">
Subject: <input name="subject" type="text"><br>
Body: <input name="body" type="text"><br>
<input type="submit" value="Send with POST">
</form>
<?php } ?>
</body>
</html>
It's not sending the email because you are not parsing the query results properly.
//connect to MySQL using following line. This is the NEW and better way of doing it.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($result = $mysqli->query('SELECT email from users')) {
while($row = $result->fetch_object()){
mail($row->email, $subject, $message);
}
}
$result->close();

Categories