Critical: E-mail script not mailing (i think)

dragonpimpsta

New Member
Messages
31
Reaction score
0
Points
0
I think this problem is happening with the mail server here somehow. I have a registration script for a tournament thats happening next Saturday. Lots of people register online and it emails me their information so we can plan for them coming. It also emails them saying they are confirmed.

RECENTLY, i tested it and it works as if it was successful but then it doesnt email their information to me. It has worked up until now... maybe the emails are delayed by a few hours??

Does anyone know a way i can check in cpanel for attempted sent messages?

Information:

it sends the emails from this addresss: jreed3s@web5.vital.x10hosting.com
my account is redhawksracquetball.x10hosting.com (It's the script at the beginning of the page)

here's the code:
PHP:
<?php
// Website Contact Form Generator
// http://www.tele-pro.co.uk/scripts/contact_form/
// This script is free to use as long as you
// retain the credit link

// get posted data into local variables
$EmailFrom = Trim(stripslashes($_POST['EmailFrom']));
$EmailTo = "fakeemail@gmail.com";
$FirstName = Trim(stripslashes($_POST['FirstName']));
$LastName = Trim(stripslashes($_POST['LastName']));
$Subject = "Rball_Registration";
$Tel = Trim(stripslashes($_POST['Tel']));
$Division = Trim(stripslashes($_POST['division']));
$Adv = Trim(stripslashes($_POST['adv']));



// validation
$validationOK=true;
if (Trim($EmailFrom)=="") $validationOK=false;
if (Trim($FirstName)=="") $validationOK=false;
if (Trim($LastName)=="") $validationOK=false;
if (!$validationOK) {
  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
  exit;
}

// prepare email body text
$Body = "";
$Body .= "FirstName: ";
$Body .= $FirstName;
$Body .= "\n";
$Body .= "LastName: ";
$Body .= $LastName;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Division: ";
$Body .= $Division;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $EmailFrom;
$Body .= "\n";
$Body .= "Advertising: ";
$Body .= $Adv;

// send email
$success = mail($EmailTo, $Subject, $Body);

$Confirmation = "";
$Confirmation .= "Thanks for Registering!!";
$Confirmation .= "\n";
$Confirmation .= $FirstName . ", You have successfully registered for the Redhawks Racquetball Tournament on -November 20th-.";
$Confirmation .= "\n";
$Confirmation .= "You can check the registered list on the website to make sure you are included sometime tomorrow.";
$Confirmation .= "\n";
$Confirmation .= "Please remember matches begin at -10:00am-.";



// redirect to success page
if ($success){
  mail($EmailFrom, "Redhawks Racquetball Tournament", $Confirmation);
  print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www6.semo.edu/rball/thankyou.htm\">";
}
else{
  print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www6.semo.edu/rball/error.htm\">";
}
?>

Last piece of info--- The page at http://redhawksracquetball.x10hosting.com/ sends form data to that script i posted above.
I'd really appreciate any help.
 
Last edited:

bdistler

Well-Known Member
Prime Account
Messages
3,534
Reaction score
196
Points
63
I assume you used your real Email address if you did - edit your post and replace it
with a dummy like "myemail@mailbox.net" or something this is to cut down on the
spam you received

PHP mail on x10Hosting free servers is NOT a 100% when it returns 'TRUE'
more like 75% - 80% during the good part of the day the rest of the time
your Email goes into the bit bucket never to be seen again.

What I use is - PHP mail - PHP (flat) log file - MySQL database
send to all 3 and hope to get one or more

maybe the emails are delayed by a few hours??
I have had delays of more then 24 hours on my x10Hosting paid server

Does anyone know a way i can check in cpanel for attempted sent messages?
IF you have 'logs' on your server - the mail logs are the only place I know to look

After you PHP-mail put all the data in a PHP (flat) file - you will have to read it by hand
from cPanel or FTP down load it to your desktop to read - better then lost registration

If you need help post back to this thread

BTW I would replace "\n" with "\r\n"
 
Last edited:

dragonpimpsta

New Member
Messages
31
Reaction score
0
Points
0
I need help :(. I'll just hope that people register in the 70% of the time it works. What exact file would have the email messages to read on the access logs? There are millions of little files!

This does help a lot! Thanks

EDIT: i added a script to also add the entries into a mySQL database and even that wont work.. The script works im sure, but it's just not happening

PHP:
//insert into database
$username="********";
$password="********";
$database="jreed3s_registry";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
mysql_query($query);
$query = "INSERT INTO registered VALUES ('',$EmailFrom,$FirstName,$LastName,$Tel,$Division,$Adv,'')";
 
Last edited:

bdistler

Well-Known Member
Prime Account
Messages
3,534
Reaction score
196
Points
63
Here is a PHP script to test your MySQL database
It is for a programer to use and not for end user
Enter your database info near the top

PHP:
<?php
// THIS IS A TEST PHP SCRIPT TO TEST CONNECTING TO YOUR MySQL DATABASE
// DO NOT INCORPORATE INTO YOUR SITE UNTIL YOU HANDLE ERRORS AND 'PASSWORD' TYPE DATA in THE APPROPRIATE WAY
//
// was tested on servers skyy, and boru at x10hosting
//
// Make sure any PHP files have permissions set to 0644 (NOT 0666 or 0777) and subdirectories set to 0755
//
// There is a possibility your .htaccess file can cause problems
// some .htaccess directives that work on other sites do not work on x10Hosting 'free' sites
// cPanel's "IP Deny Manager" on x10Hosting 'free' sites makes the wrong code
//
// Some say x10hosting server boru is haunted.
//

$serverName = "localhost"; // MySQL server name
$user_name = "myCpanelName_databaseUsername"; // MySQL user name _ do not forget the underscore
$password = "myDatabasePassword"; // MySQL password
$db_name = "myCpanelName_databaseName"; // MySQL Database name - do not forget the underscore
$tableName = "tableName"; // MySQL Table name

// try get "MySQL link identifier"
$dbConn = mysql_connect($serverName, $user_name, $password) or die("Cannot connect to server<br />\n MySQL error ==>" . mysql_errno() . "<== : ==>" . mysql_error() . "<== <br />\n");
print "Connected to MySQL server successfully<br />\n";

// try connect to database
mysql_select_db($db_name, $dbConn) or die("Cannot connect to database<br />\n MySQL error ==>" . mysql_errno($dbConn) . "<== : ==>" . mysql_error($dbConn) . "<== <br />\n");
print "Connected to database successfully<br />\n";

// try to get info from table
$query = 'SELECT * FROM ' . $tableName . ' LIMIT 0, 1';
$result = mysql_query($query, $dbConn) or die("Cannot select anything from table<br />\n MySQL error ==>" . mysql_errno($dbConn) . "<== : ==>" . mysql_error($dbConn) . "<== <br />\n");

print "I connected to your server, connected to your database, and received info from your table<br />\n";
?>
I will get back here with a update to dragonpimpsta script
 

bdistler

Well-Known Member
Prime Account
Messages
3,534
Reaction score
196
Points
63
Here is a TEST script it MUST be 'debugged'

PHP:
<?php
// THIS IS A TEST SCRIPT AND NEEDS TO BE TESTED AND DEBUGGED BEFORE A USER GETS IT

// undo the effects of magic quotes if they are in effect
function stripslashes_nested($v)
  {
    if (is_array($v))
      {
        return array_map('stripslashes_nested', $v);
      } else
        {
          return stripslashes($v);
        }
  }

$debugPrint = FALSE;
//rem next line to NOT print debug
$debugPrint = TRUE;

// ============================
// info for MySQL database

$serverName = "localhost"; // MySQL server name
$user_name = "myCpanelName_databaseUsername"; // MySQL user name _ do not forget the underscore
$password = "myDatabasePassword"; // MySQL password
$db_name = "myCpanelName_databaseName"; // MySQL Database name - do not forget the underscore

// Assume one column in table as type = text
$tableName = "tableName"; // MySQL Table name

// ============================
// info for Email

// This Email address should be at your site
// most Email clients (AOL, Yahoo, Gmail) will drop or return Email from x10Hosting 'free' servers
$EmailTo = "fakeemail@gmail.com"; // **** set this to true Email address ****

// with luck if Email is returned from "$EmailTo" - "$LogKeeper" will get the notice
$LogKeeper = "me@mysite.com"; // **** set this to Email account at your site ****

// to send a 'Cc' - remove rem at "$additional_headers" below
$EmailCcTo = "me@myOtherDomain.com"; // **** set this to Email a copy to 'Cc:' ****

$Subject = "Rball_Registration";
$validationOK = TRUE;
$hourdiff = 4; // hours def your place from server

$postTime = date("Y/m/d H:i:s",time() - ($hourdiff * 3600)) // set the '-' to '+' if you place is East of server

// ============================
// prevent SQL Injection Attack with data sent to MySQL database from data passed to us via $_POST

if (get_magic_quotes_gpc())
  {
    // if PHP "Magic Quotes" is set 'on' undo the effects of "Magic Quotes" on $_POST
    $_POST = stripslashes_nested($_POST);
  }

// mysql_real_escape_string($value) will NOT backslashes "`" (next to far let "1" key on USA key broads
// so after "mysql_real_escape_string($value)" use "$value = str_replace("`","\`",$value);"
// and get posted data into local variables

// Validation here is 'top down' programing you might like loop-de-loop

if ((isset($_POST['$EmailFrom'])) && (!empty($_POST['$EmailFrom'])))
  {
    $EmailFrom = mysql_real_escape_string(trim($_POST['$EmailFrom']));
    $EmailFrom = str_replace("`", "\`", $EmailFrom);
    // test for what you think should be in $EmailFrom
    if ($EmailFrom == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if ((isset($_POST['$FirstName'])) && (!empty($_POST['$FirstName'])))
  {
    $FirstName = mysql_real_escape_string(trim($_POST['$FirstName']));
    $FirstName = str_replace("`", "\`", $FirstName);
    // test for what you think should be in $FirstName
    if ($FirstName == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if ((isset($_POST['$LastName'])) && (!empty($_POST['$LastName'])))
  {
    $LastName = mysql_real_escape_string(trim($_POST['$LastName']));
    $LastName = str_replace("`", "\`", $LastName);
    // test for what you think should be in $LastName
    if ($LastName == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if ((isset($_POST['$Tel'])) && (!empty($_POST['$Tel'])))
  {
    $Tel = mysql_real_escape_string(trim($_POST['$Tel']));
    $Tel = str_replace("`", "\`", $Tel);
    // test for what you think should be in $Tel
    if ($Tel == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if ((isset($_POST['$Division'])) && (!empty($_POST['$Division'])))
  {
    $Division = mysql_real_escape_string(trim($_POST['$Division']));
    $Division = str_replace("`", "\`", $Division);
    // test for what you think should be in $Division
    if ($Division == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if ((isset($_POST['$Adv'])) && (!empty($_POST['$Adv'])))
  {
    $Adv = mysql_real_escape_string(trim($_POST['$Adv']));
    $Adv = str_replace("`", "\`", $Adv);
    // test for what you think should be in $Adv
    if ($Adv == "") $validationOK = FALSE;
  }
  else
    {
      $validationOK = FALSE;
    }

if (!$validationOK)
  {
    // redirect for error page
    if ($debugPrint) print "FALSE validation<br>\n";
    print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
    EXIT;
  }

// ============================
// We have data so set up Email

// prepare email body text
$Body = "FirstName: ";
$Body .= $FirstName;
$Body .= "\r\n";
$Body .= "LastName: ";
$Body .= $LastName;
$Body .= "\r\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\r\n";
$Body .= "Division: ";
$Body .= $Division;
$Body .= "\r\n";
$Body .= "Email: ";
$Body .= $EmailFrom;
$Body .= "\r\n";
$Body .= "Advertising: ";
$Body .= $Adv;
$Body .= "\r\n";
$Body .= $postTime;

$additional_headers = 'From: ' . $EmailFrom . "\r\n" . 'Reply-To: ' . $LogKeeper;

// $additional_headers .= "\r\n" . 'Cc: ' . $EmailCcTo; // **** remove the rem on this line to send a Cc: ****

$additional_headers .= "\r\n";

// try to send Email
$success = mail($EmailTo, $Subject, $Body, $additional_headers);

// send email
if (mail($EmailTo, $Subject, $Body))
  {
    $Confirmation = "Thanks for Registering!!";
    $Confirmation .= "\r\n";
    $Confirmation .= $FirstName . ", You have successfully registered for the Redhawks Racquetball Tournament on -November 20th-.";
    $Confirmation .= "\r\n";
    $Confirmation .= "You can check the registered list on the website to make sure you are included sometime tomorrow.";
    $Confirmation .= "\r\n";
    $Confirmation .= "Please remember matches begin at -10:00am-.";

    if (!mail($EmailFrom, "Redhawks Racquetball Tournament", $Confirmation))
      {
        // redirect for error page            **** You may like to change this if error on send confirmation ****
        if ($debugPrint) print "confirmation Email to " . $EmailFrom . " error<br>\n";
        print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www6.semo.edu/rball/error.htm\">";
      }

    // redirect for success page
    print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www6.semo.edu/rball/thankyou.htm\">";
  }
  else
    {
      // redirect for error page
      if ($debugPrint) print "confirmation Email to " . $EmailTo . " error<br>\n";
      print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www6.semo.edu/rball/error.htm\">";
    }

// ============================
// sent Email now put copy of data into log file

$output = $Body;
$output .= "\r\n";

// Write Email info to log file
// use 'a' to open for writing only; place the file pointer at the end of the file.
// If the file does not exist, attempt to create it.
//
// use 'b' to force binary mode
//
// If the open fails, an error of level E_WARNING is generated. Use @ to suppress this warning.
//

if (!$logFile = fopen("registered.log","ab")) // **** look for this file in dir where this script runs ****
  {
    // you may rem out these two lines and/or make some other error for user
    if ($debugPrint) print "Cannot open log file<br>\n";
    if ($debugPrint) EXIT; // this will be full stop error or rem out so user will not see it
  }
  else
    {
      if (fwrite($logFile,$output) === FALSE) // note the '===' and not '=='
        {
          // you may rem out these two lines and/or make some other error for user
          if ($debugPrint) print "Cannot write to log file<br>\n";
          if ($debugPrint) EXIT; // this will be full stop error or rem out so user will not see it
        }
    }

fclose($logFile);

// ============================
// now put copy into MySQL database

// try get "MySQL link identifier"
if ($dbConn = mysql_connect($serverName, $user_name, $password))
  {
    if ($debugPrint)
      {
        print "Cannot connect to server<br />\n MySQL error ==>" . mysql_errno() . "<== : ==>" . mysql_error() . "<== <br />\n");
        EXIT;
      }
      else
        {
          if ($debugPrint) print "Connected to MySQL server successfully<br />\n";
        }

// try connect to database
if (!mysql_select_db($db_name, $dbConn))
  {
    if ($debugPrint)
      {
        print "Cannot connect to database<br />\n MySQL error ==>" . mysql_errno($dbConn) . "<== : ==>" . mysql_error($dbConn) . "<== <br />\n");
        EXIT;
      }
  }
  else
    {
      if ($debugPrint) print "Connected to database successfully<br />\n";
    }

// try to get info from table
//assume one column in table as type = text
$query = "INSERT INTO " . $tableName . " VALUES (" . $output . ")";

// INSERT INTO $tableName
$result = mysql_query($query, $dbConn);

if (!$result)
  {
    if ($debugPrint)
      {
        print "Cannot add data to database<br />\n MySQL error ==>" . mysql_errno($dbConn) . "<== : ==>" . mysql_error($dbConn) . "<== <br />\n");
        EXIT;
      }
  }
  else
    {
      if ($debugPrint) print "Data added to database<br />\n";
    }

?>
If you find any errors post them here so we can all see them
 

dragonpimpsta

New Member
Messages
31
Reaction score
0
Points
0
Those emails from yesterday FINALLY sent. (or maybe the same people tried again) but i recieved all my test messages. that was the 24hr delay you were talking about. The mySQL stuff still doesnt work, but i havent tried the test script yet so i probably did something wrong. I'll post updates soon
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
No sir, I don't like it.

See "Re: Display all that would be secret while Mysql is broken" for an implementation of LocalDB used in the following. LocalDB is used to isolate DB user credentials, reducing typo and security problems.

Here's a rewrite of bdistler's latest script, with various improvements. It's based on PDO rather than the outdated mysql driver. It doesn't repeat itself and some of the code has been moved to separate scripts, both of which makes it more reusable, though it could be more so (for example, the form in the registration page is separate from the form in the handler page; the two could be united so the form is defined just once, rendering it on the registration page and processing it on the handler page). There are still quite a few improvements to make, portions to fill out and testing to be done.

The library scripts:
PHP:
<?php // normal_quotes.php
// undo the effects of magic quotes if they are in effect
function stripslashes_nested(&$v) {
    if (is_array($v)) {
        return array_map('stripslashes_nested', $v);
    } else {
        return $v = stripslashes($v);
    }
}

if (get_magic_quotes_gpc()) {
    // if PHP "Magic Quotes" is set 'on' undo the effects of "Magic Quotes" on $_POST
    foreach (array('_GET', '_POST', '_COOKIE', '_REQUEST') as $k) {
        stripslashes_nested($GLOBALS[$k]);
    }
}

PHP:
<?php // dbg.php
$dbgLvl = 0;

function dbgMsg($lvl) {
    global $dbgLvl;

    $msgs = func_get_args();
    if (is_int($lvl)) {
        array_shift($msgs);
    } else {
        $lvl = 1;
    }
    if ($lvl <= $dbgLvl) {
        print implode('', $msgs);
    }
}

PHP:
<?php //FormData.php
// should be further broken up into separate scripts

if (is_null(constant('INPUT_REQUEST'))) {
    define('INPUT_REQUEST', max(INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV)+1);
}

function &getInputSource($source) {
    switch ($source) {
    case INPUT_GET:
        return $_GET;
            
    case INPUT_COOKIE:
        return $_COOKIE;
            
    case INPUT_SERVER:
        return $_SERVER;
            
    case INPUT_ENV:
        return $_ENV;
            
    case INPUT_REQUEST:
        return $_REQUEST;
            
    case INPUT_POST:
    default:
        return $_POST;
    }
}
    
// each of these Field classes should be placed in its own file
class FormField {
    public $name, $type, $label, $param, $options, $error;
    protected $_source, $_input;
    static $types = array();
    
    static function create($name, $opts) {
        if (isset(self::$types[$opts['type']])) {
            $class = self::$types[$opts['type']];
        } else {
            $class = __CLASS__;
        }
        return new $class($name, $opts);
    }

    static function registerField($type, $class) {
        self::[$types] = $class;
    }

    function __construct($name, $opts) {
        $this->name = $name;
        $this->type = $opts['type'];
        $this->source = $opts['source'];
        $this->options = $opts;
        if (isset($opts['param'])) {
            $this->param = $opts['param'];
        } else {
            $this->param = ":{$this->name}";
        }
        if (isset($opts['label'])) {
            $this->label = $opts['label'];
        } else {
            $this->label = $this->name;
        }
    }

    function __get($key) {
        switch($key) {
        case 'value':
            return $this->_input[$this->name];
        case 'source':
            return $this->_source;
        default:
            if (isset($this->options[$key])) {
                return $this->options[$key];
            }
            break;
        }
    }
    function __set($key, $value) {
        switch($key) {
        case 'value':
            $this->_input[$this->name] = $value;
            break;

        case 'source':
            $this->_source = $value;
            $this->_input =& getInputSource($this->source);
            break;
        }
    }

    function validate() {
        if (FALSE === ($result = filter_input($this->source, $this->name, $this->type, $this->options))) {
            $this->setInvalidError();
        }
        if (is_null($result)) {
            $this->setBlankError();
        }
        return $result;
    }
    function setInvalidError($value=Null) {
        if (is_null($value)) {
            $value = $this->value;
        }
        $this->error = "{$this->value} isn't a valid {$this->label}";
    }

    function setBlankError() {
        $this->error = "{$this->label} can't be blank.";
    }
}

class NonemptyField extends FormField {
    function validate() {
        if (empty($this->value)) {
            $this->setBlankError();
            return False;
        }
        return True;
    }

    static function initialize() {
        static $shouldInit=True;
        if ($shouldInit) {
            $shouldInit=False;
            FormField::register('nonempty', __CLASS__);
        }
    }
}
NonemptyField::initialize();


class PhoneField extends FormField {
    public $value;
    static public $patterns = array(
        'US' => '/^(1?\d{3})?\d{7}$/',
        'UK' => '/^(\+44|0)([1-358-9]\d|60|7[05-9])\d{7,8}$/',
        '' => '/^((1?\d{3})?\d{7}|(\+44|0)([1-358-9]\d|60|7[05-9])\d{7,8})$/'
        );

    function __construct($name, $opts) {
        parent::__construct($name, $opts);
        $this->value = preg_replace('/\D+/', '', $this->originalValue);
        if (isset($opts['country'])) {
            $this->country = $opts['country'];
        } else {
            $this->country = '';
        }
    }

    function __get($key) {
        switch ($key) {
        case 'pattern':
            return self::$patterns[$this->country];
        case 'originalValue':
        default:
            return parent::__get($key);
        }
    }

    function __set($key, $value) {
        switch ($key) {
        case 'country':
            $value = strtoupper($value);
            if (isset($patterns[$value])) {
                $this->opts['country'] = $value;
            } else {
                $this->opts['country'] = '';
            }
            break;
        default:
            parent::__set($key, $value);
            break;
        }
    }


    function validate() {
        if (! preg_match($this->pattern, $this->value)) {
            $this->setBlankError($this->originalValue);
            return False;
        }
        return True;
    }

    static function initialize() {
        static $shouldInit=True;
        if ($shouldInit) {
            $shouldInit=False;
            FormField::register('phone', __CLASS__);
        }
    }

}
PhoneField::initialize();



class FormData {
    private $fields, $source, $input;
    public $errors;
    function __construct($fields, $source=INPUT_POST) {
        $this->fields = array();
        foreach ($fields as $name => $field) {
            if (is_array($field)) {
                $fields[$name] = FormField::create($name, $field);
            } elseif (is_object($field)) {
                $fields[$name] = $field;
            } else {
                $fields[$name] = FormField::create($name, array('source' => $source, 'type' => $field));
            }
        }
        $this->source = $source;
        $this->input =& getInputSource($source);
        $this->errors = array();
        $this->validate();
    }

    function validate() {
        foreach ($this->fields as $name => $field) {
            if (! $field->validate()) {
                $failed[] = $field;
            }
        }
        return $failed;
    }

    function getValue($name) {
        if (isset($this->fields[$name])) {
            return $this->fields[$name]->value;
        }
    }
    
    function toParamArray() {
        $params = array();
        foreach ($this->fields as $name => $field) {
            $params[$field->param] = $field->value;
        }
        return $params;
    }

    function columns() {
        $fields = array();
        foreach ($this->fields as $name => $field) {
            $fields[] = $field->column;
        }
    }

    function columnsString() {
        return '`' . implode('`, `', $this->fieldList()) . '`';
    }

    // should probably be abstracted into a data access layer
    function store($dbConn, $dbName, $table) {
        $params = $this->toParamArray();
        $query = $db->prepare("INSERT INTO `$dbName`.`$table` ({$this->columnsString()}) VALUES (" 
                              . implode(', ', array_keys($params)) . ')');
        return $query->execute($params);
    }
}


The form handling script is to follow.
 
Last edited:

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Finally, the registration script:

PHP:
<?php
# THIS IS A TEST SCRIPT AND NEEDS TO BE TESTED AND DEBUGGED BEFORE A USER GETS IT

include_once('dbg.php');

include_once('LocalDB.php');
include_once('normal_quotes.php');
include_once('FormData.php');

//$dbgLvl = 1; # uncomment to debug

$fields = new FormData(
    array(
        'EmailFrom' => array('type'=>FILTER_VALIDATE_EMAIL, 
                             'param' => ':email', 'label' => 'e-mail'), 
        'FirstName' => array('type' => 'nonempty', 
                             'param' => ':first', 'label' => 'first name'), 
        'LastName' => array('type' => 'nonempty', 
                            'param' => ':last', 'label' => 'last name'), 
        'Tel' => array('type' => 'phone', 
                       'param' => ':phone', 'label' => 'phone number'), 
        'division' => array('type' => 'nonempty', 
                            'param' => ':div', 'label' => 'division'),
        'adv' => array('type' => 'nonempty', 
                       'param' => ':adv', 'label' => 'advertising')
        ));


# ============================
# info for MySQL database

$opts = array(
    'db' => "myCpanelName_databaseName", # MySQL Database name - do not forget the underscore
    'table' => "tableName", # MySQL Table name
    'errorURL' => 'http://www6.semo.edu/rball/error.htm',
    'successURL' => 'http://www6.semo.edu/rball/thankyou.htm',
    'event' => 'Redhawks Racquetball Tournament',
    'date' => 'November 20th',
    'timezone' => 'America/Chicago', # tournament isn't in Chicago, but is in same timezone
    'startTime' => '10:00am'
    );

date_default_timezone_set($opts['timezone']);
$postTime = strftime('%F %T');

# ============================
# info for Email

$mail = array(
    # This Email address should be at your site
    # most Email clients (AOL, Yahoo, Gmail) will drop or return Email from x10Hosting 'free' servers
    'to' => "fakeemail@gmail.com", # **** set this to true Email address ****

    # with luck if Email is returned from "$to" - "$logKeeper" will get the notice
    'logKeeper' => "me@mysite.com", # **** set this to Email account at your site ****

    # to send a 'cc' - uncomment & set following
    //'ccTo' => "me@myOtherDomain.com", # **** set this to Email a copy to 'Cc:' ****

    'subject' => "Rball_Registration",
    );

if ("\n" == "\xD\xA") {
    $eol="\n";
    $cr=''
} else {
    $eol="\r\n";
    $cr="\r";
}

function fail($msg) {
    /* TODO: failure should give better feedback, perhaps by passing a message (via a cookie?)
     through to the error page.
     */
    global $opts;
    header("Location: $opts[errorURL]");
    dbgMsg($msg);
}

function succeed($msg) {
    global $opts;
    header("Location: $opts[successURL]");
    dbgMsg($msg);   
}

# Form processing starts here
if (($failed = $fields->validate())) {
    # TODO: tell user why validation failed.
    fail("Input failed validation.");
} else {
    $who = "_POST[FirstName] $_POST[LastName]";
    $mail['from'] = $fields->getValue('EmailFrom');
    # ============================
    # We have data so set up Email

    # prepare email body text. _POST has been sanitized.
    $Body = <<<EOF
FirstName: $_POST[FirstName]$cr
LastName: $_POST[LastName]$cr
Tel: $_POST[Tel]$cr
Division: $_POST[division]$cr
Email: $_POST[EmailFrom]$cr
Advertising: $_POST[adv]$cr
$postTime$cr
EOF;

    $additional_headers = "From: $mail[from]${eol}Reply-To: $mail[logKeeper]${eol}";

    if (isset($mail['ccTo'])) {
        $additional_headers .= "Cc: $mail[ccTo]${eol}";
    }

    # send email
    if (mail($mail['to'], $mail['subject'], $Body, $additional_headers)) {
        /* TODO: fix the name used to address a registrant. 
         The first name isn't necessarily the short form a person's name, depending on 
         their culture. However, someone living in the US will probably follow western
         naming conventions, and in some cultures that don't use western conventions
         (e.g. Japanese), the first name can still be used as a short form of address.
        */
        $Confirmation = <<<EOF
Thanks for Registering!!
$FirstName, You have successfully registered for the $opts[event] on -$opts[date]-.
You can check the registered list on the website to make sure you are included sometime tomorrow.
Please remember matches begin at -$opts[startTime]-.
EOF;

        if (mail($mail['from'], $opts['event'], $Confirmation)) {
            succeed();
        } else {
            fail("Sending confirmation e-mail to $mail[from] failed\n");
        }
    } else { # !mail($mail['to'], ...
        fail("Sending information e-mail to $mail[to] failed\n");
    }

    # ============================
    # sent Email now put copy of data into log file

    # Write Email info to log file
    # use 'a' to open for writing only; place the file pointer at the end of the file.
    # If the file does not exist, attempt to create it.
    #
    # use 'b' to force binary mode
    #
    # If the open fails, an error of level E_WARNING is generated. Use @ to suppress this warning.
    #

    if (!($logFile = fopen("registered.log","ab"))) { # **** look for this file in dir where this script runs ****
        # you may rem out these two lines and/or make some other error for user
        dbgMsg("Cannot open log file\n");
        if ($dbgLvl) exit(); # this will be full stop error or rem out so user will not see it
    } else {
        $output = "---Registration for $who---$eol$Body$eol";
        if (fwrite($logFile,$output) === FALSE) { # note the '===' and not '=='
            # you may rem out these two lines and/or make some other error for user
            dbgMsg("Cannot write to log file<br>\n");
            if ($dbgLvl) exit(); # this will be full stop error or rem out so user will not see it
        }
        fclose($logFile);
    }

    # ============================
    # now put copy into MySQL database

    try {
        $stage = 'connecting to database';
        $db = LocalDB::connect($opts['db']);
        
        dbgMsg("Connected to MySQL server successfully\n");

        $stage = 'saving  to database';
        $fields->store($db, $opts['db'], $opts['table']);
        dbgMsg("Data added to database");
    } catch (PDOException $exc) {
        dbgMsg("Error when $stage.");
        # TODO: better error logging
        error_log("Error storing registration for $who: $exc");
    }
}
?>
 
Top