sagepay form integration - Not able to decrypt the $_GET['crypt'] string returned - zen-cart

I have placed a test transaction using following encryption -
<?php
function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function encryptFieldData($input)
{
$key = "use your SagePAY encryption key here";
$iv = $key;
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
if (mcrypt_generic_init($cipher, $key, $iv) != -1)
{
$cipherText = mcrypt_generic($cipher,$input );
mcrypt_generic_deinit($cipher);
$enc = bin2hex($cipherText);
}
return $enc;
}
$str = "Currency=GBP";
$datapadded = pkcs5_pad($str,16);
$cryptpadded = "#" . encryptFieldData($datapadded);
?>
<html>
<form name="pp_form" action="SagePay test url" method="post">
<input name="VPSProtocol" type="hidden" value=3.00 />
<input name="TxType" type="hidden" value=PAYMENT />
<input name="Vendor" type="hidden" value="YOUR SAGEPAY ACCOUNT NAME HERE" />
<input name="Crypt" type="hidden" value=<?php echo $cryptpadded;?> />
<p>Click here to submit
<input type="submit" value="here">
</p>
</form>
</html>
But when the SagePay returns encrypted string, I am not sure how to decrypt this encrypted data as we will have to do decrypt it while creating order at our end. Can someone help?
Thanks in advance.

Related

Status Detail: 5068 when using sagePay

I am trying to use SagePay. I have an account and I would like to use Server Integration.
The error I get is Status Detail: 5068 : The encryption method is not supported by this protocol version.
I'm trying to create a simple 'pay now' button, as described in the documents. The code samples provided by sage don't appear to work.
Can someone please let me know why the code below doesnt work? thanks
<?php
require_once ('lib/SagePay.php');
$sagePay = new SagePay();
$sagePay->setCurrency('BG');
$sagePay->setAmount('100');
$sagePay->setDescription('Lorem ipsum');
$sagePay->setBillingSurname('Mustermann');
$sagePay->setBillingFirstnames('Max');
$sagePay->setBillingCity('Cologne');
$sagePay->setBillingPostCode('50650');
$sagePay->setBillingAddress1('Bahnhofstr. 1');
$sagePay->setBillingCountry('de');
$sagePay->setDeliverySameAsBilling();
/* Example of using BasketXML */
$xml = new DOMDocument();
$basketNode = $xml->createElement("basket");
$itemNode = $xml->createElement("item");
$descriptionNode = $xml->createElement( 'description' );
$descriptionNode->nodeValue = 'First Item Description';
$itemNode -> appendChild($descriptionNode);
$quantityNode = $xml->createElement('quantity');
$quantityNode->nodeValue = '1';
$itemNode -> appendChild($quantityNode);
$unitNetAmountNode = $xml->createElement('unitNetAmount');
$unitNetAmountNode->nodeValue = '90.00';
$itemNode -> appendChild($unitNetAmountNode);
$unitTaxAmountNode = $xml->createElement('unitTaxAmount');
$unitTaxAmountNode->nodeValue = '10.00';
$itemNode -> appendChild($unitTaxAmountNode);
$unitGrossAmountNode = $xml->createElement('unitGrossAmount');
$unitGrossAmountNode->nodeValue = '100.00';
$itemNode -> appendChild($unitGrossAmountNode);
$totalGrossAmountNode = $xml->createElement('totalGrossAmount');
$totalGrossAmountNode->nodeValue = '100.00';
$itemNode -> appendChild($totalGrossAmountNode);
$basketNode->appendChild( $itemNode );
$xml->appendChild( $basketNode );
$sagePay->setBasketXML($xml->saveHTML());
$sagePay->setSuccessURL('https://website.co.uk/page.html');
$sagePay->setFailureURL('https://website.co.uk/page.html');
?>
<form method="POST" id="SagePayForm" action="https://test.sagepay.com/gateway/service/vspform-register.vsp">
<input type="hidden" name="VPSProtocol" value= "3.00">
<input type="hidden" name="TxType" value= "PAYMENT">
<input type="hidden" name="Vendor" value= "vendorname here">
<input type="hidden" name="Crypt" value= "<?php echo $sagePay->getCrypt(); ?>">
<input type="submit" value="continue to SagePay">
</form>
Couple of things to check:
Ensure you are using AES encryption on the Crypt field
When sending the crypt over to Sage Pay, make sure it is prefixed '#'
Make sure you are not Base64 encoding the string after you have AES encrypted it (the protocol documents are a little misleading in this regard)
[update]: 4. You are actually using the Form integration method...
Thanks for the help on this.
It was a problem with the encryption method. The code that eventually worked for me was this one:
https://github.com/tolzhabayev/sagepayForm-php/blob/master/lib/SagePay.php
And my form button is like this:
<form method="POST" id="SagePayForm" action="https://test.sagepay.com/gateway/service/vspform-register.vsp">
<input type="hidden" name="VPSProtocol" value= "3.00">
<input type="hidden" name="TxType" value= "PAYMENT">
<input type="hidden" name="Vendor" value= "vendornamehere">
<input type="hidden" name="Crypt" value= "<?php echo $sagePay->getCrypt(); ?>">
<input type="submit" value="continue to SagePay">
</form>

