Jump to content

Recommended Posts

Hello,

 

I am trying to add a contactform to my page for quite a while now, and just a few days ago, I came across a - in my opinion - quite helpful template (see hereunder). The remarks and such are in Dutch, I hope that it won't be too confusing... Eventually, I would like to upload the "visible" part of the contactform to www.mysite.nl/contactformulier.php.

 

Could someone please tell me which parts of the template I should save in which file?

 

Thanks so much in advance.

 

Anthony

 

PS: If the Dutch language is confusing, I'm obviously more than willing to translate the confusing parts.

 

 <?php
////////////////////////////////////////////////
/// Contact formulier met formherhaling
/// Gemaakt door Sebazzz
/// xhtml compatible
///////////////////////////////////////////

//output buffering aanzetten om leuke errors te verhelpen/voorkomen
ob_start();

//headers alvast instellen

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");


/////////////////////////////////////////////////////
/// Variablen die ingesteld moeten worden
/////////////////////////////////////////////////////

// Maanden, hoef je eigen niks aan te wijzigen, tenzij je
// natuurlijk de maanden in het engels wil ontvangen
$SETTINGS['maanden']                       = array(
'01' => 'Januari',
'02' => 'Februari',
'03' => 'Maart',
'04' => 'April',
'05' => 'Mei',
'06' => 'Juni',
'07' => 'Juli',
'08' => 'Augustus',
'09' => 'September',
'10' => 'Oktober',
'11' => 'November',
'12' => 'December'
);

// email adres(sen) waar het naartoe moet
// naam_van_persoon => email adres
$SETTINGS['emails'] = array('Ik'        => 'ik@jij.nl',
                            'Hij'       => 'Hij@zij.com',
                            'Bin laden' => 'b.laden@alquada.ak',
                            'Bush'        => 'bush@whitehouse.gov',
                            );

//standaard persoon die aangekruist staat (email adres)
$SETTINGS['stdmail'] = 'Ik';

//onderwerpen gebruiken?
//true / false
$SETTINGS['do_onderwerpen'] = true;

//welke onderwerpen?
// id => onderwerp
$SETTINGS['onderwerpen'] = array(1  => 'Suggesie',
                                 2  => 'Klacht',
                                 3  => 'Ideëen',
                                 4  => 'Vraag',
                                 );

//wat is het standaard onderwerp
// $SETTINGS['onderwerpen'][ id_van onderwerp ]
$SETTINGS['stdsub'] = $SETTINGS['onderwerpen'][4];

// html email of plain text? kies uit:
// text/html - text/plain
$SETTINGS['mime'] = 'text/html';

//datum formaat volgens php's date() functie
$SETTINGS['datum_formaat'] = 'd-m-Y H:i:s';

//tijdzone waar je in zit
$SETTINGS['timezone'] = 1;

//STA, Server Time Adjustment in minuten. Zegt het al...
$SETTINGS['adjustment'] = 0;

//input: minimale en maximale string lengte van naam?
$SETTINGS['naam_min'] = 3;
$SETTINGS['naam_max'] = 20;

//input: minimale en maximale string lengte van titel?
$SETTINGS['titel_min'] = 4;
$SETTINGS['titel_max'] = 40;

//input: minimale en maximale string lengte van titel?
$SETTINGS['email_min'] = 4;
$SETTINGS['email_max'] = 40;

//input: minimale en maximale string lengte van bericht? maximale woord lengte?
$SETTINGS['bericht_min'] = 20;
$SETTINGS['bericht_max'] = 10000;
$SETTINGS['bericht_wmx'] = 50;

//bericht dat weergegeven wordt bovenaan het formulier, html ingeschakelt
//hoeft er niks? laat dan   staan
$SETTINGS['bericht_top'] = ' <span style="font-weight:bold;">Test formulier script</span> ';

//bericht dat weergegeven wordt nadat het emailtje successvol is verzonden
$SETTINGS['bericht_suc']  = 'Bedankt voor het versturen van een e-mail.';
$SETTINGS['bericht_suc'] .= 'Je zult snel een antwoord krijgen indien nodig. <br />';
$SETTINGS['bericht_suc'] .= 'We gaan vertroiuwelijk om met de informatie en ';
$SETTINGS['bericht_suc'] .= 'je email adres zal nooit aan derden worden gegeven.';

//kijken voor een geldige email adres? true voor ja, false voor nee
$SETTINGS['email_check'] = true;

//foutmelding om te weergeven als het verzenden van
//de email niet is gelukt(dus als mail() FALSE geeft)
//html ingeschakelt
$SETTINGS['no_email'] = 'Er is een foutje opgetreden waardoor het email verzenden is mislukt...';

//foutmelding om te weergeven als degene al een emailtje heeft verzonden. html ingeschakelt
$SETTINGS['error_spam'] = 'Jij hebt al eens een emailtje gestuurd vandaag!';

//tijd wanneer het koekje beschimmeld raakt ( in andere taal: cookie verloop tijd)
$SETTINGS['expire_cookie'] = time() + (3600 * 24); //verloopt na een dag


