How to pass Emails in Session Vars - php

I understand the basics of $_SESSION vars in php. I currently have a site that passes several values to and from pages that manage SQL queries throughout. I ran into a new problem:
I am using an email address as a Primary Key in my users table. I wish to pass this email to a second page (once the additional infomration is gathered from the server) and dynamically load content when the links are selected. This is my setup for my problem:
//Data returned from server:
// $FName = bob, $LName = rogers, $Email = bob#rogers.com
$_SESSION['userEmail'] = $Email;
$_SESSION['FirstName'] = $FName;
$_SESSION['LastName'] = $LName;
When I load the content on the second page, I recieve these values:
echo $_SESSION['userEmail']; //bob#rogers_com !!!!! THIS is not correct
echo $_SESSION['FirstName']; //bob
echo $_SESSION['LastName']; //rogers
The email is gathered from a POST form on the page. it is the only value within the form. On the first page, I retrieve the email using end(array_keys($_POST)), which is where "$_SESSION['userEmail'] = $Email" comes from. It is, more specifially, :: $_SESSION['userEmail'] = end(array_keys($_POST))::
How do I make it so the Email is passed safely through the request without being transformed?
After further troubleshooting, I have been able to determine that this transformation occurs in the POST request of the form. When clicked the form is using the POST method, which is intercepted in PHP using if($_SERVER['REQUEST_METHOD'] == 'POST'){}, where I capture the array of values (in my case, just the one email) - where the email is now transformed.

If you want use not transformed text such as hash, encode, etc,
you can try use alternative key alternative to your email primary key.
You can take hit from auto_increment index key each row.
Before:
select * from users where email = 'johndoe#johndoe.com';
After:
select * from users where id = '1';
This is equals to:
select * from users where id in (select id from users where email = 'johndoe#johndoe.com');
Good luck.

I have search and found this thing its work in Xampp localhost.This will be helpful.
/**
* Return parsed body in array format (without converting dots and spaces to underscore).
* #return array result parsed
*/
function fetch_parsed_body_nodots()
{
function DANODOT($string) {
$bes1= explode("&", $string);
foreach ($bes1 as $bes2) {
$bes2= explode("=",$bes2);
list($kilil, $beha) = array_map("urldecode", $bes2);
if(!empty($kilil)){
$te[$kilil] = $beha;
}
}
return $te;
}
return DANODOT($this->result_body);
}
http://forum.directadmin.com/showthread.php?t=48001

I figured out a work-around:
When you have the email, you can replace the chars '.' with a different sequence of characters; this is something that would not be found in a usual email address. I found that -#- is a decent one that works (generally). This is how I did it:
$TempFormat = strtr($row['UserEmail'], array('.' => '-#-'))
Then, when I went to my if($_SERVER['REQUEST_METHOD'] == 'POST'){} function, i transformed the string back to it's (hopefully) original state by performing:
$OriginalFormat = strtr(end(array_keys($_POST)), array('-#-' => '.'))

Related

how to generate unique referral code in php