Login change in to signup

I have created a HTML5 registration form,is it possible for it to check the email address(inserted first) if it's already used to ask only for password(login) and if it's not to insert other fields needed for signup? using php,js or others.
<form id="signin_student" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Register </h3>
<input type="text" class="input-block-level" id="username" name="username" placeholder="NISN" required>
<input type="text" class="input-block-level" id="firstname" name="firstname" placeholder="Nama Depan" required>
<input type="text" class="input-block-level" id="lastname" name="lastname" placeholder="Nama Belakang" required>
<label>Kelas</label>
<select name="class_id" class="input-block-level span5">
<option>Pilih Kelas</option>
<?php
$query = mysql_query("select * from class order by class_name ")or die(mysql_error());
while($row = mysql_fetch_array($query)){
?>
<option value="<?php echo $row['class_id']; ?>"><?php echo $row['class_name']; ?></option>
<?php
}
?>
</select>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<input type="password" class="input-block-level" id="cpassword" name="cpassword" placeholder="Tulis Ulang Password" required>
<button title="Klik untuk Daftar" id="signin" name="login" class="btn btn-info" type="submit"><i class="icon-check icon-large"></i> Daftar</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#signin_student").submit(function(e){
e.preventDefault();
var password = jQuery('#password').val();
var cpassword = jQuery('#cpassword').val();
if (password == cpassword){
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "student_signup.php",
data: formData,
success: function(html){
if(html=='true')
{
var delay = 2000;
setTimeout(function(){ window.location = 'siswa/index.php' }, delay);
}else if(html=='false'){
{ header: 'Data in DB is Not Found' });
}
}
});
}else
{
$.jGrowl("student does not found in the database", { header: 'Sign Up Failed' });
}
});
});
</script>
and file signup.php
<?php
mysql_select_db('db',mysql_connect('localhost','root',''))or die(mysql_error());
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$class_id = $_POST['class_id'];
$query = mysql_query("select * from student where username='$username' and firstname='$firstname' and lastname='$lastname' and class_id = '$class_id'")or die(mysql_error());
$row = mysql_fetch_array($query);
$id = $row['student_id'];
$count = mysql_num_rows($query);
if ($count > 0){
mysql_query("update student set password = '$password', status = 'Registered' where student_id = '$id'")or die(mysql_error());
$_SESSION['id']=$id;
echo 'true';
}else{
echo 'false';
}
?>
Firstly, you could use this code to check when the user stops typing:
Run javascript function when user finishes typing instead of on key up?
Once that is finished, this SQL code may work to check if the email already exists:
SELECT EXISTS(SELECT email FROM email_table)
Then you can simply use a conditional statement to print whether the email exists.

PayPal IPN and PDT - Cannot get buyer postal address on return_url page or email