/// niks meer te editen

// error reporting goed zetten
error_reporting(E_ALL ^ E_NOTICE);
//////////////////////////////
/// functies defineeren
////////////////////////////

function parse_incoming() {
    ////////////////////////////////////////////////
    /// Deze functie geeft al het 'incoming' via
    /// _POST en _GET terug. _POST heeft voorrang,
    /// dus als een key in _GET al bestaat, wordt
    /// de key overgeschreven
    ////////////////////////////////////////////////
    /// array parse_incoming( void );

    $return = array();

    
    //eerst get,
    foreach ($_GET as $k => $v) {
        if (!is_array($v)) {
            $return[ $k ] = clean_value($v);
        }
    }
    
    //en dan post!
    foreach ($_POST as $k => $v) {
        if (!is_array($v)) {
            $return[ $k ] = clean_value($v);
        }
    }
    return $return;

}

function clean_value($val) {
        global $site;
        
        if ($val == "")
        {
            return "";
        }
        
        $val = str_replace( "&#032;", " ", $val );

        $val = str_replace( chr(0xCA), "", $val );
        
        $val = str_replace( "&"            , "&"         , $val );
        $val = str_replace( "<!--"         , "&#60;&#33;--"  , $val );
        $val = str_replace( "-->"          , "--&#62;"       , $val );
        $val = preg_replace( "/<script/i"  , "&#60;script"   , $val );
        $val = str_replace( ">"            , ">"          , $val );
        $val = str_replace( "<"            , "<"          , $val );
        $val = str_replace( "\""           , """        , $val );
        $val = preg_replace( "/\n/"        , "<br>"          , $val );
        $val = preg_replace( "/\\\$/"      , "&#036;"        , $val );
        $val = preg_replace( "/\r/"        , ""              , $val );
        $val = str_replace( "!"            , "&#33;"         , $val );
        $val = str_replace( "'"            , "&#39;"         , $val );

        $val = preg_replace("/&#([0-9]+);/s", "&#\\1;", $val );
        
        $val = stripslashes($val);
        
        $val = preg_replace( "/\\\(?!&#|\?#)/", "&#092;", $val );
        
        return $val;
}

function checkcookie() {
    ///////////////////////////////////////////////
    /// Deze functie kijkt voor een cookie,
    /// in dit geval of de gast al eens een
    /// mailtje heeft gestuurd.
    // geeft false voor ja, true voor nee
    ///////////////////////////////////////////////
    /// boolean checkcookie( void );

    if ($_COOKIE['sendmail'] == "yeah") {
        return false;
    }
    return true;
}


function vervang_maand($datum) {
    //////////////////////////////////////////////////
    /// Deze functie gaat ervan uit dat $datum het
    /// volgende datum formaat gebruikt:
    /// d-m-Y H:i:xxxx
    /// d/m/Y H:i:xxxx
    /// d.m.y H:i:xxx
    /// Je zou natuurlijk strftime() kunnen gebruiken
    /// maar omdat we dan gebruik gaan maken van de
    /// ingebakken taalpakketten van php en het kan
    /// wel eens gebeuren dat men alleen engels
    /// in die versie heeft gestopt en dus nederlands
    /// niet ondersteund wordt.
    ////////////////////////////////////////////////
    /// string vervang_maand(string date);
    global $SETTINGS;
    list($dag, $maand, $rest) = split('[/.-]', $datum);
    foreach ($SETTINGS['maanden'] as $nummer => $naam) {
        $maand = str_replace ($nummer, $naam, $maand);
    }
    $temp_array = array( $dag, $maand, $rest);
    $datum = implode(" ", $temp_array);
    return $datum;
}

function validate_email($input) {
    ///////////////////////////////////////
    /// Kijkt of $input een geldig
    /// email adres bevat
    /////////////////////////////////////
    /// boolean validate_email( string email );

    if (!preg_match("/^[A-Za-z0-9._\-]+\@[A-Za-z0-9._\-]+\.[A-Za-z]{2,4}$/",$input)) {
        return false;
    }
    return true;
}

function checkstring($input, $minstrlen = 3, $maxstrlen = 10000, $maxwordlen = 300) {
    ////////////////////////////////
    /// Check $input string
    /// Geeft false als het niet goed is
    /// geeft true als de string $input
    /// oke is
    /////////////////////////////
    /// boolean checkstring(string input, [int minimaal tekens, [int maximaal tekens, [int maximaal woord lengte]]]);

    if (empty($input)) {
        return false;
    }
    if (strlen($input) < $minstrlen) {
        return false;
    }
    if (strlen($input) > $maxstrlen) {
        return false;
    }

    $temp_array = explode(" ", $input);
    foreach ($temp_array as $woord) {
        if (strlen($woord) > $maxwordlen) {
            return false;
        }
    }
    return true;
    
}

function get_date($timezone = 1, $adjustment = 0) {
    ////////////////////////////////////////////////
    /// Verkrijg de datum en tijd van een tijdzone
    /////////////////////////////////////
    /// string get_date( [int timezone, [int adjustment]] );
    global $SETTINGS;
    $adjustment = $adjustment / 60;
    $date = gmdate($SETTINGS['datum_formaat'], time() + 3600*($adjustment + $timezone + date("I")));
    
    return $date;
}

function show_form($naam = '', $email = '', $titel = '', $bericht = '', $error = false, $to = false, $onderwerp = false) {
    ///////////////////////////////////////////////
    /// Laat formulier zien. Error als opgegeven
    ////////////////////////////////////////////////
    /// void show_form( [string naam, [string email, [string titel, [string bericht, [string error]]]]] );
    global $SETTINGS;
    if ($error == false) {
        $header = $SETTINGS['bericht_top'];
    } else {
        $header = '<span style="color:#FF0000;font-weight:bold;">'.$error.'</span>';
    }

    if ($to == false) {
        $to = $SETTINGS['stdmail'];
    }
    if ($onderwerp == false) {
        $onderwerp = $SETTINGS['stdsub'];
    }
    $t = $_SERVER['PHP_SELF'];
    $s = explode("/", $_SERVER['PHP_SELF']);
    $this_file = $s[ count($s) - 1 ];
    echo '<form name="contact" action="'.$this_file.'" method="post">';
    echo '<input type="hidden" name="ip" value="'.$_SERVER['REMOTE_ADDR'].'" />';
    echo '<input type="hidden" name="act" value="dosend" />';

    echo '<table>'; //hier kun je eventueel nog style info aan toevoegen

    echo '<tr><td colspan="2" align="center">'.$header.'</td></tr>';
    echo '<tr><td align="left" valign="top">Je naam:</td><td align="left"><input type="text" name="naam" value="'.$naam.'" size="75" maxlength="'.$SETTINGS['naam_max'].'" /></td></tr>';
    echo '<tr><td align="left" valign="top">Je email:</td><td align="left"><input type="text" name="email" value="'.$email.'" size="75" maxlength="'.$SETTINGS['email_max'].'" /></td></tr>';
    echo '<tr><td align="left" valign="top">Ontvanger:</td><td align="left">';
    foreach ($SETTINGS['emails'] as $name => $adres) {
        $name = htmlentities($name);
        echo '<input type="radio" name="to" value="'.str_replace('_', ' ', $name).'" id="'.str_replace('_', ' ', $name).'" ';
        if (strtolower($to) == strtolower($name)) {
            echo 'checked="checked" ';
        }
        echo '/><label for="'.str_replace('_', ' ', $name).'">'.$name.'</label><br />';
    }
    print '</td></tr>';
    if ($SETTINGS['do_onderwerpen'] == true) {
        print '<tr><td align="left" valign="top">Onderwerp:</td>';
        print '<td align="left"><select name="onderwerp">';
        foreach ($SETTINGS['onderwerpen'] as $id => $sub) {
            print '<option value="'.$id.'" ';
            if ($sub == $onderwerp) {
                print 'selected="selected"';
            }
            print '>'.htmlentities($sub).'</option>';
        }
        print '</select></td></tr>';
    }

    echo '<tr><td align="left" valign="top">Titel:</td><td align="left"><input type="text" name="titel" value="'.$titel.'" size="75" maxlength="'.$SETTINGS['titel_max'].'" /></td></tr>';
    echo '<tr><td align="left" valign="top">Je bericht:</td><td align="left"><textarea name="bericht" cols="75" rows="7" wrap="soft">'.$bericht.'</textarea></td>';
    echo '<tr><td align="center" colspan="2"><input type="submit" name="submit" value="Verzend email" /></td></tr>';
    echo '</table></form>';
}

function sendmail($naam, $email, $titel, $bericht, $ip, $datum, $to, $onderwerp) {
    //////////////////////////////////////////////
    /// Stuurt emaitje. Gebruikt de $SETTINGS var
    /// en geeft false als het niet lukt
    /////////////////////////////////////////////
    /// boolean sendmail( string naam, string email, string titel, string bericht, string ip);
    global $SETTINGS;
    $to  = $SETTINGS['emails'][ str_replace(' ', '_', $to) ];
    $sub = $SETTINGS['onderwerpen'][ $onderwerp ];

    $subject = "Mailtje van je website - ".$naam.": ".$titel;
    if ($SETTINGS['mime'] == "text/html") {
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

        $message  = "<html><head>";
        $message .= "</head><body>";
        $message .= "Je hebt een emailtje gekregen van een gast van de website!<br /><br />";
        $message .= "<table>";
        $message .= "<tr><td>Naam:</td><td>".$naam."</td></tr>";
        $message .= "<tr><td>Email:</td><td><a href=\"mailto:".$email."\">".$email."</a></td></tr>";
        $message .= "<tr><td>Onderwerp:</td><td>".htmlentities($sub)."</td></tr>";
        $message .= "<tr><td>Titel:</td><td>".$titel."</td></tr>";
        $message .= "<tr><td>Bericht:</td><td>".$bericht."</td></tr>";
        $message .= "<tr><td colspan=\"2\"> </td></tr>";
        $message .= "<tr><td>Datum:</td><td>".vervang_maand($datum)."</td></tr>";
        $message .= "<tr><td>Ip:</td><td><a href=\"http://sunny.nic.com/cgi-bin/whois\">".$ip."</a></td></tr>";
        $message .= "</table></body></html>";


    } else {
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";

        $message  = "==============================================\n";
        $message .= "Emailtje van een gast van je website!\n";
        $message .= "==============================================\n";
        $message .= "\n";
        $message .= "Naam:\n";
        $message .= $naam."\n\n";
        $message .= "Email:\n";
        $message .= $email."\n\n";
        $message .= "Onderwerp:\n";
        $message .= $sub."\n\n";
        $message .= "Titel:\n";
        $message .= $titel."\n\n";
        $message .= "Bericht:\n";
        $message .= $bericht."\n\n";
        $message .= "\n";
        $message .= "Datum:\n";
        $message .= vervang_maand($datum)."\n\n";
        $message .= "Ip adres:\n";
        $message .= $ip."\n\n";

    }
    $headers .= "From: Php automailer <{$email}>\r\n";

    if (!mail($to, $subject, $message, $headers)) {
        return false;
    }
    return true;
}

///////////////////////////
/// En nu het script.....
///////////////////////////


$IN = parse_incoming();

if (checkcookie()) {
    if ($IN['act'] != 'dosend') {
        show_form();
    } else {
        $err = false;
        if (!checkstring($IN['naam'], $SETTINGS['naam_min'], $SETTINGS['naam_max'])) {
            $err = 'Geen naam ingevoerd of je naam is te kort of te lang.';
        } elseif (!checkstring($IN['email'], $SETTINGS['email_min'], $SETTINGS['email_max'])) {
            $err = 'Geen email ingevoerd of je email is te kort of te lang.';
        } elseif (!validate_email($IN['email']) && $SETTINGS['email_check'] == true) {
            $err = 'Ongeldig email adres ingevoerd.';
        } elseif (!checkstring($IN['titel'], $SETTINGS['titel_min'], $SETTINGS['titel_max'])) {
            $err = 'Geen titel ingevoerd of je titel is te kort of te lang.';
        } elseif (!checkstring($IN['bericht'], $SETTINGS['bericht_min'], $SETTINGS['bericht_max'])) {
            $err = 'Geen bericht ingevoerd of je bericht is te kort of te lang.';
        }
        if ($err == false) {
            $datum = get_date($SETTINGS['timezone'], $SETTINGS['adjustment']);
            if (!sendmail($IN['naam'], $IN['email'], $IN['titel'], $IN['bericht'], $IN['ip'], $datum, $IN['to'], $IN['onderwerp'])) {
                echo $SETTINGS['no_email'];
            } else {
                echo $SETTINGS['bericht_suc'];
                setcookie('sendmail', "yeah", $SETTINGS['expire_cookie']);
            }
        } else {
            show_form($IN['naam'], $IN['email'], $IN['titel'], $IN['bericht'], $err, $IN['to'], $IN['onderwerp']);
        }
    }
} else {
    echo $SETTINGS['error_spam'];
}

//laten we nu maar alles outputten, het is genoeg
//geweest voor deze keer en er komen toch
//geen headers meer ^^
ob_end_flush();
?> 

Link to comment
https://forums.phpfreaks.com/topic/221747-how-to-integrate-a-contactform-template/
Share on other sites

What sort of a contact form do you need? They're really very simple to create, I'm not sure why you need so much code.

 

From the looks of it, it's going to be one complex form. All you really need to do is create your form in html as per usual. Then you give the form an action which points to a php file. This php file will grab each of the form fields data from $_POST or $_GET (depending on your sending method), and then can either send the form data to an email address, enter it into a database, or do whatever you want it to do..

 

Unless I'm missing the point, and you're requiring a more complex setup?

 

Denno

 

 

Hi Denno,

 

You're probably right... I forgot to mention that I sort of have no knowledge of PHP yet what so ever...

 

Could you please explain what you meant?

 

I made a quick html form:

 

<p>Your Name<br />

    <input type="text" value="" class="" size="40" /></p>

<p>Your Email <br />

    <input type="text" value="" class="" size="40" /></p>

<p>Subject<br />

    <input type="text" value="" class="" size="40" /></p>

<p>Message<br />

    <textarea name="" cols="40" rows="10"></textarea></span> </p>

<p><input type="submit" value="Submit" class="" />

</form>

 

What should I do/How could I use the php script in my first post

to make this html form work?

 

As you said, the php script is kind of complex, with an anti-spam captcha, drop-down options, and such... How could I include this at the html form so that it will connect with each other?

 

Could you help me out?

 

Thanks,

Anthony

Here is a basic form I am currently using

 

<form id="form2" name="form2" method="post" action="index2.php">            
                    <label for="webnumber">Site Number</label>
                      <input name="webnumber" type="text" id="webnumber" size="2" maxlength="2" />
                <br/>
                      <br/>
                      <label for="likes">Likes</label>
                      <textarea name="likes" id="likes" cols="50" rows="10"></textarea>
                      <br/>                                                      
                      <br/>
                      <label for="dislikes">Dislikes</label>
                      <textarea name="dislikes" id="dislikes" cols="50" rows="10"></textarea>
                    
                    <p>
                      <input type="submit" name="Submit" id="submit" value="Submit" title="Submit the form button" />
                      <input type="reset" name="Reset1" id="reset1" value="Reset" title="Reset the form button" />
                    </p>
                </form>

 

The php handler that deals with this form is

 

<?php
// connection to MySQL
require ("connect.php"); // if this script is unavailable then the rest of the code is pointless as need a connection to the database.

// collection of ip address
//$ip = getRealIpAddr();


if($_POST['webnumber'])
{ // if this field has had data entered then process the data

$webnumber = strip_tags($_POST['webnumber']); // Removing false entries/malicious code
$likes = strip_tags($_POST['likes']); 
$dislikes = strip_tags($_POST['dislikes']); 

/* depending on what version of php being used will need to strip slashes also, if lower than version 6, mine is 4.4.9
$webnumber = stripslashes($_POST['webnumber']); 
$likes = stripslashes($_POST['likes']); 
$dislikes = stripslashes($_POST['dislikes']); */


/* Setting variables

$webnumber = $_POST['webnumber'];
$likes = $_POST['likes'];
$dislikes = $_POST['dislikes']; */


// insert data to dbase
$query="INSERT INTO datacollection2 (id, ip, webnumber, likes, dislikes) VALUES ('Null', '$ip', '$webnumber', '$likes', '$dislikes')";

// Null is in the id field as his is added automatically by the database.

// message to say if database has been updated

mysql_query($query) or die (mysql_error());

echo "The database has just been updated with the following information: ".'<br/>';

//echo "<b>Your IP address is: $ip</b> <br />";

/*function getRealIpAddr() 
{ 
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet 
    { 
      $ip=$_SERVER['HTTP_CLIENT_IP']; 
    } 
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy 
    { 
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
    } 
    else 
    { 
      $ip=$_SERVER['REMOTE_ADDR']; 
    } 
    return $ip; 
} */

echo $haveemail.'<br/>';
echo '<br/>'."<b>You liked the following </b>".$likes." <b>from website</b> ".$webnumber.'<br/>';
echo '<br/><br/>'."<b>You disliked the following </b>".$dislikes."<b> from website </b>".$webnumber.'<br/>';
echo '<br/><br/>'."Thankyou for your input".'<br/><br/>';

}
?>

To connect the two so that the form calls the php into action my finished form xhtml code looks like

[code]
<?php include 'php/writedatacollection2.php'; ?>  <!-- includes php script  to write data to dbase-->
                  
    			  <form id="form2" name="form2" method="post" action="index2.php">            
                    <label for="webnumber">Site Number</label>
                      <input name="webnumber" type="text" id="webnumber" size="2" maxlength="2" />
                <br/>
                      <br/>
                      <label for="likes">Likes</label>
                      <textarea name="likes" id="likes" cols="50" rows="10"></textarea>
                      <br/>                                                      
                      <br/>
                      <label for="dislikes">Dislikes</label>
                      <textarea name="dislikes" id="dislikes" cols="50" rows="10"></textarea>
                    
                    <p>
                      <input type="submit" name="Submit" id="submit" value="Submit" title="Submit the form button" />
                      <input type="reset" name="Reset1" id="reset1" value="Reset" title="Reset the form button" />
                    </p>
                </form>

 

[/code]

 

the include statement prior to the form tags is what calls the php

<?php include 'php/writedatacollection2.php'; ?>  <!-- includes php script  to write data to dbase-->

 

Hope this helps

 

What sort of a contact form do you need? They're really very simple to create, I'm not sure why you need so much code.

 

From the looks of it, it's going to be one complex form. All you really need to do is create your form in html as per usual. Then you give the form an action which points to a php file. This php file will grab each of the form fields data from $_POST or $_GET (depending on your sending method), and then can either send the form data to an email address, enter it into a database, or do whatever you want it to do..

 

Unless I'm missing the point, and you're requiring a more complex setup?

 

Denno

 

 

I NEED help please, i am very new to PHP and I have a problem.....

 

I have a form that sends to a php which posts all values to my table and at thesame time sends an email

I have everything orking great except one thing: I cannot include a $value inside my email message

 

Here it is:

 

$confirmCode = md5(uniqid(rand()));

$to      = $_POST;

$subject = "Subject";

 

$message = " To confirm that registration, please  click on this link: http://www.pinoyescrow.com/confirmation.php?passkey=$confirmCode

 

$headers = 'From: admin@mysite.com' . "\r\n" .

    'Reply-To: admin@mysite.com' . "\r\n" .

mail($to, $subject, $message, $headers);

 

Problem is:

The email received does not actually include the actual confirmation code but is treating $confirmCode as a text

honestly, i do not have enough experience with "" and '' but i think that is not the problem because you see, the php script works fine except for this problem. I am able to insert values to my database table and i do receive the email. The problem is, in this example, I cannot get to put the value of $confirmCode inside the body of my email message. I have tried these:

 

$message = "here is your confirmation code: $confirmcode"    //sends me the email but shows $confirmcode as text

$message = "here is your confirmation code: '$confirmcode' " //sends me the email but shows $confirmcode as text

$message = "here is your confirmation code:" $confirmcode // only sends: here is your confirmation code:

$message = 'here is your confirmation code: "$confirmcode" ' //i do not receive email, submit page goes blank

$message = 'here is your confirmation code:' "$confirmcode" //i do not receive email, submit page goes blank

does the $headers variable display properly in your emails?

 

I've copied your code into dreamweaver, and it's immediately complained, saying there is syntax errors.

 

Attached is a screenshot, so you can see where these are, and how my auto formatting is showing the code. What do you code your php in?

 

Denno

 

[attachment deleted by admin]

Try this code. It doesn't complain about any syntax errors.

<?php

$confirmCode = md5(uniqid(rand()));
$to      = $_POST;
$subject = "Subject";
$message = " To confirm that registration, please  click on this link: [url=http://www.pinoyescrow.com/confirmation.php?passkey=]http://www.pinoyescrow.com/confirmation.php?passkey=[/url]$confirmCode$headers = \'From: [email]admin@mysite.com\'" . "\r\n" . 'Reply-To: admin@mysite.com' . "\r\n" .
mail($to, $subject, $message, $headers);

?>

 

I looked up the different between single and double quotes, and turns out it's personal preference. However, if you use double quotes, you need to escape any single qutoes (by putting a \ before it). It basically says, treat the next character as if it were just a normal character, don't give it any special meaning.

 

Hope that helps.

 

Denno

  • 2 weeks later...

I haven't been online @phpfreaks.com for a while, thanks all for the replies.

 

I decided not to go for the complicated php form and I slowly started to make an own form. It worked, but now I decided to remove the php file that was the "form action", and integrate this file into the contact file itself. I named this file "contactformulier.php" (contactformulier is Dutch for contactform...), and it can be found online @ http://amstel-webdesign.nl/contactformulier.php. As you can see when you visit the website, there is a:

 

Parse error: syntax error, unexpected $end in /home/amstelwd/domains/amstel-webdesign.nl/public_html/contactformulier.php  on line 213.

 

Does anyone know what I'm doing wrong/what I have to change?

 

The source of the contactform is as follows:

<?php
if(isset($_POST['submit'])) {

$to = "kenzo-dolce@live.nl";
$subject = "Form Tutorial";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$dropdown = $_POST['drop_down'];



$body = "Afzender: $name_field\n Emailadres: $email_field\n Betreft: $dropdown\n Bericht: $message_field\n";

echo "Uw bericht is verstuurd naar $to!";
mail($to, $subject, $body);

?>


<!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=iso-8859-1" />
<title>Amstel webdesign & graphics</title>
<link href="style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20418005-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>

<body>
<!-- header start -->
<div id="header">
    <ul>
        <li><a href="">Homepage</a></li>
        <li><a href="">Over ons</a></li>
    <li><a href="">Webdesign</a></li>
        <li><a href="">Graphics</a></li>   
        <li><a href="">Prijzen</a></li>
        <li><span><a href="contact.php">Contact</a></span></li>
        </ul>
</div>
<!-- header end -->
   
<!-- body start -->
<div id="body">




<div class="left">
       

<a href="#" title="Over ons"><img src="images/hobby_profession.png" alt="Onze hobby is ons beroep geworden..." width="780" height="305" border="0" /></a><br class="spacer" />



          <br class="spacer" />

<div class="textbox">
<h2><span>Contact</span>formulier</h2><br /> <br />


<?php
if(isset($_POST['submit'])) {
echo "<p>Uw bericht is succesvol verzonden.</p>";
} else {
?>
           
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
    Uw volledige naam:<br />
<input onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" type="text" name="name" size="60"></p>
   
<p>
    Uw emailadres:<br />
<input onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" type="text" name="email" size="60"></p>

<p>
    Betreft:<br />
<select size="1" name="drop_down">
<option>Webdesign</option>
<option>Graphics</option>

</select></p>
   
<p>
Uw bericht:<br />
<textarea onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" rows="9" name="message" cols="60"></textarea><br /></p>
   
<p>
    <input type="submit" value="Verzenden" name="submit"></p>
</form>

<?php } ?>


</div>
</div>
<div class="right">
<h2><span>Diensten</span></h2><br />
<ul>
<li><a href="#">Webdesign </a></li>
<li><a href="#">Consultancy  </a></li>
<li><a href="#">Onderhoud </a></li>
<li><a href="#">CMS </a></li>
<li><a href="#">SEO  </a></li>
<li><a href="#">Webshop ontwikkeling </a></li>
<li><a href="#">Contactformulier ontwikkeling </a></li>
                <li><a href="#">Zoekfunctie ontwikkeling </a></li>
                <li><a href="#">Google Analytics </a></li>
<li><a href="#">Google Maps </a></li>
<li><a href="#">Mobiel </a></li>
<li><a href="#">Huisstijl ontwikkeling </a></li>
<li><a href="#">Drukwerk  </a></li>
<li><a href="#">Vertalingen </a></li>               
</ul>
            <br /><br />
           
            <form method="post" action="#" name="search" class="search">
<label><span>Zoek</span>functie</label>
<br class="spacer" />
<input name="search" type="text" id="search" />
<a href="#" title="Advance search">Geavanceerd zoeken</a><input name="" type="image" src="images/search_btn.gif" title="Search"  class="searchBtn"/>
</form>
<form method="post" action="#" name="login" class="login">
<h2><span>Log-</span>in</h2><br class="spacer" />
<label>Naam</label><br class="spacer" />
<input name="name" type="text" id="name" /><br class="spacer" />
<label>Wachtwoord</label><br class="spacer" />
<input name="password" type="password" id="password" /><br class="spacer" />
<input name="" type="image" src="images/login_btn.gif" title="Login" class="loginBtn" />
</form><br class="spacer" />
</div>
<br class="spacer" /></div>
<!-- body end -->
   
<!-- footer start -->
<div id="footer">
<div class="footer">
<div id="nav_left">
            <a href="" title="Home">Home</a> <br />
            <a href="" title="Over ons">Over ons</a> <br />
<a href="" title="Webdesign">Webdesign</a> <br />
<a href="" title="Graphics">Graphics</a> <br />
<a href="" title="Prijzen">Prijzen</a> <br />
<a href="" title="Contact">Contact</a>
            <br class="spacer" />
        </div>
            <div id="nav_center">
  <a href="">Webdesign</a> <br />
              <a href="">Consultancy</a> <br />
              <a href="">Onderhoud</a> <br />
              <a href="" title="Content Management System">CMS</a> <br />
              <a href="" title="Search Engine Optimization / Zoekmachine Optimalisatie">SEO</a> <br />
              <a href="">Webshop ontwikkeling</a>
            </div>
            <div id="nav_right">
                <a href="">Google Analytics</a> <br />
                    <a href="">Google Maps</a> <br />
                    <a href="">Mobiel</a> <br />
                    <a href="">Huisstijl ontwikkeling</a> <br />
                    <a href="">Drukwerk</a> <br />
                    <a href="">Vertalingen</a>
                </div>
?>
                </p>
    </div>
    </div>
    </div>
</div>
<!-- footer end -->
</body>
</html>

Also, does anyone know what I should do to add a "captcha" (do I name it right?)? The anti-spam thing you have to fill in to prove you are human...

 

Thanks in advance,

Oooh, it's fixed. Thank you so much. Forgot to mention that I'm a complete php idiot, but anyway, even I could understand how the unclosed "IF" could be fixed..

 

Furthermore I checked out some of the php scripts online, but found that most of the scripts worked independently. That is in a 'captcha.php' file or so, or the scripts are only available in a complete contactform package. Do you know I could integrate a captcha code to my existing "contactformulier.php"? I found the following script for example (the comments used to be in Dutch, I hope I translated them all, but perhaps I missed a few)...:

<?php 
// make the random number and save it in a php session

session_start(); 

$randomnr = rand(1000, 9999); 
$_SESSION['randomnr2'] = md5($randomnr); 

// Make the captcha image with number 

$im = imagecreatetruecolor(100, 38); 

// Decide colors

$white = imagecolorallocate($im, 255, 255, 255); 
$grey = imagecolorallocate($im, 128, 128, 128); 
$black = imagecolorallocate($im, 0, 0, 0); 

// draw black box

imagefilledrectangle($im, 0, 0, 200, 35, $black); 

// here - font.ttf' replace with de location of your own font file
$font = 'font.ttf'; 

// add shaduw 

imagettftext($im, 35, 0, 22, 24, $grey, $font, $randomnr); 

// add random number

imagettftext($im, 35, 0, 15, 26, $white, $font, $randomnr); 

// prevent that the image gets cached

header("Expires: Wed, 1 Jan 1997 00:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false); 
header("Pragma: no-cache"); 

// send image to browser 

header ("Content-type: image/gif"); 
imagegif($im); 
imagedestroy($im); 
?>

 

The "contactformulier.php" file looks like this right now:

 

<?php
if(isset($_POST['submit'])) {

$to = "kenzo-dolce@live.nl"; 
$subject = "Form Tutorial";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$dropdown = $_POST['drop_down'];



$body = "Afzender: $name_field\n Emailadres: $email_field\n Betreft: $dropdown\n Bericht: $message_field\n";

mail($to, $subject, $body); }

?>


<!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=iso-8859-1" />
<title>Amstel webdesign & graphics</title>
<link href="style.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20418005-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

</head>

<body>
<!-- header start -->
<div id="header">
    	<ul>
        	<li><a href=""> Homepage</a></li>
        	<li><a href="">Over ons</a></li>
    		<li><a href="">Webdesign</a></li>
        	<li><a href="">Graphics</a></li>    	
        	<li><a href="">Prijzen</a></li>
        	<li><span><a href="contact.php">Contact</a></span></li>
         </ul>
</div>
<!-- header end -->	
    
<!-- body start -->
<div id="body">




	<div class="left">
        	

<a href="#" title="Over ons"><img src="images/hobby_profession.png" alt="Onze hobby is ons beroep geworden..." width="780" height="305" border="0" /></a><br class="spacer" />



          <br class="spacer" />

<div class="textbox">
		<h2><span>Contact</span>formulier</h2><br /> <br />


<?php
if(isset($_POST['submit'])) {
echo "<p>Uw bericht is succesvol verzonden.</p>";
} else {
?>
            
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
    Uw volledige naam:<br />
<input onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" type="text" name="name" size="60"></p>
    
<p>
    Uw emailadres:<br />
<input onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" type="text" name="email" size="60"></p>

<p>
    Betreft:<br />
<select size="1" name="drop_down">
<option>Webdesign</option>
<option>Graphics</option>

</select></p>
    
<p>
Uw bericht:<br />
<textarea onfocus="this.style.borderColor='#ff0080';" onblur="this.style.borderColor='#eee';" rows="9" name="message" cols="60"></textarea><br /></p>
    
<p>
    <input type="submit" value="Verzenden" name="submit"></p>
</form>

<?php } ?>


</div>
	</div>
	<div class="right">
		<h2><span>Diensten</span></h2><br />
		<ul>
			<li><a href="#">Webdesign </a></li>
			<li><a href="#">Consultancy  </a></li>
			<li><a href="#">Onderhoud </a></li>
			<li><a href="#">CMS </a></li>
			<li><a href="#">SEO  </a></li>
			<li><a href="#">Webshop ontwikkeling </a></li>
			<li><a href="#">Contactformulier ontwikkeling </a></li>
                <li><a href="#">Zoekfunctie ontwikkeling </a></li>
                <li><a href="#">Google Analytics </a></li>
			<li><a href="#">Google Maps </a></li>
			<li><a href="#">Mobiel </a></li>
			<li><a href="#">Huisstijl ontwikkeling </a></li>
			<li><a href="#">Drukwerk  </a></li>
			<li><a href="#">Vertalingen </a></li>                
		</ul>
            <br /><br />
            
            <form method="post" action="#" name="search" class="search">
			<label><span>Zoek</span>functie</label>
			<br class="spacer" />
			<input name="search" type="text" id="search" />
			<a href="#" title="Advance search">Geavanceerd zoeken</a><input name="" type="image" src="images/search_btn.gif" title="Search"  class="searchBtn"/>
		</form>
		<form method="post" action="#" name="login" class="login">
			<h2><span>Log-</span>in</h2><br class="spacer" />
			<label>Naam</label><br class="spacer" />
			<input name="name" type="text" id="name" /><br class="spacer" />
			<label>Wachtwoord</label><br class="spacer" />
			<input name="password" type="password" id="password" /><br class="spacer" />
			<input name="" type="image" src="images/login_btn.gif" title="Login" class="loginBtn" />
		</form><br class="spacer" />
	</div>
<br class="spacer" /></div>
<!-- body end -->
    
<!-- footer start -->
<div id="footer">
<div class="footer">
	<div id="nav_left">
            	<a href="" title="Home">Home</a> <br />
            	<a href="" title="Over ons">Over ons</a> <br />
			<a href="" title="Webdesign">Webdesign</a> <br />
			<a href="" title="Graphics">Graphics</a> <br />
			<a href="" title="Prijzen">Prijzen</a> <br />
			<a href="" title="Contact">Contact</a>
            <br class="spacer" />		
        </div>		
            <div id="nav_center">
		  <a href="">Webdesign</a> <br />
              <a href="">Consultancy</a> <br />
              <a href="">Onderhoud</a> <br />
              <a href="" title="Content Management System">CMS</a> <br />
              <a href="" title="Search Engine Optimization / Zoekmachine Optimalisatie">SEO</a> <br />
              <a href="">Webshop ontwikkeling</a>
            </div>
            	<div id="nav_right">
                	<a href="">Google Analytics</a> <br />
                    <a href="">Google Maps</a> <br />
                    <a href="">Mobiel</a> <br />
                    <a href="">Huisstijl ontwikkeling</a> <br />
                    <a href="">Drukwerk</a> <br />
                    <a href="">Vertalingen</a>
                </div>
</div>
<!-- footer end -->		
</body>
</html>

 

Could you please help me out?

 

Also, if I have succesfully send the form (when testing if it all works or not), I get redirected to a page with "Uw bericht is succesvol verzonden." which means "Your message has been send succesfully.". If I refresh the page here, another message is send, and if I press F5 ten times, I have 10 mails in my inbox. Can this be prevented?

 

Lastly, if I have not succesfully send the form, I also get redirected to this same page with "Your message has been send succesfully.". What should I add to the form to make sure another message (for example: "Your message could not be sent for the following reasons:

- No emailaddress was filled in

- No name was filled in

- Or whatever)

 

Thanks,

Anthony

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.