I have created E-commerce website, In user system, I created referral system works like this -> When a visitor create an account then unique referral code for that customer will be generated. I fear that referral code should not be matched when I'll have a lot of users. So, I wanna create unique referral code.
I am creating like this:
$referral_code = strtolower(substr($first_name,0,3)).$this->refer_code(3);
public function refer_code($limit){
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}
Here, I am picking first 3 letters from user name and 3 random letters. It's generating referral code like this:
illqhx
But my boss said that It's very difficult to read and tell to other. So, he wants that referral code should be only numbers or 3 letters from name and 3 numbers should be generated automatically and it should be unique, and limit should be 5 or 6.
Please help me
Try this
function random_strings($length_of_string)
{
$str_result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// This function will generate
// Random string of length 10
echo random_strings(10);
?>
I recommend adding something like the following to your User class. You can use createReferralCode from the outside to retrieve the code. It will always return the same value. You could also just return $this and use an accessor method to retrieve the value.
How you save or validate your new key I'm leaving up to you.
/**
* Referral Code
*
* #var string
*/
protected $referralCode;
/**
* Create a referral code and store it on the User.
*
* #return string
*/
public function createReferralCode() : string
{
if (empty($this->referralCode)) {
// attempt to create a referral code until the one you have is unique
do {
$referralCode = $this->generateReferralCode();
} while (!$this->hasUniqueReferralCode($referralCode));
$this->referralCode = $referralCode;
}
return $this->referralCode;
}
/**
* Generate a referral code.
*
* #return string
*/
protected function generateReferralCode() : string
{
// generate crypto secure byte string
$bytes = random_bytes(8);
// convert to alphanumeric (also with =, + and /) string
$encoded = base64_encode($bytes);
// remove the chars we don't want
$stripped = str_replace(['=', '+', '/'], '', $encoded);
// get the prefix from the user name
$prefix = strtolower(substr($this->firstName, 0, 3));
// format the final referral code
return ($prefix . $stripped);
}
/**
* Check if the referral code is unique.
*
* #param string $referralCode
*
* #return boolean
*/
protected function hasUniqueReferralCode(string $referralCode) : bool
{
// check against database to enforce uniqueness
}
if($referrelid){
$condition = ' AND username LIKE "' . $referrelid. '" ';
$sql = $db->getRecFrmQry("SELECT ewallet FROM " . DB_TBLPREFIX . "_mbrs WHERE 1 " . $condition . "");
$ewallet = $sql[0]['ewallet'] + 50;
$data =array(
'ewallet' => $ewallet,
);
if (count($sql) > 0) {
$update = $db->update(DB_TBLPREFIX . '_mbrs', $data, array('username' => $referrelid));
}
}
When the new user creates an account with any refferel id, $50 added to his account when the account is created successfully.
If you want your referrer code to be only numbers, perhaps generating a unique code is not the best idea. Instead you can save the code in a database, start from 000001 and work your way up.
In this case you're guaranteed to have unique codes since you know all the previous codes.
This could also work with alphanumeric characters using the same principle. But starting with 000AAA or something similar.
Leaving aside the guaranteed non collision you can also keep track of issued referrer codes and invalidate them at will using a column such as is_active.
Concrete example from your code:
Lets assume that client Dave has referrer code illqhx. Lets also assume that client Linda wants a referrer code too.
Your code may look something like this:
// get dave's referrer code from the database
$dave_referrer_code = 'illqhx';
$linda_referrer_code = $dave_referrer_code++;
var_dump($dave_referrer_code); // illqhx
var_dump($linda_referrer_code); // illqhz
// Do note that this code won't work, it's just an example
What you should actually do is get the column with the largest id from the database, get the referrer code from there and increment that.
Having a unique index on the referrer_code column will guaranteed uniqueness since you can't have duplicate codes.
It makes much easier as far as I'm concerned.

Trying to print values in multidimensional array to form as presets values

I'm currently working on a project where my current goal is to print information about the specific user on the final checkout form inputs.
First off I gather the information of the specific user through a public function:
public function getUserAddress($dbh)
{
$sql = "SELECT street, zip, city FROM address WHERE user_id=:user";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':user', $this->uid);
$stmt->execute();
$userAddress = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->userAddress = $userAddress;
return $this->userAddress;
}
Then I store the information in a variable I call $userAddress
$userAddress = $user->getUserAddress($dbh);
Since the user has two addresses, both with a "Street", "City" & "Zip" I'm storing both arrays in $templateData. This way I can specify what index should be printed out in which input tag instead of having to create a new function for each slot.
$templateData['user']['address'] = $userAdress['street']." ".$userAddress['city']." ".$userAddress['zip'];
However, printing these out seems near impossible. When I var_dump
$templateData['user']['address']
I only seem to be getting 2 empty strings and nothing else.
This is just code from my Checkout.controller but somehow the information doesn't seem to be found in my template page. All routes and includes are correct so dw about that.
I'm quite new to all this so I'd appreciate any help I can get!
Image of how the information should be presented https://gyazo.com/40fa06832207bd785ee038af4962bb1e
So in this case: "Postort" = "City" & "Gatuadress" = "Street"
PDO::fetchAll(PDO::FETCH_ASSOC) will return an array of associative arrays; so to access the individual elements you need something like:
$userAdress[0]['street']." ".$userAddress[0]['city']." ".$userAddress[0]['zip']
I could alaways define every single one of them specifically although it seems far fetched. Something like this:
$templateData['user']['address'][0]['street'] = $userAddress[0]['street'];
$templateData['user']['address'][0]['city'] = $userAddress[0]['city'];
$templateData['user']['address'][0]['zip'] = $userAddress[0]['zip'];
$templateData['user']['address'][1]['street'] = $userAddress[1]['street'];
$templateData['user']['address'][1]['city'] = $userAddress[1]['city'];
$templateData['user']['address'][1]['zip'] = $userAddress[1]['zip'];
I'm basically looking for another solution which doesn't require so much repetition.