I am setting up a basic donation system and need to send a confirmation email to the client but cannot get the buyer postal address to show on return_url page of the website, or to show in the email to send to the client. The custom values for the taxpayer yes/no radio selects won't follow through either in the email. I am using a custom form on our website with fields to fill in the donation amount, name, address and if they pay tax (simple radio select.) Not sure if I'm using it right but I have both IPN and PDT settings on the site site and setup within the PayPal account.
Donation Form:
<form class="dsForm" name="details" action="https://www.paypal.com/cgi-bin/webscr" method="post" onsubmit="if ( !CheckForm() ) return false;">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" id="business" name="business" value="charityemail#internet.com">
<input type="hidden" id="item_name" name="item_name" value="Website Donation - Water">
<input type="hidden" name="notify_url" value="http://www.urltoipnscript.com/ipn.php">
<input type="hidden" id="item_number" name="item_number" value="3">
<input type="hidden" name="no_note" value="1">
<input type="hidden" id="currency_code" name="currency_code" value="GBP">
<input type="hidden" name="no_shipping" value="2">
<input type="hidden" name="tax" value="0">
<input type="hidden" name="bn" value="IC_Sample">
<input type="hidden" value="donation" name="custom">
<ul id="donate-form">
<li><label>Amount:</label>
<input type="text" id="amount" name="amount" value="25.00" size='9'>
<select id='currency' onchange='CheckCurrency()'>
<option value="GBP">GBP</option>
<option value="EUR">EUR</option>
<option value="AUD">AUD</option>
<option value="USD">USD</option>
</select>
</li>
<li><label>Program:</label>
<select name='program' id='program' onchange='ProgramChange();' >
<option value=''>Please Select</option>
<option id="education" value='4'>Education</option>
<option id="water" value='3' selected="selected">Water</option>
<option id="health" value='2'>Health Promotion</option>
<option id="community" value='18'>Community Based Projects</option>
<option id="sponsorship" value='8'>Child Sponsorship</option>
</select>
</li>
<li><label>Firstname:</label>
<input type='text' name='first_name' size='30' />
</li>
<li><label>Surname:</label>
<input type='text' name='last_name' size='30' />
</li>
<li><label>Address 1:</label>
<input type='text' name='address1' size='30' />
</li>
<li><label>Address 2:</label>
<input type='text' name='address2' size='30' />
</li>
<li><label>Town/City:</label>
<input type='text' name='city' size='30' />
</li>
<li><label>Postcode/Zip:</label>
<input type='text' name='zip' size='30' />
</li>
<li><label>Country:</label>
<select name='country' id='country' >
<option value='' selected='selected'>Please Select</option>
<option value='AL'>Albania
</option><option value='DZ'>Algeria
</option><option value='GB'>United Kingdom
</option><option value='US'>United States
etc...
</li>
<div id='ukTaxOptions' style='display:none'>
<label style="width:auto; margin-top:20px; margin-bottom:10px;font-weight: bold;" > Please choose an appropriate option below:</label >
<li>
<label style="width:auto" >
<input id='gbTaxPayer_1' name='gbTaxPayer_radio' type='radio' value='1' onchange="SetPayPalCustom('UK')" />
<input id="gbTaxPayer" name="gbTaxPayer" type="hidden" value="1" /> I am a UK taxpayer and would like to Gift Aid all donations I have made to Fields Of Life in the last four years and all donations I make in the future, until I notify you otherwise *
</label>
</li>
<li><label style="width:auto">
<input id='gbTaxPayer_' name='gbTaxPayer_radio' type='radio' value='' checked onchange="SetPayPalCustom('')" />I am not a UK taxpayer
</label></li>
<li><label style="width:auto">* I understand that I must have paid an amount of income tax or capital gains tax at least equal to the tax you reclaim on my donations</label></li>
</div>
<input type="hidden" name="hosted_button_id" value="hidden from stackflow">
<input type="image" src="http://www.hiddenfromsov.com/mybtn.png" border="0" name="submit" alt="PayPal — The safer, easier way to pay online.">
<li><img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif width="1" height="1" /></li>
</ul>
IPN Script:
<?php
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if( !($res = curl_exec($ch)) ) {
curl_close($ch);
exit;
}
curl_close($ch);
if (strcmp ($res, "VERIFIED") == 0) {
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];
$address_street = $_POST['address_street'];
$address_city = $_POST['address_city'];
$address_state = $_POST['address_state'];
$address_zip = $_POST['address_zip'];
$address_country = $_POST['address_country'];
$address_status = $_POST['address_status'];
$gbtax = $_POST['gbTaxPayer_radio'];
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
}
Code on success return_url page
//PDT
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';
$tx_token = $_GET['tx'];
$auth_token = "I've copied this the paypal settings";
$req .= "&tx=$tx_token&at=$auth_token";
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
// $fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
// read the body data
$res = '';
$headerdone = false;
while (!feof($fp)) {
$line = fgets ($fp, 1024);
if (strcmp($line, "\r\n") == 0) {
// read the header
$headerdone = true;
}
else if ($headerdone)
{
// header has been read. now read the contents
$res .= $line;
}
}
// parse the data
$lines = explode("\n", $res);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$item_number = $_GET['item_number'];
$address12 = $_GET['address_street'];
$firstname = $keyarray['first_name'];
$lastname = $keyarray['last_name'];
$payer_email = $keyarray['payer_email'];
$amount = $keyarray['mc_gross'];
$payment_date = $keyarray['payment_date'];
$payment_status = $keyarray['payment_status'];
$payment_type = $keyarray['payment_type'];
$mc_currency = $keyarray['mc_currency'];
$transactionid = $keyarray['txn_id'];
$itemname = $keyarray['item_name'];
$address1 = $keyarray['address1'];
$address_street = $keyarray['address_street'];
$address_city = $keyarray['address_city'];
$address_state = $keyarray['address_state'];
$address_zip = $keyarray['address_zip'];
$address_country = $keyarray['address_country'];
$gbtax = $keyarray['gbTaxPayer_radio'];
echo ("<p><strong>Payment Details</strong></p>\n");
echo ("<ul>\n");
echo ("<li><b>Address</b>: $address12</li>\n");
echo ("<li><b>Item Number</b>: $item_number</li>\n");
echo ("<li><b>Donation Type</b>: $itemname</li>\n");
echo ("<li><b>Date</b>: $payment_date</li>\n");
echo ("<li><b>Name</b>: $firstname $lastname ($payer_email)</li>\n");
echo ("<li><b>Street Address</b>: $address1</li>\n");
echo ("<li><b>Town/City</b>: $address_city</li>\n");
echo ("<li><b>County/State</b>: $address_state</li>\n");
echo ("<li><b>Postcode/ZIP</b>: $address_zip</li>\n");
echo ("<li><b>Country</b>: $address_country</li>\n");
echo ("<li><b>Amount</b>: £$amount</li>\n");
echo ("<li><b>Payment status</b>: $payment_status</li>\n");
echo ("<li><b>Transaction ID</b>: $transactionid</li>\n");
echo ("<li><b>UK Tax Payer?</b> $gbtax</li>\n");
echo ("</ul>\n");
// send e-mail
$today = date("F j, Y, g:i a");
mail("charityemail#internet.com", "Donation made - $itemname", "A donation was made on $today \n Payment Details \r\n\r\n Donation type: $itemname \r\n\r\n Name: $firstname $lastname \n Amount: $amount \n Donator Email: $payer_email \r\n\r\n Address: $address1 \n $address_city \n $address_state \n $address_zip \n $address_country \r\n\r\n Payment date: $payment_date \n Payment status: $payment_status \n Currency: $mc_currency \n Transaction ID: $transactionid \n UK Tax Payer? $gbtax \n", "From: Charity Donation <charityemail#internet.com>");
}
else if (strcmp ($lines[0], "FAIL") == 0) {
// log for manual investigation
}
}
fclose ($fp);
At the moment all I need to get working is the address to show on the email, return_url page and PayPal website (currently says Postal Address: Not Specified.)
Are you entering in an address when testing? Try passing over the variable "no_shipping" and setting the value to "2", and see if this makes a difference. Also PayPal will not pass back variables/values that are not valid PayPal variables, meaning you would not be able to make up your own variables and pass them over.

