Problem: Blank email from PHP web application.
Confirmed: App works in Linux, has various problems in Windows server environment. Blank emails are the last remaining problem.
PHP Version 5.2.6 on the server
I'm a librarian implementing a PHP based web application to help students complete their assignments.I have installed this application before on a Linux based free web host and had no problems.
Email is controlled by two files, email_functions.php and email.php. While email can be sent, all that is sent is a blank email.
My IT department is an ASP only shop, so I can get little to no help there. I also cannot install additional libraries like PHPmail or Swiftmailer.
You can see a functional copy at http://rpc.elm4you.org/ You can also download a copy from Sourceforge from the link there.
Thanks in advance for any insight into this!
email_functions.php
<?php
/**********************************************************
Function: build_multipart_headers
***********************************************************
Purpose:
Creates email headers for a message of type multipart/mime
This will include a plain text part and HTML.
**********************************************************/
function build_multipart_headers($boundary_rand)
{
global $EMAIL_FROM_DISPLAY_NAME, $EMAIL_FROM_ADDRESS, $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
// Using \n instead of \r\n because qmail doubles up the \r and screws everything up!
$crlf = "\n";
$message_date = date("r");
// Construct headers for multipart/mixed MIME email. It will have a plain text and HTML part
$headers = "X-Calc-Name: $CALC_TITLE" . $crlf;
$headers .= "X-Calc-Url: http://{$SERVER_NAME}/{$CALC_PATH}" . $crlf;
$headers .= "MIME-Version: 1.0" . $crlf;
$headers .= "Content-type: multipart/alternative;" . $crlf;
$headers .= " boundary=__$boundary_rand" . $crlf;
$headers .= "From: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Sender: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Reply-to: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Return-Path: $EMAIL_FROM_DISPLAY_NAME <$EMAIL_FROM_ADDRESS>" . $crlf;
$headers .= "Date: $message_date" . $crlf;
$headers .= "Message-Id: $boundary_rand#$SERVER_NAME" . $crlf;
return $headers;
}
/**********************************************************
Function: build_multipart_body
***********************************************************
Purpose:
Builds the email body content to go with the headers from
build_multipart_headers()
**********************************************************/
function build_multipart_body($plain_text_message, $html_message, $boundary_rand)
{
//$crlf = "\r\n";
$crlf = "\n";
$boundary = "__" . $boundary_rand;
// Begin constructing the MIME multipart message
$multipart_message = "This is a multipart message in MIME format." . $crlf . $crlf;
$multipart_message .= "--{$boundary}{$crlf}Content-type: text/plain; charset=\"us-ascii\"{$crlf}Content-Transfer-Encoding: 7bit{$crlf}{$crlf}";
$multipart_message .= $plain_text_message . $crlf . $crlf;
$multipart_message .= "--{$boundary}{$crlf}Content-type: text/html; charset=\"iso-8859-1\"{$crlf}Content-Transfer-Encoding: 7bit{$crlf}{$crlf}";
$multipart_message .= $html_message . $crlf . $crlf;
$multipart_message .= "--{$boundary}--$crlf$crlf";
return $multipart_message;
}
/**********************************************************
Function: build_step_email_body_text
***********************************************************
Purpose:
Returns a plain text version of the email body to be used
for individually sent step reminders
**********************************************************/
function build_step_email_body_text($stepnum, $arr_instructions, $dates, $query_string, $teacher_info ,$name, $class, $project_id)
{
global $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
$step_email_body =<<<BODY
$CALC_TITLE
Step $stepnum: {$arr_instructions["step$stepnum"]["title"]}
Name: $name
Class: $class
BODY;
$step_email_body .= build_text_single_step($stepnum, $arr_instructions, $dates, $query_string, $teacher_info);
$step_email_body .= "\n\n";
$step_email_body .=<<<FOOTER
The $CALC_TITLE offers suggestions, but be sure to check with your teacher to find out the best working schedule for your assignment!
If you would like to stop receiving further reminders for this project, click the link below:
http://$SERVER_NAME/$CALC_PATH/deleteproject.php?proj=$project_id
FOOTER;
// Wrap text to 78 chars per line
// Convert any remaining HTML <br /> to \r\n
// Strip out any remaining HTML tags.
$step_email_body = strip_tags(linebreaks_html2text(wordwrap($step_email_body, 78, "\n")));
return $step_email_body;
}
/**********************************************************
Function: build_step_email_body_html
***********************************************************
Purpose:
Same as above, but with HTML
**********************************************************/
function build_step_email_body_html($stepnum, $arr_instructions, $dates, $query_string, $teacher_info, $name, $class, $project_id)
{
global $CALC_PATH, $CALC_TITLE, $SERVER_NAME;
$styles = build_html_styles();
$step_email_body =<<<BODY
<html>
<head>
<title> $CALC_TITLE </title>
$styles
</head>
<body>
<h1> $CALC_TITLE Schedule </h1>
<strong>Name:</strong> $name <br />
<strong>Class:</strong> $class <br />
BODY;
$step_email_body .= build_html_single_step($stepnum, $arr_instructions, $dates, $query_string, $teacher_info);
$step_email_body .=<<<FOOTER
<p>
The $CALC_TITLE offers suggestions, but be sure to check with your teacher to find out the best working schedule for your assignment!
</p>
<p>
If you would like to stop receiving further reminders for this project,
click this link.
</p>
</body>
</html>
FOOTER;
return $step_email_body;
}
/**********************************************************
Function: build_html_styles
***********************************************************
Purpose:
Just returns a string of <style /> for the HTML message body
**********************************************************/
function build_html_styles()
{
$styles =<<<STYLES
<style type="text/css">
body { font-family: Arial, sans-serif; font-size: 85%; }
h1 { font-size: 120%; }
table { border: none; }
tr { vertical-align: top; }
img { display: none; }
hr { border: 0; }
</style>
STYLES;
return $styles;
}
/**********************************************************
Function: linebreaks_html2text
***********************************************************
Purpose:
Convert <br /> html tags to \n line breaks
**********************************************************/
function linebreaks_html2text($in_string)
{
$out_string = "";
$arr_br = array("<br>", "<br />", "<br/>");
$out_string = str_replace($arr_br, "\n", $in_string);
return $out_string;
}
?>
email.php
<?php
require_once("include/config.php");
require_once("include/instructions.php");
require_once("dbase/dbfunctions.php");
require_once("include/email_functions.php");
ini_set("sendmail_from", "reference#cna-qatar.edu.qa");
ini_set("SMTP", "mail.qatar.net.qa");
// Verify that the email has not already been sent by checking for a cookie
// whose value is generated each time the form is loaded freshly.
if (!(isset($_COOKIE['rpc_transid']) && $_COOKIE['rpc_transid'] == $_POST['transid']))
{
// Setup some preliminary variables for email.
// The scanning of $_POST['email']already took place when this file was included...
$to = $_POST['email'];
$subject = $EMAIL_SUBJECT;
$boundary_rand = md5(rand());
$mail_type = "";
switch ($_POST['reminder-type'])
{
case "progressive":
$arr_dbase_dates = array();
$conn = rpc_connect();
if (!$conn)
{
$mail_success = FALSE;
$mail_status_message = "Could not register address!";
break;
}
// Sanitize all the data that will be inserted into table...
// We need to remove "CONTENT-TYPE:" from name/class to defang them.
// Additionall, we can't allow any line-breaks in those fields to avoid
// hacks to email headers.
$ins_name = mysql_real_escape_string($name);
$ins_name = eregi_replace("CONTENT-TYPE", "...Content_Type...", $ins_name);
$ins_name = str_replace("\n", "", $ins_name);
$ins_class = mysql_real_escape_string($class);
$ins_class = eregi_replace("CONTENT-TYPE", "...Content_Type...", $ins_class);
$ins_class = str_replace("\n", "", $ins_class);
$ins_email = mysql_real_escape_string($email);
$ins_teacher_info = $teacher_info ? "YES" : "NO";
switch ($format)
{
case "Slides": $ins_format = "SLIDES"; break;
case "Video": $ins_format = "VIDEO"; break;
case "Essay":
default: $ins_format = "ESSAY"; break;
}
// The transid from the previous form will be used as a project identifier
// Steps will be grouped by project identifier.
$ins_project_id = mysql_real_escape_string($_POST['transid'] . md5(rand()));
$arr_dbase_dates = dbase_dates($dates);
$arr_past_dates = array();
// Iterate over the dates array and build a SQL statement for each one.
$insert_success = TRUE;
//
$min_reminder_date = date("Ymd", mktime(0,0,0,date("m"),date("d")+$EMAIL_REMINDER_DAYS_AHEAD,date("Y")));
for ($date_index = 0; $date_index < sizeof($arr_dbase_dates); $date_index++)
{
// Make sure we're using the right keys...
$ins_date_index = $date_index + 1;
// The insert will only happen if the date of the event is in the future.
// For dates today and earlier, no insert.
// For dates today or after the reminder deadline, we'll send the email immediately after the inserts.
if ($arr_dbase_dates[$date_index] > (int)$min_reminder_date)
{
$qry =<<<QRY
INSERT INTO email_queue
(
NOTIFICATION_ID,
PROJECT_ID,
EMAIL,
NAME,
CLASS,
FORMAT,
TEACHER_INFO,
STEP,
MESSAGE_DATE
)
VALUES (
NULL,
'$ins_project_id',
'$ins_email',
'$ins_name',
'$ins_class',
'$ins_format',
'$ins_teacher_info',
$ins_date_index, /*step number*/
{$arr_dbase_dates[$date_index]} /* Date in the integer format yyyymmdd */
)
QRY;
// Attempt to do the insert...
$result = mysql_query($qry);
// If even one insert fails, bail out.
if (!$result)
{
$mail_success = FALSE;
$mail_status_message = "Could not register address!";
break;
}
}
// For dates today or earlier, store the steps=>dates in an array so the mails can
// be sent immediately.
else
{
$arr_past_dates[$ins_date_index] = $arr_dbase_dates[$date_index];
}
}
// Close the connection resources.
mysql_close($conn);
// SEND OUT THE EMAILS THAT HAVE TO GO IMMEDIATELY...
// This should only be step 1, but who knows...
//var_dump($arr_past_dates);
for ($stepnum=1; $stepnum<=sizeof($arr_past_dates); $stepnum++)
{
$email_teacher_info = ($teacher_info && $EMAIL_TEACHER_REMINDERS) ? TRUE : FALSE;
$boundary = md5(rand());
$plain_text_body = build_step_email_body_text($stepnum, $arr_instructions, $dates, $query_string, $email_teacher_info ,$name, $class, $ins_project_id);
$html_body = build_step_email_body_html($stepnum, $arr_instructions, $dates, $query_string, $email_teacher_info ,$name, $class, $ins_project_id);
$multipart_headers = build_multipart_headers($boundary);
$multipart_body = build_multipart_body($plain_text_body, $html_body, $boundary);
mail($to, $subject . ": Step " . $stepnum, $multipart_body, $multipart_headers, "-fresearch#rpc.elm4you.org");
}
// Set appropriate flags and messages
$mail_success = TRUE;
$mail_status_message = "Email address registered!";
$mail_type = "progressive";
set_mail_success_cookie();
break;
// Default to a single email message.
case "single":
default:
// We don't want to send images in the message, so strip them out of the existing structure.
// This big ugly regex strips the whole table cell containing the image out of the table.
// Must find a better solution...
//$email_table_html = eregi_replace("<td class=\"stepImageContainer\" width=\"161px\">[\s\r\n\t]*<img class=\"stepImage\" src=\"images/[_a-zA-Z0-9]*\.gif\" alt=\"Step [1-9]{1} logo\" />[\s\r\n\t]*</td>", "\n", $table_html);
// Show more descriptive text based on the value of $format
switch ($format)
{
case "Video": $format_display = "Video"; break;
case "Slides": $format_display = "Presentation with electronic slides"; break;
case "Essay":
default:
$format_display = "Essay"; break;
}
$days = (int)$days;
$html_message = "";
$styles = build_html_styles();
$html_message =<<<HTMLMESSAGE
<html>
<head>
<title> $CALC_TITLE </title>
$styles
</head>
<body>
<h1> $CALC_TITLE Schedule </h1>
<strong>Name:</strong> $name <br />
<strong>Class:</strong> $class <br />
<strong>Email:</strong> $email <br />
<strong>Assignment type:</strong> $format_display <br /><br />
<strong>Starting on:</strong> $date1 <br />
<strong>Assignment due:</strong> $date2 <br />
<strong>You have $days days to finish.</strong><br />
<hr />
$email_table_html
</body>
</html>
HTMLMESSAGE;
// Create the plain text version of the message...
$plain_text_message = strip_tags(linebreaks_html2text(build_text_all_steps($arr_instructions, $dates, $query_string, $teacher_info)));
// Add the title, since it doesn't get built in by build_text_all_steps...
$plain_text_message = $CALC_TITLE . " Schedule\n\n" . $plain_text_message;
$plain_text_message = wordwrap($plain_text_message, 78, "\n");
$multipart_headers = build_multipart_headers($boundary_rand);
$multipart_message = build_multipart_body($plain_text_message, $html_message, $boundary_rand);
$mail_success = FALSE;
if (mail($to, $subject, $multipart_message, $multipart_headers, "-reference#cna-qatar.edu.qa"))
{
$mail_success = TRUE;
$mail_status_message = "Email sent!";
$mail_type = "single";
set_mail_success_cookie();
}
else
{
$mail_success = FALSE;
$mail_status_message = "Could not send email!";
}
break;
}
}
function set_mail_success_cookie()
{
// Prevent the mail from being resent on page reload. Set a timestamp cookie.
// Expires in 24 hours.
setcookie("rpc_transid", $_POST['transid'], time() + 86400);
}
?>
Instead of sending it, build the email and display all of the vars used in the mail call to the screen and comment out the mail call. That will confirm that the vars are being properly constructed.
Then start using the mail function again, if you have access to mail logs that would help as well, as it may give you more information. Also, take a look at the headers on the email you receive as that also may show you that a header or 2 is messed up.
Also try setting $crlf = "\r\n";
brett, if you think it's the headers, i'd try the bare minimum and get it to work. once it works, start adding headers until you get the error. then let us know what the problem is.
Related
My question has differently been answered in another post, but I just can't make things work with my own code - so here it comes:
I am making a reminder function, that is supposed to be executed by cron job and send out an reminder email to remind client about an event.
I will use info from mysql, sort out the events that is going to be reminded based on X number of hours and the reminder time frame (if the cron job runs every 15 minutes, the code must find all event starting in the minutes between each cron job run).
All the above works just fine, and I do get the echo "test1"; from test-cron.php. But the email from test-cron-email-reminder.php is not send, and I do not get the echo "test2"; printed out.
I seems like my include in test-cron.php does not work. Why?
If I put it all together in one php file it works fine.
When this is ready, I will make a similar code to send out sms reminder with twilio. That as well works fine, as long as the whole code is in one file.
Both php files are in the same folder.
Here is my code:
TEST-CRON.PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Get info from SQL
$result = performQuery("SELECT mindful_pbbooking_events.service_id,
mindful_pbbooking_treatments.id,
mindful_pbbooking_events.id, name,
customfields_data,
dtstart, dtend, date_created
FROM mindful_pbbooking_events,
mindful_pbbooking_treatments
WHERE
mindful_pbbooking_events.service_id=mindful_pbbooking_treatments.id;
");
while ($row = mysqli_fetch_array($result)) {
//Split customfields_data and collect the informaton from created array (just making things a little bit more easy to work with)
$dataArray = $row[customfields_data];
$dataArrayDecoded = json_decode($dataArray,TRUE);
$clientFname = $dataArrayDecoded[0][data];
$clientLname = $dataArrayDecoded[1][data];
$clientEmail = $dataArrayDecoded[2][data];
$clientMobile = $dataArrayDecoded[3][data];
$clientGender = $dataArrayDecoded[4][data];
//Collect information from customfields_data (more making things a little bit more easy to work with)
$eventId = $row[mindful_pbbooking_events.id];
$eventStart = $row[dtstart];
$eventDate = date("Y-m-d", strtotime($eventStart));
$eventTime = date("H:i", strtotime($eventStart));
$eventEnd = $row[dtend];
$service = $row[name];
$eventCreated = $row[date_created];
//Time calculation to find out who to send reminder to
$eventtimestring = strtotime("$eventStart");
$nowtimestring = strtotime("now");
$reminderdurationstring = $reminderDuration*60;
$startstring = $nowtimestring + $hours*3600;
$endstring = $startstring + $reminderdurationstring;
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
// ****** HERE IT COMES ******
// The test-cron-email-reminder.php is the file with the code I want to include
include 'test-cron-email-reminder.php';
}
}
?>
TEST-CRON-EMAIL-REMINDER-PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
break;
?>
require 'configuration.php';
in TEST-CRON-EMAIL-REMINDER-PHP
may produce redeclaration error
try require_once 'configuration.php';
to prevent it
The problem is in TEST-CRON.PHP -- don't put an include inside a while loop, unless you really want to include that file over and over. (You don't)
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
/// DON'T DO THIS
include 'test-cron-email-reminder.php';
/// DON'T DO THIS
}
Instead, do this. In TEST-CRON.PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
require_once 'TEST-CRON-EMAIL-REMINDER-PHP'
...
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
doSomething(); // Defined in TEST-CRON-EMAIL-REMINDER-PHP
break;
}
In TEST-CRON-EMAIL-REMINDER-PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// And wrap all this stuff up in a function that
// you can call from within your while() loop.
func doSomething() {
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
}
?>
I am trying to have an SMS sent as a reminder to the users of my web application. I am not too familiar or good with cron jobs. I know that I have to set one up, I don't think that I did it effectively though.
I am not sure if my path is correct, how could I test that? Also, should I set it to every minute or should I set it to once a day. What is the difference?
Would this work if the path is correct?
<?php
//This was based upon http://glennstovall.com/blog/2013/01/07/writing-cron-jobs-and-command-line-scripts-in-codeigniter/ with modifications for Easy!Appointments by Craig Tucker, 7/18/2014.
class Reminders extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('email');
$this->load->library('session');
$this->load->model('settings_model');
$this->load->model('reminders_model');
// Set user's selected language.
if ($this->session->userdata('language')) {
$this->config->set_item('language', $this->session->userdata('language'));
$this->lang->load('translations', $this->session->userdata('language'));
} else {
$this->lang->load('translations', $this->config->item('language')); // default
}
}
public function index() {
if(!$this->input->is_cli_request()) {
echo "This script can only be accessed via the command line" . PHP_EOL;
return;
}
$d = 3; //Number of days out for the reminder
$timestamp = strtotime("+".$d." days");
$appointments = $this->reminders_model->get_days_appointments($timestamp);
$baseurl = $this->config->base_url();
$company_name = $this->settings_model->get_setting('company_name');
$appointment_link = $this->config->base_url().'index.php/appointments/index/';
if ($d == "1") {
$notice = "One more day until your appointment.";
} else {
$notice = $d." more days until your appointment.";
}
$msg = '';
if(!empty($appointments)) {
foreach($appointments as $appointment) {
$aptdatetime=date('D g:i a',strtotime($result["start_datetime"]));
$startdatetime=date('l, F j, Y, g:i a',strtotime($appointment->start_datetime));
$config['mailtype'] = 'text';
$this->email->initialize($config);
$this->email->set_newline("\r\n");
$this->email->to($appointment->customer_email);
if (!empty($appointment->customer_cellurl)){
$phone = $appointment->customer_phone_number;
$phone = preg_replace('/[^\dxX]/', '', $phone);
$this->email->bcc($phone.$appointment->customer_cellurl);
}
$this->email->from($appointment->provider_email, $company_name);
$this->email->subject($notice);
$msg .= $company_name."\r\n";
$msg .= "REMINDER: Your appointment with ".$appointment->provider_first_name." ".
$appointment->provider_last_name." is on ".$startdatetime."\r\n";
$msg .= "\r\n";
$msg .= "If you have had a good experience, let others know! Please review me at:\r\n";
$msg .= "www.healthgrades.com/review/XGVRC\r\n";
$msg .= "\r\n";
$msg .= "To edit, reschedule, or cancel your appointment please click the following link:\r\n";
$msg .= $appointment_link.$appointment->hash."\r\n";
$msg .= "\r\n";
$msg .="To attend your session on line, log in to www.craigtuckerlcsw.com and go to 'My Appointments'\r\n";
$this->email->message($msg);
$this->email->send();
$msg = "";
echo $this->email->print_debugger();
}
}
}
}
/* End of file reminders.php */
/* Location: ./application/controllers/cli/reminders.php */
I am trying to migrate our site to a new host that uses PHP5. Previously we were on PHP4.
I have a form that is not submitting and redirecting to the thankyou page after a user fills out a survey which worked previously on php4. I'm sure it's probably something obvious that I'm missing but I can't see why it doesn't work.
When I click submit, the survey page reloads, the URL gets ?submit=t added to the end and the email is not sent to me.
The code from our survey.php is shown below with my email address and most of the HTML form feilds removed. Can somebody point me in the right direction?
Thanks!
<?
$APP_ROOT = "../";
$FILE = __FILE__;
$TITLE="Service Survey";
if(!isset($submit)) {
include($APP_ROOT."include/header.php");
include($APP_ROOT."include/nava.php");
?>
<div class="bodymargin">
<img src="<?=$WEB_ROOT;?>images/titles/<?=$SECTION."_".$FILE;?>.gif" width="400" height="36"><br>
<br>
<form method="POST" action="<?=$FILE;?>.php?submit=t">
<?
if(isset($error)) {
while(list($key, $value) = each($HTTP_GET_VARS)) {
$$key = stripslashes($value);
}
print("<p class=\"alert\">". urldecode($error) . "</p>\n");
}
?>
<input type="text" name="name" value="<?=$name;?>">
</form>
<?
include($APP_ROOT."include/navb.php");
include($APP_ROOT."include/footer.php");
} else {
include_once($APP_ROOT . "functions/index.php");
include_once($APP_ROOT . "functions/form_validation.php");
$CONTINUE = TRUE;
$valid = new Validation($HTTP_POST_VARS);
if($CONTINUE = $valid->success) {
$to = "myemailaddress";
$subject = "Service Survey";
$from_email = $to;
$from_name = "mysite.com";
$headers = "From: $from_name<$from_email>\n";
$headers .= "Reply-To: <$email>\n";
$headers .= "Return-Path: <$from_email>\n";
$body = "The following information was just posted \n";
unset($HTTP_POST_VARS['required_fields']);
reset($HTTP_POST_VARS);
while(list($key, $value) = each($HTTP_POST_VARS)) {
if(!empty($value)) {
$body .= proper_form($key) . ": " . stripslashes($value) ."\n";
}
}
$body .= "\nThis is an automated message, please do not respond.";
mail($to,$subject,$body,$headers);
$URL = $WEB_ROOT . "/customer/thanks.php?form=" . $FILE;
server_redirector($URL);
} else {
while(list($key, $value) = each($HTTP_POST_VARS)) {
$rebound .= "&$key=" . urlencode(stripslashes($value));
}
$URL = $WEB_ROOT . "customer/survey.php?error=". urlencode(nl2br($valid->errors)) . $rebound;
server_redirector($URL);
die();
}
}
?>
regsiter_globals is not active in newer PHP versions.
So instead of using if(!isset($submit)) you have to use if(!isset($_GET['submit'])). And for posted values, you use $_POST['parameter'].
The __FILE__ constant is possibly not returning what you expect, or not what it previously did. from the docs
Since PHP 4.0.2, __ FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
So you may be getting an absolute path now, instead of a relative one.
Also check if your new installation allows for short_open_tags as explained in the docs
$HTTP_POST_VARS is deprecated. You will want to replace it with $_POST.
Alternatively, you can just add $HTTP_POST_VARS = $_POST; at the beginning of the script to avoid editing every line (Not really recommended).
I'm new to PHP and trying to create a form with all fields required, including one where a file must be selected. Here is what I would like to achieve:
user must complete 4 fields + upload a file
file can only be of a certain type + under a certain size
if user does not complete one of the requirements and clicks submit, the word "Required" appears next to the empty field
if selected file does not meet criteria, a different message appears
data is preserved in the fields that were filled in if the user left something blank and has to go back to fill it in.
when form submits, info goes into database + into an email
I am close but missing something. If I select a file that meets the requirements, the form submits even if the other fields are blank. As long as the form field is empty, the other fields behave correctly. What am I missing? I would appreciate any help. Thank you.
<?php require_once('../scripts/lcoa.php'); ?>
<?php
if (isset($_GET['jobid'])) {
$jobid = $_GET['jobid'];
}
if (isset($_GET['jobtitle'])) {
$jobtitle = $_GET['jobtitle'];
}
//This is the directory where resumes will be saved
$timestamp = time();
$folder = "../careers/resumes/";
$resume = ($_FILES['resume']['name']);
$target = $folder.basename($timestamp.$_FILES['resume']['name']);
$type = ($_FILES['resume']['type']);
$extension = strtolower(substr($resume, strpos($resume, '.') + 1));
$size = ($_FILES['resume']['size']);
$max_size = 3145728;
$name = ($_POST['name']);
$email = ($_POST['email']);
$phone = ($_POST['phone']);
$jobid = ($_POST['jobid']);
$jobtitle = ($_POST['jobtitle']);
$cover = ($_POST['coverletter']);
$error=array();
if(isset($name)){
if (empty ($name)){
$error['name']="<p class='error'>Required </p>";
}
}
if(isset($email)){
if (empty ($email)){
$error['email']="<p class='error'>Required </p>";
}
}
if(isset($phone)){
if (empty ($phone)){
$error['phone']="<p class='error'>Required </p>";
}
}
if(isset($cover)){
if (empty ($cover)){
$error['coverletter']="<p class='error'>Required </p>";
}
}
//Writes the resume to the server
if (isset ($resume)) {
if (empty ($resume)){
$error['resume']="<p class='error'>Resume Required </p>";
}
if (!empty ($resume)){
if(($extension=='doc'||$extension=='docx'||$extension=='txt'||$extension=='pdf')&&($type=='application/pdf'||'application/msword'||'application/vnd.openxmlformats-officedocument.wordprocessingml.document'||'text/plain')&&$size<=$max_size) {
if(move_uploaded_file($_FILES['resume']['tmp_name'], $target)) {
//Writes the information to the database
$insertSQL = "INSERT INTO applicants (id, name, email, phone, jobid, jobtitle, coverletter, resume) VALUES ('','".$_POST['name']."','".$_POST['email']."','".$_POST['phone']."','".$_POST['jobid']."','".$_POST['jobtitle']."','".$_POST['coverletter']."','".$resume."')";
mysql_select_db($database_lcoa, $lcoa);
$Result1 = mysql_query($insertSQL, $lcoa) or die(mysql_error());
//Sends Email
$sendto = "emailaddress";
$name = nl2br($_POST['name']);
$email = nl2br($_POST['email']);
$phone = nl2br($_POST['phone']);
$jobid = nl2br($_POST['jobid']);
$jobtitle = nl2br($_POST['jobtitle']);
$cover = nl2br($_POST['coverletter']);
$subject = "Submitted Job Application";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$headers = "From: " . strip_tags($email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>Job Application Submitted</h2>\r\n";
$msg .= "<p><strong>Applied for:</strong> ".$jobtitle."</p>\r\n";
$msg .= "<p><strong>Job ID:</strong> ".$jobid."</p>\r\n";
$msg .= "<p><strong>Applicant Name:</strong> ".$name."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$email."</p>\r\n";
$msg .= "<p><strong>Phone:</strong> ".$phone."</p>\r\n";
$msg .= "<p><strong>Cover Letter:</strong> ".$cover."</p>\r\n";
$msg .= "<a href='http://domain.com/".$target."'>Download Resume</a>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "";
} else {
echo "false";
}
//Tells you if its all ok
echo "<div id='confirm-app'><p>Thank you for submitting your application. Resumes submitted will be reviewed to determine qualifications that match our hiring needs.<br /><br /> If you are selected you will be contacted by a member of our recruiting team.</p><br /><br /><a href='../careers/job-postings.php'>Return to current opportunities</a></div>";
}
}
else {
//Gives and error if its not
echo "<p style='color: #6D6E71; font-family: Arial,Helvetica,sans-serif; font-size: 13px;'>We accept resumes in <strong>.doc</strong>, <strong>.docx</strong>, <strong>.pdf</strong>, or <strong>.txt</strong> formats, 3MB or less. Please <a href='javascript:history.back(-1);'>go back</a> to upload a file that meets these requirements.<br /><br />If you continue to experience errors, please report them.</p>";
die();
}
}
}
?>
You have to add one more condition near if (!empty ($resume)) that checks your $error array empty if not empty then print the errors else insert or email etc
if (!empty ($resume) && empty($error)){
//do your stuff
}else{
//display errors
}
you are only testing to see if if (!empty ($resume)){ and the requirements for the file before you execute the database insert and email sending. you will have to test for other elements being correct as well. Since you are building an array called $error you can test to see if empty($error) before performing the database insert and email.
Im using the php mail function to send a link with many many paramaters. The url after being encoded can be 650 or more characters long because its holding variables to repopulate a form.
When I click on the link in my email its broken because a space has been inserted somewhere in the URL.
Heres my sendMail function:
protected function sendEmail($to, $subject, $body) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . '\r\n';
$headers .= 'From: Sales Order From <sales#imninjas.com>' . '\r\n';
$headers .= 'X-Mailer: PHP/' . phpversion() . '\r\n';
$body = '<html><body style="font-size: 10pt; font-family: Arial, Helvetica, sans-serif;">'.$body.'</body></html>';
return mail($to, $subject, $body, $headers);
}
Heres the code I call sendMail with. Its the '$salesUrl = $this->getSalesFormUrl();' that is the 650+ character url chock full of encoded paramaters.
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$salesUrl."'>".$salesUrl."</a><br/><br/>";
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And here's the URL I receive in my email, you'll notice the space '...BhsNKq Jsd_x4...' in the middle of the URL. This happens in a different place each time even if I'm sending the exact same url. To prove this I hard coded this url without a space in the emailRep method and sent it multiple times. The space moved around.
http://example.com/admin/index.php?fdJdj9QgFAbgXzPcNJ3AAdbxgotxdk28cNRMjPESW9yihVbKxHR_vaeU7TSZxqSfHDhPX9Jg-lPneu1H9cFHE7yJxUcdfpto_XNxtv6XHkgw_Vk7oy7aFRdnYzONPDltWxV01Zi23glqnU-z91XnpvrnpvNGSXYo4Q0t6UEKUmUp9Sh28JC7Va01Pmaibcc83M8dpCzzKYn5H_rX_BhsNKq Jsd_x4w7e4zHqputSWdc1Uwzezt2LS5xGQJHKxlF98qbzUZMhauxw_k5ebK8YPwDFr776GEb11WPzGtfhjIFE68zL9H2l3FOCFXea5qkHUmO9pCihThlegDLAHamuIeCmTiXSGv8cm_TorL-6q8NnYuvp6nEfpntthgrvx3enkhWP-FJ0P4vYYAvyJ45pbR9slaw9pbPLsnu4d9nNZSuXJZdll2WXJRc2XKYgu0zRvcwuqBSVwuzylQu4ILugxOJCciG7kF1Qx8vjZl5Y8sIqL59dRu9dfnP5yuXJ5dnl2eXJ3crLl7x8lVeoFJWKe1co_uoK_B1eXZFckV2RXaG-fHvazCuWvGKVV84u23DlzZUrVyZXZldmVyZ3K69c8so57z8
Here is the code I use to encode / decode the url paramaters before sending it through the email.
class UrlEncoder {
function compressUrl($url) {
return rtrim(strtr(base64_encode(gzdeflate($url, 9)), '+/', '-_'), '=');
}
function uncompressUrl($url) {
$startParams = strrpos($url, "?");
if($startParams) {
$paramaterString = substr($url, $startParams);
$host = substr($url, 0, strrpos($url, "?"));
$uncompressedParamaters = gzinflate(base64_decode(strtr($paramaterString, '-_', '+/')));
return $host."?".$uncompressedParamaters;
} else {
return NULL;
}
}
}
How do I prevent this space? I know I could shorten the URL with something like bit.ly however its an internal tool. I feel like there must be a way to stop the space from being inserted.
Who in their right mind uses a 650-character long query string?
My recommendation is to save the query-string server-side. Put it in a database with an AUTO_INCREMENT field, then you can get an ID for it. Then you can just send the URL as http://example.com/?email_key=ID_GOES_HERE, a much shorter URL. Then just look up the query string from the database.
Done.
I have what you need, http://www.9lessons.info/2009/01/split-url-from-sentence-using-php.html. Create tinyurl links using API,nothing in the database :)
Ok,I had same issue. My solution was my own link shrinking... Make new table in database with few rows, few lines of code in your old script, and new page for redirect... This is shortest explanation, if you need some help,just ask :)
EDIT:
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
/***********************************************************************************/
$arr = str_split('QWERTYUIOPLKJHGFDSAZXCVBNM123456789qwertyuioplkjhgfdsazxcvbnm'); // get all the characters into an array
shuffle($arr); // randomize the array
$arr = array_slice($arr, 0, 6); // get the first six (random) characters out
$short = implode('', $arr); // smush them back into a string
mysql_query("INSERT INTO shortlinks VALUES(NULL, '$salesUrl', '$short')");
/*******************************************************************************************/
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$short."'>".$short."</a><br/><br/>"; // Rename $salesUrl to $short
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And redirect page:
$token=$_GET['token']; // like http://example.com/out.php?token=ahgByT or make it cleaner with htaccess
$qry=mysql_query("SELECT * FROM links WHERE short='$token'");
$arr=mysql_fetch_array($qry);
$out=$arr['long_link'];
header("Location: ".$out);
?>