Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Apr 2012
    Posts
    89
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Simple PHP OOP Contact Form

    Hello everyone,

    I am learning to code PHP in OOP style and I was wondering if I am on the right path. So far what I have made is the following. This is my contact.php form:

    Code:
    <?php
    require 'contact.class.php';
    ?>
    
    <form action="" method="post">
    
    <?php
    if (isset($_POST["submit"])) {
    
    $sendMail 		= new gw2Mail();
    
    $sendMail->senderName 	= $_POST['senderName'];
    $sendMail->senderEmail 	= $_POST['senderEmail'];
    $sendMail->recipient 	= $_POST['recipient'];
    $sendMail->copy 	= $_POST['copy'];
    $sendMail->subject 	= $_POST['subject'];
    $sendMail->message 	= $_POST['message'];
    
    $sendMail->sendMail();
    
    }
    ?>
    
    <table class='ipb_table ipsMemberList'>
    
    	<tr class='header' colspan='4'>
    		<th scope='col' colspan='5'>Send E-mail</th>
    	</tr>
    
    	<tr class='row1'>
    		<td style='width: 50%'><strong>From:</strong><br />Enter the sender's name in this field.</td>
    		<td><input type="text" class="input_text" name="senderName" id="senderName" value="<?php if (isset($_POST['senderName'])) { echo $_POST['senderName']; } ?>" size="50" maxlength="125" /></td>
    	</tr>
    
    	<tr class='row2'>
    		<td style='width: 50%'><strong>From E-mail:</strong><br />Enter the sender's e-mail address in this field.</td>
    		<td><input type="text" class="input_text" name="senderEmail" id="senderEmail" value="<?php if (isset($_POST['senderEmail'])) { echo $_POST['senderEmail']; } ?>" size="50" maxlength="125" /></td>
    	</tr>
    
    	<tr class='row1'>
    		<td style='width: 50%'><strong>Recipient:</strong><br />Enter the recipient's e-mail address in this field.</td>
    		<td><input type="text" class="input_text" name="recipient" id="recipient" value="<?php if (isset($_POST['recipient'])) { echo $_POST['recipient']; } ?>" size="50" maxlength="125" /></td>
    	</tr>
    
    	<tr class='row2'>
    		<td style='width: 50%'><strong>Carbon Copy:</strong><br />Send a copy to someone else? Enter another e-mail address here. Leave blank for no copy.</td>
    		<td><input type="text" class="input_text" name="copy" id="copy" value="<?php if (isset($_POST['copy'])) { echo $_POST['copy']; } ?>" size="50" maxlength="125" /></td>
    	</tr>
    
    	<tr class='row1'>
    		<td style='width: 50%'><strong>Subject:</strong><br />Enter a subject in this field.</td>
    		<td><input type="text" class="input_text" name="subject" id="subject" value="<?php if (isset($_POST['subject'])) { echo $_POST['subject']; } ?>" size="50" maxlength="50" /></td>
    	</tr>
    
    	<tr class='row2'>
    		<td colspan='2' style='width: 100%'><textarea style="height: 250px; width: 99%;" name="message" id="message" cols="30" rows="14" virtual wrap="on"><?php if (isset($_POST['message'])) { echo $_POST['message']; } ?></textarea></td>
    	</tr>
    
    </table>
    
    <input type="submit" name="submit" value="Submit" tabindex="50" class="input_submit" accesskey="s" />
    
    </form>
    And here is the class:

    PHP Code:
    <?php

    class gw2Mail {

        var 
    $senderName;
        var 
    $senderEmail;
        var 
    $recipient;
        var 
    $copy;
        var 
    $subject;
        var 
    $message;
        var 
    $bcc;

        public function 
    sendMail()
        {
                if (
    $this->senderName != "") {
                    
    $this->senderName filter_var($this->senderNameFILTER_SANITIZE_STRING);
                    if (
    $this->senderName == "") {
                        
    $errors .= '- Please enter a valid name!';
                    }
                } else {
                    
    $errors .= '- You forgot to enter a name!<br />';
                }

                if (
    $this->senderEmail != "") {
                    
    $this->senderEmail filter_var($this->senderEmailFILTER_SANITIZE_STRING);
                    if (
    $this->senderEmail == "") {
                        
    $errors .= '- Please enter a valid Email!';
                    }
                } else {
                    
    $errors .= '- You forgot to enter an email!<br />';
                }

                if (
    $this->recipient != "") {
                    
    $this->recipient filter_var($this->recipientFILTER_SANITIZE_STRING);
                    if (
    $this->recipient == "") {
                        
    $errors .= '- Please enter a valid recipient email!';
                    }
                } else {
                    
    $errors .= '- You forgot to enter a recipient email!<br />';
                }

                if (
    $this->subject != "") {
                    
    $this->subject filter_var($this->subjectFILTER_SANITIZE_STRING);
                    if (
    $this->subject == "") {
                        
    $errors .= '- Please enter a valid subject!';
                    }
                } else {
                    
    $errors .= '- You forgot to enter a subject!<br />';
                }

                if (
    $this->message != "") {
                    
    $this->message filter_var($this->messageFILTER_SANITIZE_STRING);
                    if (
    $this->message == "") {
                        
    $errors .= '- Please enter a valid message!';
                    }
                } else {
                    
    $errors .= '- You forgot to enter a message!<br />';
                }

                if (!
    $errors) {

                
    $this->bcc="";

                
    $headers "From: $this->senderName <$this->senderEmail>";
                
    $headers .= "\r\nCc: $this->copy";
                
    $headers .= "\r\nBcc: $this->bcc\r\n\r\n";

                
    $send_contact=mail("$this->recipient","$this->subject","$this->message","$headers");

                } else {
                echo 
    '<p class=\'message error\'>';
                echo 
    '<font color="#FFFFFF">' $errors '</font>';
                echo 
    '</p><br />';
                }
        }
        }
    ?>
    But I feel that my code isn't really that much object oriented, or is it? There is a small piece of "styling" in it aswell, the "message error" thing at the end. Should that be in my class or should it go somewhere else? Any pointers would be helpful

    Thanks in advance!
    Last edited by Hardist; 03-16-2014 at 07:44 PM.

  • #2
    New Coder
    Join Date
    Apr 2012
    Posts
    89
    Thanks
    15
    Thanked 0 Times in 0 Posts
    Right, I have updated the above code as I "finished" it, for testing purposes and learning purposes. If anyone has any comments about it, please let me know.

    Thanks in advance!

  • #3
    New Coder
    Join Date
    Dec 2011
    Posts
    87
    Thanks
    5
    Thanked 14 Times in 14 Posts
    First, I just say if it works then don't take a hammer to it.

    Second, I have jQuery check form validation and have PHP as backup (catch things at the server-side), this way it give the user a better web experience for your website.

    Third, I keep PHP limited, but this is my own personal preference. Here's a couple of routines using OOP.

    PHP Code:
        // Method returns a Boolean if the user's email is valid:
        
    public function hasValidEmail() {
            return (!
    filter_var($this->emailFILTER_VALIDATE_EMAIL));
        } 
    That way I can call it this way:
    PHP Code:
        if ($guest->hasValidEmail()) {
            
    $errorMsg[3] = 'Email is invalid, please re-enter.';
            
    $flag true;
        } 
    This way I can change the message depending on where I'm using it, for example it might be a registration page or a contact page. I have routines for username, username availability, etc.

    Another example of using username availability:
    PHP Code:
        // Method checks to see if username isn't already taken and returns true if it is already taken:
        
    public function isUsernameAvailable() {

            
    // Connect to PDO database:
            
    $db Database::getInstance();
            
    $pdo $db->getConnection();

            
    $query "
                SELECT
                    1
                FROM users
                WHERE
                    username = :username1
            "
    ;

            
    $query_params = array(
                
    ':username1' => $this->username
            
    );

            
    // These two statements run the query against your database table.
            
    $stmt $pdo->prepare($query);
            
    $result $stmt->execute($query_params);

            
    // The fetch() method returns an array representing the "next" row from
            // the selected results, or false if there are no more rows to fetch.              
            
    return $row $stmt->fetch();
            
    // If a row was returned, then we know a matching username was found in
            // the database already and we should return a boolean value back.       
        

    Though I have since found something better, I also check at saving time:
    PHP Code:
            $query 'INSERT INTO users (userType, username, email, pass, validation_code, dateAdded) VALUES (:userType, :username, :email, :pass, :validation_code, NOW())';
            
    $stmt $pdo->prepare($query);
            try {
                
    $result $stmt->execute(array(':userType' => $guest->userType':username' => $guest->username':pass' => $guest->pass':validation_code' => $user_verification':email' => $guest->email));
                
    $sendMail = new Verification();
                
    $result $sendMail->email_method($guest->email$user_verification);
            } catch (
    PDOException $error) {
                if (
    substr($error->getCode(), 02) == SQL_CONSTRAINT_VIOLATION) {
                    
    $errorMsg[5] = 'The username already exists.';
                } else {
                    throw 
    $error// some other error happened; just pass it on.    
                
    }
            } 
    Though that is more for a registration page.

    That to me is where the power of php comes into play, for it checks the server side of things where plain old JavaScript can perform most of the mundane tasks on the client side.
    Last edited by Strider64; 03-17-2014 at 04:51 PM.
    True courage is about knowing not when to take a life, but when to spare one. PDO Tutorial

  • Users who have thanked Strider64 for this post:

    Hardist (03-17-2014)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •