Account activation link in email after registration cakephp - php

I am using cakephp 2.6. i need to send account activation link in email after successful registration and
if the user clicks on activation link then the status field of my database to be updated with 1.
My email is going to be correctly but i don know how to send link inside email by getting lastinsertid as a unique identifier in email and update the account after click.
please help me to out of this.
function add() {
$this->layout = "layout_login";
$this->pageTitle = "Add Admin";
$this->set("pageTitle", "Add Admin");
if (!empty($this->request->data)) {
$this->User->set($this->data['User']);
$isValidated = $this->User->validates();
if ($isValidated) {
// Generating UUID
$this->data['User']['activation_key'] = $activation_key = String::uuid();
$this->User->save($this->data, array('validate' => false));
$this->Session->setFlash(__('Please check your email for account verification.'));
$subject = "Account Activation link By Kaya Dispatch";
$to = trim($this->request->data['User']['email']);
$this->Email->sendAs = 'html';
$this->Email->from = 'luckybajpai87#gmail.com';
$this->Email->to = $to;
$this->Email->subject = $subject;
$activationUrl = Router::url(['controller' => 'users', 'action' => 'activate/' . $activation_key ]);
$message = "Dear <span style='color:#666666'>" . $name . "</span>,<br/><br/>";
$message .= "Your account has been created successfully by Administrator.<br/>";
$message .= "Please find the below details of your account: <br/><br/>";
$message .= "<b>Activate your account by clicking on the below url:</b> <br/>";
$message .= "<a href='$activationUrl'>$activationUrl</a><br/><br/>";
$message .= "<br/>Thanks, <br/>Support Team";
$this->Email->send($message);
}
}
}
below is my account activation code
function activate($activation_key) {
$userData = $this->User->find('first', array(
'conditions' => array(
'User.activation_key' => $activation_key,
'User.status' => 0
)
));
if( !empty($userData)){
if ($userData['User']['status'] == 0)
{
$activeStatus = 1;
}
$status = $this->User->updateAll(array('User.status' => $activeStatus), array('User.id' => $id));
if ($status)
{ $this->Session->setFlash(__('Status updated successfully'));
} else
{ $this->Session->setFlash(__('Something went wrong, please try again.'));
}
$this->redirect(array('controller' => 'Users', 'action' => 'index'));
}
}

Well, this is something logical, I mean this is totally depends how you wanna do that. I am writing my way :)
Make new column in your users table i.e. activation_key, and set it before inserting it into the Table. Like this:
if ($isValidated) {
$password = $this->data['User']['password'];
$this->data['User']['password'] = md5($this->data['User']['password']);
// Generating UUID
$this->data['User']['activation_key'] = $activation_key = String::uuid();
$this->User->save($this->data, array('validate' => false));
$this->Session->setFlash("<div class='success-message flash notice'>Admin has been created successfully.</div>");
$subject = "Account Activation link send on your email";
$name = $this->request->data['User']['fname'] . " " . $this->request->data['User']['lname'];
$to = trim($this->request->data['User']['email']);
$this->Email->sendAs = 'html';
$this->Email->from = 'luckybajpai87#gmail.com';
$this->Email->to = $to;
$this->Email->subject = $subject;
$activationUrl = Router::url(['controller' => 'users', 'action' => 'activate/' . $activation_key ]);
// Always try to write clean code, so that you can read it :) :
$message = "Dear <span style='color:#666666'>" . $name . "</span>,<br/><br/>";
$message .= "Your account has been created successfully by Administrator.<br/>";
$message .= "Please find the below details of your account: <br/><br/>";
$message .= "<b>First Name:</b> " . $this->data['User']['fname'] . "<br/>";
$message .= "<b>Last Name:</b> " . $this->data['User']['lname'] . ((!empty($this->data['User']['phone'])) ? "<br/>";
$message .= "<b>Phone:</b> " . $this->data['User']['phone'] : "") . "<br/>";
$message .= "<b>Address:</b> " . $this->data['User']['address1'] . " " . $this->data['User']['address2'] . "<br/>";
$message .= "<b>Email:</b> " . $this->data['User']['email'] . "<br/>";
$message .= "<b>Username:</b> " . $this->data['User']['username'] . "<br/>";
$message .= "<b>Password:</b> " . $password . "<br/>";
$message .= "<b>Activate your account by clicking on the below url:</b> <br/>";
$message .= "<a href='$activationUrl'>$activationUrl</a><br/><br/>";
$message .= "<br/>Thanks, <br/>Support Team";
$this->Email->send($message);
}
And then in your function activate($activation_key='') receive that activation key as a parameter, and find from users like this:
// Finding user data from users table on behalf of activation key
// and Status should be 0 (deactivate). So that, a URL can be use only ONCE.
$userData = $this->User->find('first', array(
'conditions' => array(
'User.activation_key' => $activation_key,
'User.status' => 0
)
));
if( !empty($userData) ){
// $userData as you have User's data update the status as 1 and set activation_key as empty "";
}else{
// So, you don't find any user, it is an invalid request.
}
Sometime, it happens that Cakephp do not allow you to update $this->data as in this example we are trying to change $this->data['User']['password'] and $this->data['User']['activation_key'] values so you can simply store $postData = $this->data and then use $postData for insertion and further operations.
Update: Please confirm/debug if String::uuid() is working correctly for you, if it dosn't work, try to use the below line for this purpose:
// Generating activation_key
$this->data['User']['activation_key'] = $activation_key = time();
Thank you!