Joomla Paypal IPN always return INVALID

I've problem to veryfied the paypal payment on my joomla 1.5 website. I always get "INVALID" although the payment is success. i cannot get POST value from paypal, only can GET value. what's wrong with these code or the setting.
my paypal setting in sandbox.paypal.com
IPN : Turn On
Message delivery : enabled
notification url : http://mysite.com/index.php?option=com_order&type=orders
auto return : on
return url : http://mysite.com/index.php?option=com_order&type=orders
PDT : on
Encrypted Website Payments : off
PayPal Account Optional : off
in mycomponent joomla
payment.php
<form method="post" action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="paypal">
<input type="hidden" value="_xclick" name="cmd">
<input type="hidden" value="myname_1335697493_biz#gmail.com" name="business">
<input type="hidden" value="test payment" name="item_name" id="item_name">
<input type="hidden" value="11" name="item_number" id="item_number">
<input type="hidden" value="0.1" name="amount" id="amount">
<input type="hidden" value="USD" name="currency_code" id="currency_code">
<input type="hidden" value="<?php echo JURI::base();?>index.php?option=com_order&type=orders" name="return" id="return">
<input type="hidden" value="<?php echo JURI::base();?>index.php?option=com_order&type=orders" name="cancel_return" id="cancel_return">
<input type="hidden" value="<?php echo JURI::base();?>index.php?option=com_order&task=orders" name="notify_url" id="notify_url">
<input type="hidden" name="rm" value="2">
<table class="tblpay">
.....
</table>
</form>
on my controller.php
function display()
{
$user =& JFactory::getUser();
$type = JRequest::getVar('type');
switch($type) {
...
case 'orders':
$viewName = 'orders';
$viewLayout = 'orderslayout';
if (JRequest::getVar('tx') != null){
$this->processpayment();
$viewLayout = 'paymentlayout';
}
break;
...
}
function processpayment(){
// Response from Paypal
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
$get = JRequest::get('get');
foreach ($get as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// assign posted variables to local variables
$data['amount'] = JRequest::getVar('amt');
$data['currency'] = JRequest::getVar('cc');
$data['cm'] = JRequest::getVar('cm');
$data['idorder'] = JRequest::getVar('item_number');
$data['st'] = JRequest::getVar('st');
$data['tx'] = JRequest::getVar('tx');
$data['option'] = JRequest::getVar('option');
$data['type'] = JRequest::getVar('type');
$data['paymentresult'] = "";
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp($res, "VERIFIED") == 0) {
...
}else if (strcmp ($res, "INVALID") == 0) {
...
}
}
fclose ($fp);
}
//$redirectTo = str_replace("amp;","",JRoute::_('index.php?option='.JRequest::getVar('option').'&type=orders&layout=paymentlayout'));
//$this->setRedirect($redirectTo, '');
}
this is the result i get from paypal (use jdump):
[string] option = "com_order"
[string] type = "orders"
[string] tx = "9D9224627W344360N"
[string] st = "Completed"
[string] amt = "0.10"
[string] cc = "USD"
[string] cm = ""
[string] item_number = "41"
[string] Itemid = "" --> why i get this because i never send itemid?
Ok I have had a similar issue today and I think usually these 'INVALID' responses are usually when the submitted data is not exactly the same as the received data.
For me it was an issue with addressses but for you it probably is that Itemid. With my problem (which I'll just mention here since it may help others), paypal had been requested to send back the users address. Because paypal allows the street address to be multiple lines long it adds \r\n in between the lines of the address.
Its usually best practice to use something line this to send values back...
$value = urlencode( stripslashes( $value ) );
but this won't work if you have requested an address because it will strip the slashes from the \r\n so you just want to do a conditional so that if the key is address_street you just urlencode (or just get the address another way which I ended up doing)
In your case you can change the above code to
foreach ( $post as $key => $value ) {
if ($key != 'Itemid')
{
$value = urlencode( stripslashes( $value ) );
$req .= "&$key=$value";
}
}
Hope that solves it for you ;)

Contact form with file attachment?

I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.