Trying to remove duplicate lines from array acc. to column contents

Using PHP and making a SELECT query from DB I am getting an output I don't like.
I start like this:
$details = Db::getInstance()->executeS($sql);
And I get, after a
echo json_encode($details);
For debug purposes:
[{"email":"test#on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]
[{"email":"test#on.gr","lastname":"OTHER","firstname":"DIFFERENT","id_lang":"1","id_order":"2"}]
[{"email":"test#on.gr","lastname":"THIRD","firstname":"DIFFERENT","id_lang":"1","id_order":"3"}]
[{"email":"new#on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]
What I want is to transform array $details to check on each "line" if the email column has unique values on the whole output. If yes to delete the lines that contain the duplicate entries and leave only the first that contain it.
Desired output:
[{"email":"test#on.gr","lastname":"TEST","firstname":"TEST1","id_lang":"1","id_order":"1"}]
[{"email":"new#on.gr","lastname":"THIRD","firstname":"NEW","id_lang":"1","id_order":"4"}]
(As you see lines with id order 2 and 3 where removed as they have the same email with the first)
Any kind of help will be highly appreciated.
Edit: just wanted to add up here that my code isn't in PHP. You have to change it.
Do an ORDER BY email command in the select statement.
Pseudo Code:
Loop through results:
String email1 = "";
String email2 = "";
for (i=0;i<(Detailssize); i++){
email2 = details[email][i]; //Do whatever you need to do to access the value of the email key here.
if(email2 != email1){
KEEP IT
}
else{
THROW AWAY
}
email1 = email2;
}
Obviously this is not PHP. It has been a while since i coded php. Nonetheless logically this should still work. I'm sure theres a way to change your SELECT statement to only return one from each value but i'm not good enough at SQL for that. This isn't as good of a solution but hope it helps.
Keep a list of emails you've seen before; whenever you encounter an email that has been seen before, skip that row.
Like this:
$newSet = array();
$seenBefore = array();
foreach( $details as $row ) {
if( isset( $seenBefore[ $row['email'] ) ) {
continue; // jump to the next row
}
// this email address must be new; add it to things we've seen before then add this row to the newSet
$seenBefore[$row['email']] = true;
$newSet[] = $row;
}
Then output $newSet in whichever way you want.

Forward a JSONencoded string to another page

I'm having trouble taking a string (called $name) from one page and outputing that string to another page.
This is a snippet of my code from where I think it is relevant:
if ($_POST['to'])
{
// Get all relevant messages
$get_msgs = mysql_query("SELECT * FROM messages WHERE touser='$from'");
$mailbox = array();
while($row = mysql_fetch_assoc($get_msgs))
{
$mailbox[] = $row;
}
// Make a string with the JSON array in it
$name = "{ \"mailbox\":".json_encode($mailbox)." }";
// now here, how do I simply forward this string to a page called page2.php
}
A. What should the code be for page2.php? (even though all I want it to do is really just echo $name)
B. If I run the above code multiple times, would page2.php be cleared, and refreshed each time with the new $name?
Thank you in advance for the help guys.
I tried this:
session_start();
$_SESSION['myValue']=$name;
And in page2 used:
session_start();
echo $_SESSION['myValue'];
But no data was forwarded to page 2
you have 3 way :
some one set session to passing array to new page :
sesstion_strat() ;
$_SESSION['name'] = $name ;
-> in page2
sesstion_strat() ;
$name = $_SESSION['name'] ;
2en way :
pass array with get method , this method not good for long arrays and spcial chars.
header("Location: page2.php?name=".$name);
-> in page2
$name = $_GET['name'] ;
or use curl for post data :
you see sample here :
http://php.net/manual/en/book.curl.php

Adding input field to PHP emailer only if it exists, how?

I have a form with inputs for 'name' and 'email'. And another for 'data-1'. The user can click on add button and jQuery will dynamically add a input for 'data-2', 'data-3' etc..as needed.
The form is posted to a PHP emailer script which validates fields and places data into a template for mailing.
How can i add inputs 'data-2', 'data-3' etc.. if they are created? And if they are not how can i avoid gaps in my email template?
(is there a way to write it so if the post is received add this and if not do nothing?)
Here is an example of the code i am using:
$name = $_POST['name'];
$email = $_POST['email'];
$data-1 = $_POST['data-1'];
(do i need to add: $data-2 = $_POST['data-2'] and $data-3....up to a set value of say 10?)
$e_body = "You were contacted by $name today.\r\n\n";
$e_data = "Data Set 1: $data-1.\r\n\n";
Here is where i would like to show "Data Set 2/3/4....etc" if they exist
$e_reply = "You can contact $name via email, $email";
$msg = $e_body . $e_data . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) {
I hope that is clear and thank you for any help or guidance
thom
You should be using input arrays for this purpose.
In your HTML, set the name of the form element to conform to this naming scheme: data[].
Then, when the form is submitted you can simply loop through this array and add fields to the email within the loop:
$name = $_POST['name'];
$email = $_POST['email'];
$data = $_POST['data'];
$e_data = '';
foreach($data as $i => $d) {
if((int) $i != $i) continue; //thanks Alex
$e_data .= "Data Set {$i}: " . $d . "\r\n\n";
}
//...
On the client side, your code should be something like this:
<input type="hidden" name="data[]"/>
As a general point form processing is trick and has many traps for the unwary. It's worth having a look at this post on best practice form processing
The crux of your problem is that you do not know how many "data" values you will get in your $_POST array. The answer is simply to iterate over the $_POST array to find your data values.
$rawData = array();
foreach ($_POST as $index => $value) {
// Test for a "data-n" index
if ((preg_match('#^data-\d+#i', $index, $matches))) {
$rawData[] = $value;
}
}
The above code will copy all the $_POST values with keys of the form 'data-0', 'data-1', etc. You can then filter and validate these values.
All we do is iterate over $_POST to get each key and value. We then test the key using preg_match to see if it starts with the string 'data-' and is followed by one or more digits. If so, we add it to our raw (unfiltered, non validated) data.
In this example, we could replace the preg_match with the strpos function -
if ( strpos ($index, 'data-') === 0) {
The use of the preg_match gives us more flexibility. For example, if you wanted to capture the numeric portion of your 'data-n' keys - 'data-23', 'data-999', 'data-5', etc. Then change the if statement to
if ((preg_match('#^data-(\d+)#i', $index, $matches))) {
$rawData[$matches[1]] = $value;
}
The variable $matches is an array that captures the results of the search. The complete matching string is is $matches[0]. However, we have enclosed the digit matching pattern in parenthesis and hence the captured digits are placed into $matches1 which we then use to key the $rawData array. In this case $rawData would have the keys = 23, 999 and 5.
Use something like this:
if(isset($_POST['data-1']))
{
// $_POST['data-1'] exists, include it.
}
else
{
// $_POST['data-1'] doesn't exists, don't include it.
}

Categories