Related

Send learners reminder email and admin

Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>
mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?
below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}

Need help updating from md5 to sha-512 Authorize.net

I am new to authorize.net and i receive an email from them saying that they are phasing out md5 hash and i have to move to sha-512 hash via signature key, but i don't have any idea how to do that.
I have followed the hello world (PHP) steps from their website: https://developer.authorize.net/hello_world/ and it's working fine.
I don't have any md5 on my codes, and I'm thinking that maybe the sdk I'm currently using has that code.
This is my code when charging customer's credit card
function chargeCreditCard($arrayPost, $creditCardNum, $creditCardExp, $creditCardCode)
{
$totalAmountDue = str_replace(',', '', $arrayPost['total-due']);
// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(X_API_LOGIN);
$merchantAuthentication->setTransactionKey(X_TRAN_KEY);
$refId = 'ref' . time();
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber($creditCardNum);
$creditCard->setExpirationDate($creditCardExp);
$creditCard->setCardCode($creditCardCode);
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
$order = new AnetAPI\OrderType();
$order->setInvoiceNumber($arrayPost['invoice']);
$order->setDescription(PRODUCT_DESCRIPTION);
// Set the customer's Bill To address
$customerAddress = new AnetAPI\CustomerAddressType();
$customerAddress->setFirstName($arrayPost['fname']);
$customerAddress->setLastName($arrayPost['lname']);
$customerAddress->setCompany($arrayPost['company']);
$customerAddress->setAddress($arrayPost['address']);
$customerAddress->setCity($arrayPost['city']);
$customerAddress->setState($arrayPost['state']);
$customerAddress->setZip($arrayPost['zip']);
$customerAddress->setCountry($arrayPost['country']);
// Create a TransactionRequestType object
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($totalAmountDue);
$transactionRequestType->setOrder($order);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setBillTo($customerAddress);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);
if ($response != null) {
$tresponse = $response->getTransactionResponse();
if ($response->getMessages()->getResultCode() == "Ok") {
if ($tresponse != null && $tresponse->getMessages() != null) {
$messages = "";
$errors = "";
$responseCode = $tresponse->getResponseCode();
$rawResponseCode = $tresponse->getRawResponseCode();
$authCode = $tresponse->getAuthCode();
$avsResultCode = $tresponse->getAvsResultCode();
$cvvResultCode = $tresponse->getCvvResultCode();
$cavvResultCode = $tresponse->getCavvResultCode();
$transId = $tresponse->getTransId();
$refTransID = $tresponse->getRefTransID();
$transHash = $tresponse->getTransHash();
$testRequest = $tresponse->getTestRequest();
$accountNumber = $tresponse->getAccountNumber();
$entryMode = $tresponse->getEntryMode();
$accountType = $tresponse->getAccountType();
$splitTenderId = $tresponse->getSplitTenderId();
$prePaidCard = $tresponse->getPrePaidCard();
if($tresponse->getMessages() != null){
$messages .= " Code : " . $tresponse->getMessages()[0]->getCode() . "\n";
$messages .= " Description : " . $tresponse->getMessages()[0]->getDescription() . "\n";
}
if($tresponse->getErrors() != null){
$errors .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$errors .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
}
$splitTenderPayments = serialize($tresponse->getSplitTenderPayments());
$userFields = serialize($tresponse->getUserFields());
$shipTo = $tresponse->getShipTo();
$secureAcceptance = $tresponse->getSecureAcceptance();
$emvResponse = $tresponse->getEmvResponse();
$transHashSha2 = $tresponse->getTransHashSha2();
//$profile = $tresponse->getProfile();
$profile = "";
//SAVE PERSONAL DETAILS
$personal_detail_id = $this->objEcommerceModel->savePersonalDetails($arrayPost['fname'], $arrayPost['lname'], $arrayPost['company'], $arrayPost['address'], $arrayPost['city'], $arrayPost['state'], $arrayPost['zip'], $arrayPost['country']);
//SAVE MERCHANT LOGS
$this->objEcommerceModel->saveMerchantTransactionLogs($personal_detail_id, $responseCode, $rawResponseCode, $authCode, $avsResultCode, $cvvResultCode, $cavvResultCode, $transId, $refTransID, $transHash, $testRequest, $accountNumber, $entryMode, $accountType, $splitTenderId, $prePaidCard, $messages, $errors, $splitTenderPayments, $userFields, $shipTo, $secureAcceptance, $emvResponse, $transHashSha2, $profile);
return 'Success';
} else {
$msg = "Transaction Failed \n";
if ($tresponse->getErrors() != null) {
$msg .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$msg .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
}
}
} else {
$msg = "Transaction Failed \n";
$tresponse = $response->getTransactionResponse();
if ($tresponse != null && $tresponse->getErrors() != null) {
$msg .= " Error code : " . $tresponse->getErrors()[0]->getErrorCode() . "\n";
$msg .= " Error message : " . $tresponse->getErrors()[0]->getErrorText() . "\n";
} else {
$msg .= " Error code : " . $response->getMessages()->getMessage()[0]->getCode() . "\n";
$msg .= " Error message : " . $response->getMessages()->getMessage()[0]->getText() . "\n";
}
}
} else {
$msg .= "No response returned \n";
}
}
The MD5 hash is only used to verify a transaction response is actually from Authorize.Net. This code processes a transaction using the AIM API which typically does not need to verify the response since you get it as a result of your direct call to Authorize.Net. The MD5 hash is typically used by SIM and DPM API users who do not have a direct connection to Authorize.Net and thus need a way to verify the response is authentic.

