Redirect to PHP script from Image - php

I need some help with my PHP code. I want to redirect to my PHP script when I view an hidden image.
When I try this:
http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/phpmailer/examples/send.php?id=71
It will show the image, but it will not redirect to the send.php script with the ID.
Here is the code:
<?php
include('config.php');
require '../PHPMailerAutoload.php';
if (isset($_POST['send'])) {
$from = 'rob#robertsite.org';
$toArr = explode(",",$_POST['to']);
$subject = $_POST['subject'];
$message = $_POST['message'];
$sendDateTime = date("Y-m-d h:i:s");
foreach($toArr as $to)
{
mysql_query("insert into tracker(email, sendDateTime,isRead) values('$to', '$sendDateTime', '0')");
$selSendEmailID = mysql_query("select id from tracker order by id desc");
$rowSendEmailID = mysql_fetch_array($selSendEmailID);
$rowEmailID = $rowSendEmailID['id'];
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = "mail.robertsite.org";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = 'rob#robertsite.org';
$mail->Password = 'mypassword';
$mail->Port = 465; //25, 465 or 587
$mail->FromName = 'Robert Test Mail';
$mail->From = $from;
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->addAddress($to);
$mail->send();
}
echo "Email has been sent!";
}
?>
I am doing this for email tracker where I can see if someone have read my email or not. I tried to use without blank.jpg, it will show the empty image so I have to use blank.jpg to show as a blank image where it cannot be seen.
Do you know how I can run the send.php script with an ID when I view the blank.jpg image??
EDIT: Here is the send.php script:
<?php
include('config.php');
if($_GET['id'] != ''){
$id = $_GET['id'];
$readDateTime = date("Y-m-d h:i:s");
mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
}
if (!empty($_POST['message']))
{
$emails = explode("\n", $_POST['message']); // explode textarea on a line break into an array
$email_str = implode(", ", $emails); // take each of the emails and implode together with the ,
echo '<script> closePopUp(); </script>'; //call javascript function
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send Email</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="jquery-1.12.0.js"></script>
<script>
$(document).ready(function(){
$('#popup').click(function(event) {
event.preventDefault();
var popup = window.open("add_address.php", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=400, height=400");
if (popup != null && !popup.closed) {
var element = popup.document.getElementById("thePopupField");
var text = $('#theField').val();
if(text != ''){
var count = (text.match(/,/g) || []).length;
popup.my_count = count+1;
popup.my_special_setting = text.replace(/,/g, '\n');
}
}
});
});
</script>
</head>
<body>
<!---->
<form action="pr_send.php" method="POST" id="theForm">
<table>
<!-- <tr>
<td>From:</td>
<td><input type="text" name="from"></td>
</tr> -->
<tr>
<td><input type="button" name="to" value="" style="height:24px; width:24px; background:url('addressbook.png'); border:none;" id="popup" > To:</td> <!--onClick="Popup()"-->
<td><input type="text" id="theField" name="to" value="<?php if (!empty($email_str)) { echo $email_str; } ?>" style="height:15px; width:650px"> (<span id="noOfEmails">0</span>)</td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" style="height:15px; width:650px"></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea name="message" cols="90" rows="20"></textarea></td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="submit" name="send" value="" style="height:35px; width:100px; background:url('send.png'); border:none">
</td>
</tr>
</table>
</form>
</body>
<!--<script type="text/javascript">
var popup = null;
function Popup()
{
window.open("add_address.php", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=400, height=400");
}
function closePopUp()
{
if (popup)
{
popup.close();
}
}
</script>-->
</html>

Instead
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
You have to use
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."&img=".urlencode('http://robertsite.org/phpmailer/examples/blank.jpg')."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
And in the send.php script add couple strings
if($_GET['id'] != ''){
$id = (int)$_GET['id'];
$readDateTime = date("Y-m-d h:i:s");
mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
if(!empty($_GET['img'])) {
header('location: '.$_GET['img']);
exit;
}
}

Related

How can i make subject and body message to be given from inputs in phpmailer

This is index.php
Right now all i can do is give values to the $mail->Subject and $mail->body but i want it to be dynamic for example
Here i want to give 2 inputs for subject and message and pass it on $mail->Subject and $mail->Body
since the post method is on ajax im unable to pass two values from input fields to the send_mail.php any help would be appreciated
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Customer Name</th>
<th>Email</th>
<th>Select</th>
<th>Action</th>
</tr>
<?php
$count = 0;
foreach($result as $row)
{
$count = $count + 1;
echo '
<tr>
<td>'.$row["customer_name"].'</td>
<td>'.$row["customer_email"].'</td>
<td>
<input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
</td>
<td>
<button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
</td>
</tr>
';
}
?>
<tr>
<td colspan="3"></td>
<td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name')
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
And this is send_mail.php
<?php
//send_mail.php
if(isset($_POST['email_data']))
{
require 'class/class.phpmailer.php';
$output = '';
foreach($_POST['email_data'] as $row)
{
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = 'xx';
$mail->Password = 'xx';
$mail->SMTPSecure = 'tls';
$mail->From = 'xx';
$mail->FromName = 'xx';
$mail->AddAddress($row["email"], $row["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
$mail->AltBody = '';
$result = $mail->Send(); //Send an Email. Return true on success or false on error
// if($result["code"] == '400')
// {
// $output .= html_entity_decode($result['full_error']);
// }
}
if($output == '')
{
echo 'ok';
}
else
{
echo $output;
}
}
?>
I am assuming You want to add two inputs for subject and message for each email data.
You can add 2 fields and in ajax set it along with email data and pass it to send_mail.php.
JS Code
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name"),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name'),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
In send_mail.php replace following lines
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
With This
$mail->Subject = $row["subject"];
$mail->Body = $row["message"];
Hope it will answer your question.
Firt of all:
Send only user id with ajax (better use fetch() for requests in js)
and then get user data in file (send_mail.php) from database (user validation)!!!
User validation is needed if not by session then by checking against the database.
See composer class for sending emails with phpmailer here:
https://github.com/MoovFun/Xo-Mail

How to set my own upload size of attachment?

I want to set on this PHP code my own size limit of attachment.
I've tried lot of codes but anything isn't working.
Can u help me with it? What working code should I use there?
I want to set maximum size to 2MB, and there should be message ,,Sorry, this attachment is too big (or sth else - it's for check that it's working)".
And how to definite types to attach? For example I want only PNG and JPG to upload. How to do that on my code? And there should be message too, for example - ,,Sorry, you can only attach PNG and JPG files."
NOTE! EVERYTHING IS WORKING RIGHT. I ONLY WANT TO CHANGE UPLOAD SIZE AND MAKE PNG AND JPG FILES :) THANKS!
Here is my PHP code:
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
if(!empty($_POST["send"])) {
require_once ('phpmailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->Port = 587;
$mail->Username = "wlasciciel#rubinmc.pl";
$mail->Password = "XXXXXXXXX";
$mail->Mailer = "smtp";
if (isset($_POST["userEmail"])) {
$userEmail = $_POST["userEmail"];
}
if (isset($_POST["userName"])) {
$userName = $_POST["userName"];
}
if (isset($_POST["subject"])) {
$subject = $_POST["subject"];
}
if (isset($_POST["userMessage"])) {
$message = $_POST["userMessage"];
}
if (isset($_POST["NickCheatera"])) {
$NickCheatera = $_POST["NickCheatera"];
}
$mail->SetFrom('wlasciciel#rubinmc.pl', $userName);
$mail->AddReplyTo($userEmail, $userName);
$mail->AddAddress("wlasciciel#rubinmc.pl"); // set recipient email address
$mail->Subject = 'Zgloszenie';
$mail->Body = join('', array(
'Wiadomosc od: ',
$_POST['userName'],
'<br/>',
'E-mail: ',
$_POST['userEmail'],
'<br/>',
'Nick cheatera: ',
$_POST['NickCheatera'],
'<br/>',
'Powod: ',
$_POST['subject'],
'<br/>',
'Dodatkowe informacje: ',
'<br/>',
$_POST['userMessage'],
'<br/>'
));
$mail->WordWrap = 80;
$mail->IsHTML(true);
$mail->SMTPSecure = 'tls';
$mail->Host = 'serwer2092488.home.pl';
if (! empty($_FILES['attachment'])) {
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
// Attaching multiple files with the email
for ($i = 0; $i < $count; $i ++) {
if (! empty($_FILES["attachment"]["name"])) {
$tempFileName = $_FILES["attachment"]["tmp_name"][$i];
$fileName = $_FILES["attachment"]["name"][$i];
$mail->AddAttachment($tempFileName, $fileName);
}
}
}
}
if (! $mail->Send()) {
$message = "Wystąpił problem podczas wysyłania e-maila. Spróbuj ponownie.";
$type = "error";
} else {
$message = "Dziękujemy za zgłoszenie! Odpowiemy do 24 godzin.";
$type = "success";
}
}
HTML code:
<?php
require_once "mail-sending-script.php";
iconv_set_encoding("internal_encoding", "UTF-8");
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>RubinMC - zgłoś cheatera</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function validate() {
var valid = true;
$(".info").html("");
var userName = document.forms["mailForm"]["userName"].value;
var userEmail = document.forms["mailForm"]["userEmail"].value;
var NickCheatera = document.forms["mailForm"]["NickCheatera"].value;
var subject = document.forms["mailForm"]["subject"].value;
var userMessage = document.forms["mailForm"]["userMessage"].value;
if (userName == "") {
$("#userName-info").html("(To pole jest wymagane.)");
$("#userName").css('background-color', '#FFFFDF');
valid = false;
}
if (userEmail == "") {
$("#userEmail-info").html("(To pole jest wymagane.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (!userEmail.match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#userEmail-info").html("(Zły format e-maila.)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (NickCheatera == "") {
$("#NickCheatera-info").html("(To pole jest wymagane.)");
$("#NickCheatera").css('background-color', '#FFFFDF');
valid = false;
}
if (subject == "") {
$("#subject-info").html("(To pole jest wymagane.)");
$("#subject").css('background-color', '#FFFFDF');
valid = false;
}
if (userMessage == "") {
$("#userMessage-info").html("(To pole jest wymagane.)");
$("#userMessage").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
</script>
</head>
<body>
<h1 style="text-align: center">Zgłoś cheatera</h1>
<div class="attachment-form-container">
<form name="mailForm" id="mailForm" method="post" action=""
enctype="multipart/form-data" onsubmit="return validate()">
<div class="input-row">
<label style="padding-top: 20px;">Nick</label> <span
id="userName-info" class="info"></span><br /> <input
type="text" class="input-field" placeholder="Wpisz swój nick..." name="userName"
id="userName" />
</div>
<div class="input-row">
<label>E-mail</label> <span id="userEmail-info"
class="info"></span><br /> <input type="text"
class="input-field" name="userEmail" placeholder="Wpisz adres e-mail..."
id="userEmail" />
</div>
<div class="input-row">
<label>Nick cheatera</label> <span id="NickCheatera-info"
class="info"></span><br /> <input type="text"
class="input-field" name="NickCheatera" placeholder="Wpisz nick cheatera..."
id="NickCheatera" />
</div>
<div class="input-row">
<label for="subject">Powód</label>
<select id="subject" name="subject" class="input-field">
<option disabled selected>Wybierz powód</option>
<option id="Spam">Spam</option>
<option id="X-Ray">X-Ray</option>
<option value="Sales3">Sales2</option>
</select>
</div>
<div class="input-row">
<label>Dodatkowe informacje</label> <span id="userMessage-info"
class="info"></span><br />
<textarea name="userMessage" id="userMessage"
class="input-field" id="userMessage" placeholder="Wpisz dodatkowe informacje..."
cols="60"
rows="6"></textarea><br />
<label>Dodaj załącznik</label>
</div>
<div class="attachment-row">
<input type="file" class="input-field"
name="attachment[]">
</div>
<div>
<input type="submit" name="send" style="position: relative; left: 210px" class="btn-
submit"
value="Wyślij" />
<div id="statusMessage">
<?php
if (! empty($message)) {
?>
<p class='<?php echo $type; ?>Message'><?php echo $message; ?></p>
<?php
}
?>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
var inputPreview = $(".input-preview"),
input = $(".input");
TweenMax.set(input, {
scale: 1.2,
alpha: 0
});
inputPreview.on("click", function(){
var that = $(this);
that.toggleClass("active");
if(that.hasClass("active")){
TweenMax.staggerTo(input, 1.25, {
scale: 1,
alpha: 1,
ease: Elastic.easeOut
}, .1);
}
else {
TweenMax.staggerTo(input, 1, {
scale: 1.2,
alpha: 0,
ease: Elastic.easeOut
}, .1);
}
});
input.on("click", function() {
var tlInput = new TimelineMax({
onComplete: done
});
var that = $(this),
siblings = that.siblings(".input"),
data = that.data("val"),
top = that.css("top");
siblings.removeClass("active");
tlInput.to(siblings, .25, {
alpha: 0
})
.to(that, .25, {
scale: 1.2
})
.to(that, .25, {
top: 0,
})
.set(inputPreview, {
display: "none"
})
.to(that, .25, {
scale: 1,
})
.to(that, .5, {
backgroundColor: "#1D77EF"
})
.set(inputPreview, {
text: data,
display: "block"
})
.to(that, .25, {
alpha: 0
})
function done() {
inputPreview.removeClass("active");
that.css("top", top).addClass("active");
TweenMax.set(input, {
scale: 1.2,
alpha: 0,
backgroundColor: "#fff"
});
}
});
// copy
balapaCop("Select Input Interaction", "rgba(255,255,255,.5)");
});
</script>
</body>
</html>
Try by changing upload_max_filesize in php.ini.

duplicate page content after ajax to the same page

I have simple registration formulae and I want I want to firstly send with ajax and without refreshing the page to control if I insert correct data and then just redirect to some other page. The problem is that after I send it through ajax to the same page everything is working but content of my page is being duplicate, I can see it twice...
here is my ajax
function registruj () {
var name = $('#meno').val();
var priez = $('#priezvisko').val();
var log = $('#login').val();
var mail = $('#mail').val();
var cisloTel = $('#cislo').val();
var heslo = $('#heslo').val();
var heslo1 = $('#heslo1').val();
$.post( "", {
'meno': name,
'priezvisko': priez,
'login':log,
'mail':mail,
'cislo':cisloTel,
'heslo':heslo,
'heslo1':heslo1,
}, function (data) {
$('#result').html(data);
}
);
$('#nove').load(document.URL + ' #nove');
}
and this is my php file
<?php
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
}
?>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>blblblbl</title>
<link rel="stylesheet" type="text/css" href="./fancybox/jquery.fancybox-1.3.4.css" media="screen" />
<script src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script>$(function(){$('.img').fancybox();});</script>
<style type="text/css"> </style>
<script type="text/javascript" src="mojskript.js"></script>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style1.css" />
</head>
<body class="registracia">
<div class="container">
<div id="nove">
<form >
<table >
<tr><td><label for="napdis">Vyplňte nasledujúci formulár:</label></td></tr>
<tr><td><input type="radio" name="pohlavie" value="zena" id="zena" >Žena</td></tr>
<br>
<tr><td><input type="radio" name="pohlavie" value="muz" id="muz">Muž</td></tr>
<br>
<tr><td><label for="meno">Meno :</label></td><td><input type = "text" id="meno" name="meno"></td></tr><br>
<tr><td><label for="priezvisko">Priezvisko :</label></td><td><input type = "text" id="priezvisko" name="priezvisko"></td></tr><br>
<tr><td><label for="login">Login :</label></td>
<td><input type = "text" id="login" name="login"></td></tr><br>
<?php
if(isset($heslo)) {
if (($heslo != "" && $hesloZnovu != "") && ($heslo == $hesloZnovu)) {
$hesloOk = 1;
}
else {
echo '<tr><td><label for="heslo">Heslo :</label><td><input type = "password" name="heslo"></td><td><label for="zleHeslo">Heslá sa nezhodujú</label></td></tr>';
$pocet = 1;
}
}
?>
<?php
if(!isset($pocet)) {
echo'<tr ><td ><label for="heslo" > Heslo :</label ></td >
<td ><input type = "password" id="heslo" name = "heslo" ></td ></tr ><br >';
}
?>
<tr><td><label for="heslo2">Heslo znovu :</label></td>
<td><input type = "password" id="heslo1" name="heslo1"></td></tr><br>
<?php
if(isset($mail)) {
if (!stristr($mail, "#") OR !stristr($mail, ".")) {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" name="email"></td><td><label for="zlyMail">Zlý formát emailu</label></td></rd></tr><br>';
} else {
$mailOk = 1;
}
}
else {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" id="mail" name="email"></td></tr><br>';
}
?>
<tr><td><label for="cislo">Telefónne číslo :</label></td>
<td><input type = "text" id="cislo" name="cislo"></td></tr><br>
<tr><td><input type="button" value="Zaregistrovať" onclick="registruj()" ></td></tr>
</table>
</form>
<?php
if(isset($mailOk) && isset($hesloOk)) {
$length = 20;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$zasifrovane = crypt($heslo,$randomString);
echo $zasifrovane;
mysql_query("INSERT INTO uzivatelia (Meno,Priezvisko,Login,Heslo,mail,pohlavie,cislo) VALUES ('$meno','$priezvisko','$login','$zasifrovane','$mail','$pohlavie','$cislo')");
header("location:index.php");
}
?>
</div>
<div id="result"></div>
</div>
</body>
How should I do that ?
Try to use exit(); like :
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
exit();
}
Use exit(); or die(); when ajax processing done otherwise it will return all page content.
Change success function to:
function (data) {
$('#result').empty().html(data);
}

PHP form forgets values when uploading large files

Title says it all...I have a contact form that allows four files to be uploaded. If you upload large files, the form actually "forgets" name, phone number, e-mail, etc. At least, I get the error screen telling the user to provide that info, and I don't get the e-mail message.
If I use small files (like, say, a megabyte or less), it works fine, and I get the files, but any more bandwidth and it's like I'm submitting a blank form, even though it goes through the motion of uploading the files (it takes well over a minute before I get the error page).
Here's the source of the form itself, including some PHP:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<html>
<head>
<script language="Javascript">
function formValidate() {
// Did the user include a name?
var userName=document.forms["contactRich"]["cName"].value;
if (userName=="" || userName==null) {
alert("Please provide your name.");
return false;
}
// Did the user include a phone number and area code?
var phoneNumber=document.forms["contactRich"]["cNumber"].value;
var areaCode=document.forms["contactRich"]["cAreaCode"].value;
if (phoneNumber=="" || phoneNumber==null || areaCode=="" || areaCode==null) {
alert("Please include your phone number with the area code.");
return false;
}
// Did the user provide a valid e-mail address?
var emailAddress=document.forms["contactRich"]["cEmail"].value;
var atCount=emailAddress.split("#").length-1;
var lastAt=emailAddress.lastIndexOf("#");
var isDot=emailAddress.lastIndexOf(".");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(emailAddress) || emailAddress=="" || emailAddress==null || emailAddress.length<5 || lastAt <0 || isDot<0 || isDot<lastAt || atCount!=1) {
alert("Please provide a valid e-mail address.");
return false;
}
// Did the user select a service?
if (document.forms["contactRich"]["cTopic"].value=="null") {
alert("Please tell us what you need help with.");
return false;
}
document.getElementById("isValid").value="yes";
return true;
}
</script>
<!-- #BeginEditable "doctitle" -->
<title>Contact Rich</title>
<!-- #EndEditable -->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.form { font-family: "Franklin Gothic Medium", "Trebuchet MS"; font-size: 13pt}
-->
</style>
</head>
<body bgcolor="#CCCCCC">
<table width="800" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF">
<form name="contactRich" id="contactRich" method="post" action="formHandler2.php" enctype="multipart/form-data" onsubmit="return fabFormValidate()">
<table cellpadding="6">
<tr>
<td colspan="2"><h3>Contact</h3></td>
</tr>
<tr>
<td class="form">Your name:</td>
<td><input type="text" name="cName" size="31"></td>
</tr>
<tr>
<td class="form">Your phone number:<br /><span class="footer">(Include area code)</span></td>
<td>(<input type="text" size="3" maxlength="3" name="cAreaCode"/>) <input type="text" id="cNumber" name="cNumber" size="23"></td>
</tr>
<tr>
<td class="form">Your e-mail address:</td>
<td><input type="text" name="cEmail" size="31"></td>
</tr>
<tr>
<td class="form">What can we help you with?</td>
<td><select name="cTopic">
<option value="null">(Please choose:)</option>
<option value="an estimate">Estimate</option>
<option value="bifold doors">Bifold doors</option>
<option value="broken window ropes">Broken window ropes</option>
<option value="door that won't stay shut">My door won't stay shut!</option>
<option value="noisy doors">My door is noisy!</option>
<option value="sticking doors">My door is sticking!</option>
<option value="drywall repairs">Drywall repairs</option>
<option value="garbage disposals">Garbage disposals</option>
<option value="grab bars">Grab bars</option>
<option value="your various services">(other)</option>
</select></td>
</tr>
<tr>
<td class="form">Any additional details?</td>
<td><textarea name="cAdditional" cols="27" rows="4" wrap="soft"></textarea></td>
</tr>
<tr>
<td class="form">You may include up to<br />four pictures:</td>
<td>
<input type="file" name="file_1" id="file_1" /><br />
<input type="file" name="file_2" id="file_2" /><br />
<input type="file" name="file_3" id="file_3" /><br />
<input type="file" name="file_4" id="file_4" /><br />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan="2"><hr /></td>
</tr>
</table>
<input type="hidden" id="isValid" name="isValid" value="no" />
</form>
</table>
<p> </p>
</body>
</html>
Here's the PHP that actually processes the data and tries to send it, via PHPMailer:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
$error_exists = false;
$masterEmail = "email#goes.here";
require 'PHPMailer-master/PHPMailerAutoload.php';
include "Form.php";
$name = $_POST['cName'];
$areaCode = $_POST['cAreaCode'];
$phone = $_POST['cNumber'];
$email = $_POST['cEmail'];
$from = "from_address#goes.here";
$topic = "(WEB) ".$_POST['cTopic'];
$additional = $_POST['cAdditional'];
$isValid = $_POST['isValid'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r<br /> <br />";
$body = "Name: ".$name."<br /> <br />";
$body = $body."Phone number: (".$areaCode.") ".$phone."<br /> <br />";
$body = $body."E-mail address: ".$email."<br /> <br />";
$body = $body."Needs help with: ".$topic."<br /> <br />";
if (!empty($additional)) {
$body = $body .$additional;
}
$body .= "\n\nIP address: ".$_SERVER['REMOTE_ADDR']."<br /> <br />";
$body .= "Browser: ".$_SERVER['HTTP_USER_AGENT']."<br /> <br />";
$mail = new PHPMailer();
$mail->addAddress($masterEmail);
$mail->setFrom($email, $from);
$mail->Subject = $subject;
$mail->msgHTML($body);
if (isset($_FILES['file_1'])) {
$mail->addAttachment($_FILES['file_1']['tmp_name'],$_FILES['file_1']['name']);
}
if (isset($_FILES['file_2'])) {
$mail->addAttachment($_FILES['file_2']['tmp_name'],$_FILES['file_2']['name']);
}
if (isset($_FILES['file_3'])) {
$mail->addAttachment($_FILES['file_3']['tmp_name'],$_FILES['file_3']['name']);
}
if (isset($_FILES['file_4'])) {
$mail->addAttachment($_FILES['file_4']['tmp_name'],$_FILES['file_4']['name']);
}
if (empty($name)) {
$errors = "Please provide your name.<br />";
$error_exists = true;
}
if (!ctype_digit($areaCode) || strlen($areaCode) != 3 || strlen($phone) < 7) {
$errors .= "Please provide your phone number, including area code.<br />";
$error_exists = true;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "Please enter a valid e-mail address.<br />";
$error_exists = true;
}
if (empty($topic)) {
$errors .= "Please tell us what you need help with.<br/>";
$error_exists = true;
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<title>Request for Information</title>
</head>
<body bgcolor="#cccccc">
<?php
$f=new fabForm();
$f->setSubject($subject);
$f->setBody($body);
$f->setEmail($email);
$f->setFrom($from);
?>
<p> </p>
<table align="center" bgcolor="#FFFFFF">
<tr>
<td>
<?php
if ($error_exists) {
echo $errors;
echo " <br />";
echo "<a href='contact.php'>Click here to try again.</a>";
} else {
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</td>
</tr>
</table>
</body>
</html>
Finally, here's the form class I'm using:
<?php
class Form {
private $email;
private $subject;
private $body;
private $from;
private $headers;
// SET methods
public function setEmail($emailAddress) {
$this->email=$emailAddress;
}
public function setSubject($subjectLine) {
$this->subject=$subjectLine;
}
public function setBody($bodyText) {
$this->body=$bodyText;
}
public function setHeaders($sizeHeaders) {
$this->headers=$sizeHeaders;
}
public function setFrom($whoFrom) {
$this->from="From:".$whoFrom."\n".$this->headers;
}
// ACCESSOR METHODS
public function getEmail() {
return $this->email;
}
public function getSubject() {
return $this->subject;
}
public function getBody() {
return $this->body;
}
public function getHeaders() {
return $this->headers;
}
public function getFrom() {
return $this->from;
}
public function sendMail($sendHere) {
if (mail(
$sendHere,
stripslashes($this->getSubject()),
stripslashes($this->getBody()),
$this->getFrom()
)
)
echo("<p>Your request has been sent.</P>");
else
echo("<p>Due to technical difficulties, your request could not be delivered.</p>");
}
}
?>
I can post the PHPMailer source files, but that's practically a whole software package...
But what would cause the form's data to literally be forgotten?? How could I prevent it??? (And limiting file size is not a feasible option.) If it helps, the host is 1and1.com.
when the file is bigger than post_max_size the "POST datas" are erased by PHP
a solution would be to send the file by AJAX before to submit the form. look here to know how to do this :
Upload image with JavaScript from another server via AJAX

PHP mail form problems?

sorry if this seems like a silly question but I'm really stuck.
I'm using a form with php to allow users to send mail from my website and everything works fine except when you want to add more than one 'item', 'amount' and 'boxeach' to the form.
The script I use does duplicate the items but keeps them with the same name, which means that my php will only read and send one of them in the email. Is there any way to change that so all of those three elements are put in the email, with one appearing under the other?
This is the script I use to duplicate (used with a button):
<script>$(function() {
$('#copy').click(function(){
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
});</script>
Here is my full html code:
<head>
<title>WHOLESALE ORDER</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>$(function() {
$('#copy').click(function(){
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
});</script>
label,a
{
font-family : Arial, Helvetica, sans-serif;
font-size : 12px;
}
</style>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>
<body>
<h2>WHOLESALE ORDER <strong><script type="text/javascript">
var date = new Date();
var month = new Array(7);
month[0] = "01";
month[1] = "02";
month[2] = "03";
month[3] = "04";
month[4] = "05";
month[5] = "06";
month[6] = "07";
month[7] = "08";
month[8] = "09";
month[9] = "10";
month[10] = "11";
month[11] = "12";
var year = date.getYear();
if (year < 2000) { year+=1900; }
document.write(date.getDate() + "/" + month[date.getMonth()] + "/" + year);
</script></strong></h2>
<form method="POST" name="contactform" action="contact-form-handler.php">
<p>
<table><tr><td>
<label for='name'>Name:</label> <br>
<input type="text" name="name">
</td>
<td>
<label for='email'>Email:</label> <br>
<input type="text" name="email">
</td></tr></table>
</p>
<p>
<table><tr><td>
<label for='address'>Delivery Address:</label> <br>
<input type="text" name="address">
</td>
<td>
<label for='telephone'>Telephone:</label> <br>
<input type="tel" name="telephone">
</td></tr></table>
</p>
<p>
<div id="content"><table><tr><td><label for='amount'><input type="text" name="amount"></label>
<label for='items'><select name="items">
<option value="APPLE BAG">APPLE BAG</option>
<option value="APPLE BRAMLEY">APPLE BRAMLEY</option></select></label>
<label for='boxeach'><select name="boxeach">
<option value="BOX">BOX</option>
<option value="EACH">EACH</option>
</select></label>
</td></tr></table></div>
</p>
<p>
<input type="button" id="copy" value="Add another item +"/>
</p>
<input type="submit" value="Submit"><br>
</form>
<script language="JavaScript">
var frmvalidator = new Validator("contactform");
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email");
frmvalidator.addValidation("email","email","Please enter a valid email address");
</script>
Here is my full php code:
<?php
$errors = '';
$myemail = 'someone#gmail.com';//
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['items']) ||
empty($_POST['boxeach']) ||
empty($_POST['amount']))
{
$errors .= "\n Error: all fields are required";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$amount = $_POST['amount'];
$items = $_POST['items'];
$boxeach = $_POST['boxeach'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "WHOLESALE ORDER $name";
$email_body = "You have received a new message. ".
" Here are the details:\n $name \n $email_address \n \n \n $amount $items $boxeach";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: contact-form-thank-you.html');
}
?>
When you click $("#copy) you create a div with information,that rewrites the privous one.
What you can do is to make a hidden input which will be outside of the #content div since you are rewriting it's html.
<input type="hidden" name="name_string">
And on click when you create a div also append the information to your hidden input:
$('#copy').click(function(){
var hidden = $("input[name='name_string']);
hidden.val(hidden.val() +","+ $("input[name='name']).val());
var content = $('#content').html();
var newdiv = $("<div>");
newdiv.html(content);
$('#content').after(newdiv);
});
Then in php you will get $_POST["name_string"] which will be like "name1,name2,name3,". You can use explode function in php to create and array from this string:
$array = explode(",", $_POST["name_string"]);
The problem you're having is that you're not making an array of the elements to store multiple values. Your script is just recreating a div. So the simple solution is that add "[]" to your amount, itmes and boxeach elements. i.e
<input type="text" name="amount[]" />
<select name="items[]">...</select>
<select name="boxeach[]">...</select>
Than in your php code change these lines from
$amount = $_POST['amount'];
$items = $_POST['items'];
$boxeach = $_POST['boxeach'];
to
$amount = implode(',',$_POST['amount']);
$items = implode(',',$_POST['items']);
$boxeach = implode(',',$_POST['boxeach']);
or manipulate the posted array in what ever way you like.
I hope my it helps you.

Categories