PHP Script is not inserting values into Database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For whatever reason, whenever I submit the form, it doesn't add the inputted data to the database. It was working before... Which I think is what's frustrating me the most. I came back to it a couple of hours later, and surprise! Not inserting new rows into the database. Perhaps there's a slight error I may have done subconsciously by accident? Nothing stands out to me, though. :(
refer.html: http://pastebin.com/d1xQUJLR
generator.php: http://pastebin.com/CE2UX8zs
main.js: http://pastebin.com/CSQh9DKs
Just fixed some bugs in your code ;)
<?php
include_once "access.php";
$ref_email = $_POST["tf_ref_email"];
$ref_username = $_POST["tf_ref_username"];
$ref_ign = $_POST["tf_ref_ign"];
$access = new Access();
$crux = $access->getCrux();
$anchor = $access->getAnchor();
$user = $access->getUser();
try {
$pdo = new PDO($anchor, $user, $crux);
$stq = "INSERT INTO referred_users
(ref_id, ref_email, ref_username, ref_ign, ref_awarded, new_email, new_awarded)
VALUES (:ref_id, :ref_email, :ref_username, :ref_ign, :ref_awarded, :new_email, :new_awarded)";
for($i = 0; $i < min(count($_POST["emails"]), 10); $i++) {
$ref_id = $_POST["ref_ids"][$i];
$new_email = $_POST["emails"][$i];
$new_ref_id = checkId($ref_id, $pdo);
$query = $pdo->prepare($stq);
$results = $query->execute(
array(
':ref_id' => $new_ref_id,
':ref_email' => $ref_email,
':ref_username' => $ref_username,
':ref_ign' => $ref_ign,
':ref_awarded' => '0',
':new_email' => $new_email,
':new_awarded' => '0'
)
);
$to = $new_email;
$subject = "Check out this AMAZING Minecraft RP Server!";
$message = "You have been invited to join " . $ref_ign . " in Arithia! Enter your Referral ID in the provided link to get a head start on your first character!" . "\n";
$message .= "Referral ID: " . $new_ref_id . "\n";
$message .= "Redeem Rewards: " . "http://www.graphicgoldfish.com/referral/referral.html" . "\n";
$message .= "By redeeming your referral, you will get:" . "\n";
$message .= "- 300 Credit Points" . "\n";
$message .= "- 50 Ducats" . "\n";
$message .= "- 25 Cooked Beef" . "\n";
$message .= "- Identification Tome" . "\n";
$message .= "We look forward to seeing you in Arithia! For more information, visit: http://www.arithia.com" . "\n";
$headers = "From: $ref_email";
mail($to, $subject, $message, $headers);
}
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
function checkId($id, $con) {
$stmt = $con->prepare("SELECT ref_id FROM referred_users WHERE ref_id = :ref_id");
$stmt->bindParam(':ref_id', $id);
$stmt->execute();
if($stmt->rowCount() > 0) {
$new_id = (string)rand(1000000, 9999999);
return checkId($new_id, $con);
}
return $id;
}

MySQL/PHP will not insert into database

I've been trying to add an email confirmation system to my website when people sign up and create an account but it will not add the key and the user id in the database. The other problem I'm running across is I'm trying to send a confirmation email but the email does not send. It echo's "message sent successfully" but when I check the email I put in, it is not received. Thanks in advance for your help! And yes, I am aware that mysql is prone to sql injection, but I would like to figure this out with mysql.
Here is my code:
EDIT: I replaced $insert_confirm with $hin and I renamed the table confirm to email_confirmation to maybe get rid of reserved words but I'm still getting an error
<?php
require_once '../scripts2/app_config.php';
require_once '../scripts2/database_connection.php';
$upload_dir = HOST_WWW_ROOT . "/uploads/profile_pics/";
$image_fieldname = "user_pic";
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$name = $first_name . " " . $last_name;
$username = trim($_REQUEST['username']);
$password = trim($_REQUEST['password']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
if(isset($_POST['submit1'])) {
if($_POST['picture'] == 'picture1') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else if($_POST['picture'] == 'picture2') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387547040-auto_pic_grey2.png";
} else if($_POST['picture'] == 'picture3') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
}
}
$bgcolor = "#FF0000";
$check_email = "SELECT `email`" .
" FROM users" .
" WHERE `email` = '$email'";
$query_email = mysql_query($check_email);
$check_username = "SELECT `username`" .
" FROM users" .
" WHERE `username` = '$username'";
$query_username = mysql_query($check_username);
if(mysql_num_rows($query_email)>0 || mysql_num_rows($query_username)>0 ) {
if(mysql_num_rows($query_email)>0) {
$email_msg = "This email is already taken: {$email}";
header("Location:signup2.php?error_message={$email_msg}");
} else if(mysql_num_rows($query_username)>0) {
$username_msg = "This username is already taken: {$username}";
header("Location:signup2.php?error_message={$username_msg}");
} else {
$msg = "This email and username is already taken: {$email} , {$username}";
header("Location:signup2.php?error_message={$msg}");
}
} else {
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, name, username, " .
"password, email, " .
"bio, " .
"user_pic_path, bgcolor) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($name),
mysql_real_escape_string($username),
mysql_real_escape_string(crypt($password, $username)),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($radio_value),
mysql_real_escape_string($bgcolor));
//insert the user into the database
$insert_user = mysql_query($insert_sql);
$private_user_id = mysql_insert_id();
function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$private_user_key = generateRandomString();
$hin = sprintf("INSERT INTO email_confirmation " .
"(user_id, key) " .
"VALUES (%d, '%s');",
mysql_real_escape_string($private_user_id),
mysql_real_escape_string($private_user_key));
//insert the user into the database
mysql_query($hin);
echo mysql_error();
$name = mysql_real_escape_string($_POST['name']);
$create_user_table = mysql_query("CREATE TABLE `".$email."` ( friend_id INT, friend_status INT)");
if($insert_user && $create_user_table) {
// Email the new user the confirmation key
$to = $email;
$subject = 'Welcome!';
$message = "
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>Please click the following link to confirm your email:</p>
<p>Confirm Email</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: Admin <email#email.com>' . "\r\n";
// Mail it
$retval = mail($to, $subject, $message, $headers);
if( $retval == true )
{
echo "Message sent successfully...";
echo "\n" . $to . "\n" . $message . "\n" . "\n" . $subject;
}
else
{
echo "Message could not be sent...";
}
}
//Redirect this user to the page that displays user information
// $msg = "Please check your email to confirm your email address";
// header("Location: newuser_signinA.php?error_message={$msg}");
// exit();
}
?>

PHP POST form validating error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got a PHP form that executes on the contact form's page. I've got it working well - but it currently only checks to make sure name and email are entered. I'm trying to get it to check for a message too, but my attempts just cos the page not to load after the php. Here's what I have:
<?php
$to = "me#gmail.com" ;
$from = $_REQUEST['Email'] ;
$name = $_REQUEST['Name'] ;
$headers = "From: $from";
$subject = "Web Contact Data";
$startmonth = $_REQUEST['StartMonth'];
$startyear = $_REQUEST['StartYear'];
$endmonth = $_REQUEST['EndMonth'];
$endyear = $_REQUEST['EndYear'];
$message = $_REQUEST['Message'];
$fields = array();
$fields{"Name"} = "Name";
$fields{"Email"} = "Email";
$fields{"Phone"} = "Phone";
$selectedProjects = 'None';
if(isset($_POST['projects']) && is_array($_POST['projects']) && count($_POST['projects']) > 0){
$selectedProjects = implode(', ', $_POST['projects']);
}
$selectedSkills = 'None';
if(isset($_POST['skills']) && is_array($_POST['skills']) && count($_POST['skills']) > 0){
$selectedSkills = implode(', ', $_POST['skills']);
}
$selectedNoRush = 'None';
if(isset($_POST['norush']) && is_array($_POST['norush']) && count($_POST['norush']) > 0){
$NoRush= implode(', ', $_POST['norush']);
}
$selectedWhenReady = 'None';
if(isset($_POST['whenready']) && is_array($_POST['whenready']) && count($_POST['whenready']) > 0){
$WhenReady= implode(', ', $_POST['whenready']);
}
$selectedBudget = 'None';
if(isset($_POST['budget']) && is_array($_POST['budget']) && count($_POST['budget']) > 0){
$selectedBudget= implode(', ', $_POST['budget']);
}
$body = "We have received the following information:\n\n"; foreach($fields as $a => $b){$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]);}
$body .= "\n" . 'Selected Projects: ' . $selectedProjects . "\n";
$body .= 'Selected Skills: ' . $selectedSkills . "\n\n";
$body .= 'Start Date: ' . $startmonth . " " . $startyear . " " . $NoRush . "\n";
$body .= 'End Date: ' . $endmonth . " " . $endyear . " " . $WhenReady . "\n";
$body .= 'Budget: ' . $selectedBudget . "\n\n";
$body .= 'Message:' . $message . "\n";
$headers2 = "From: me#gmail.com";
$subject2 = "Thank you for contacting us";
$autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usually within 48 hours.";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send)
{print "Thank you. Your request has been successfully submitted.";}
else
{print "We encountered an error sending your mail, please check your details are correct or email us at hello#lyonempire.co.uk"; }
}
}
?>
So the above all works fine, but when I add the following code after the name/email checks, it breaks:
if($message == '') {print "You have not entered a message, please go back and try again";}
else {
What am I doing wrong?
Thanks! MC
if($name == '')
{
print "You have not entered a name, please go back and try again";
}
else if($message == '') {
// do what ever you want
}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
.... Rest goes here
i cant tell from the code you've shown, but have you closed the curly bracket on your else statement?
if($message == '') {print "You have not entered a message, please go back and try again";}
else {} <----

Categories