Allow only mails with #gmail.com ending - php

This Github repository serves to add a dot (.) to a Gmail address and thus register on a site multiple times with random addresses derived from the original.
The code works fine, but it works with any domain (e.g. #house.com)
And I need to limit it to only work with #gmail.com (I tried this in my HTML) <input type="email" pattern="^[a-zA-Z0-9]+#gmail\.com$">
But I prefer it to be server side, I have no idea how to do it, I am new in PHP.
Thanks in advance.
PHP Code:
<?php
set_time_limit(0);
if(isset($_POST['email']))
{
$mail = explode('#', $_POST['email']);
$email = $mail[0];
$domain = '#'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total: '.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
function addDOT($str){
if(strlen($str) > 1)
{
$ca = preg_split("//",$str);
array_shift($ca);
array_pop($ca);
$head = array_shift($ca);
$res = addDOT(join('',$ca));
$result = array();
foreach($res as $val)
{
$result[] = $head . $val;
$result[] = $head . '.' .$val;
}
return $result;
}
return array($str);
}
?>

With PHP 8+ you can use str_ends_with().
function isGmail($email) {
return str_ends_with($email, '#gmail.com');
}
Or a prior PHP8+ with a classic regex
function isGmail($email) {
return preg_match("/#gmail.com\$/", $email);
}
or strpos with a negative offset
function isGmail($email) {
$pattern = '#gmail.com';
return (false !== strpos($email, $pattern, -strlen($pattern)));
}
Update
Regarding from your comment I think you want to do something like this:
$email = $_POST['email'] ?? '';
if(!isGmail($email)) {
header('Location: /');
exit();
}

<?php
set_time_limit(0);
if(isset($_POST['email']))
{
if(isGmail($_POST['email'])){
$mail = explode('#', $_POST['email']);
$email = $mail[0];
$domain = '#'.$mail[1];
$email = ltrim($email);
$domain = ltrim($domain);
$email = rtrim($email);
$domain = rtrim($domain);
$email = stripslashes($email);
$domain = stripslashes($domain);
$email = htmlentities($email);
$domain = htmlentities($domain);
$res = addDOT($email);
echo '<div class="box"><div class="title">Total:'.sizeof($res).'</div><textarea type="text">';
foreach($res as $mcMails)
{
echo nl2br($mcMails.$domain).PHP_EOL;
}
echo '</textarea></div>';
}
}
function addDOT($str){
if(strlen($str) > 1)
{
$ca = preg_split("//",$str);
array_shift($ca);
array_pop($ca);
$head = array_shift($ca);
$res = addDOT(join('',$ca));
$result = array();
foreach($res as $val)
{
$result[] = $head . $val;
$result[] = $head . '.' .$val;
}
return $result;
}
return array($str);
}
/**
* Check if an email is a Gmail address
* #param string $email The email address to check
* #return boolean
*/
function isGmail($email) {
$email = trim($email); // in case there's any whitespace
return mb_substr($email, -10) === '#gmail.com';
}
?>

Fixed. I modified the first if of the code by putting a second conditional:
if(isset($_POST['email']) and (substr($_POST['email'], -10) == '#gmail.com'))

Related

Trim Error occuring in PHP

I am designing an application and in my modal came across a strange error
<b>Warning</b>: trim() expects parameter 1 to be string, array given in <b>C:\xampp\htdocs\gurukul\demo2\controller\routemgmt\route_mgmt.php</b> on line <b>7</b><br />
61
As far as I can understand its passing an array instead of string in trim. Below is the modal where its showing the error lies :
<?php
include_once dirname(dirname(dirname(__FILE__))) . "/const.php";
include_once PHP_PATH . "/config1.php";
include_once CONFIG_PATH.'/modal/routemgmt/route_mgmt.php';
function sanitize($input) {
return htmlspecialchars(trim($input));
}
// Sanitize all the incoming data
$sanitized = array_map('sanitize', $_POST);
$reason = $sanitized['reason'];
if($reason == "insert"){
$staffs = [];
$stops = [];
$name = $sanitized['rname'];
$code = $sanitized['rcode'];
$desc = $sanitized['rdesc'];
$vnum = $sanitized['vnum'];
$stf = $_POST['staff'];
$st = isset($_POST['stops'])? $_POST['stops']: [];
$st = [];
// foreach($staffs as $staff){
// $stf[] = array_map('sanitize', $staff);
// }
// if(isset($stops)){
// foreach($stops as $stop){
// $st[] = array_map('sanitize', $stop);
// }
// }
$val = insertRoute($conn,$name, $code, $desc, $vnum, $stf, $stops);
echo $val;
}
if($reason == "view"){
$id = $sanitized['id'];
$val = [];
$val = viewRoute($conn,$id);
echo json_encode($val);
}
if($reason == "edit"){
$stf = [];
$stp = [];
$id = $sanitized['pkid'];
$name = $sanitized['rname'];
$code = $sanitized['rcode'];
$desc = $sanitized['rdesc'];
$vnum = $sanitized['vnum'];
$estaffs = $_POST['estaff'];
$estops = $_POST['estops'];
$edel = $_POST['del'];
foreach($estaffs as $val){
$stf[] = array_map('sanitize', $val);
}
foreach($estops as $val){
$stp[] = array_map('sanitize', $val);
}
$cnt = 0;$n_stp = [];
for($i = 0; $i<sizeof($stp); $i++){
if($stp[$i]['stat'] != "Exist"){
$n_stp[$cnt] = $stp[$i];
$cnt++;
}
}
$val = editValues($conn,$id, $name, $code, $desc, $vnum, $stf, $n_stp, $edel);
echo $val;
}
if($reason == "delRoute"){
$id = $sanitized['id'];
$val = delRoute($conn,$id);
echo $val;
}
Can someone please guide me how can I resolve this ? Tried few debugging steps but didnt get succeded
You could rewrite your sanitize function as:
function sanitize($input) {
if (is_array($input))
return array_map('sanitize', $input);
else
return htmlspecialchars(trim($input));
}
That way it will handle a value passed to it which is an array.
Your $_POST variable probably contains some kind of array. Either figure out what you're posting by checking the output of var_dump($input) inside your sanitize function or change it to this:
function sanitize($input) {
return htmlspecialchars(trim((string) $input));
}
if you just want it to work.

How I can do this PHP If Statement in right way?

I have 50 variables in php. I want to check each of them and if they true then add 2 points in a variable called $point. I am new so I write a few lines but I think I am doing wrong way.
$strenght_point = 0;
if($f_name){$strenght_point++;}
if($l_name){$strenght_point + 2;}
if($full_name){$strenght_point + 2;}
How can I do it right way.Thanks
Update my full function is here...
It's Codeigniter Controller Function
Hope you guys understand well now
function strength_scale() {
$user_id = $this->uri->segment(2);
$user_name = $this->uri->segment(3);
$query = $this->db->get_where('aoa_user', array('id' => $user_id, 'username' => $user_name));
foreach ($query->result() as $row){
$f_name = $row->f_name;
$l_name = $row->l_name;
$full_name = $row->full_name;
$username = $row->username;
$alias_name = $row->alias_name;
$gender = $row->gender;
$country = $row->country;
$avatar = $row->avatar;
$cover_photo = $row->cover_photo;
$email = $row->email;
$skill = $row->skill;
$other_skills = $row->other_skills;
$ex_time = $row->ex_time;
$about = $row->about;
$company = $row->company;
$company_position = $row->company_position;
$phone = $row->phone;
$facebook = $row->facebook;
$facebook_page = $row->facebook_page;
$google_plus = $row->google_plus;
$twitter = $row->twitter;
$youtube = $row->youtube;
$skype = $row->skype;
$linkedin = $row->linkedin;
$website = $row->website;
$latitude = $row->latitude;
$longitude = $row->longitude;
$verification = $row->verification;
}
$strength_point = 0;
if($f_name){$strength_point++;}
if($l_name){$strength_point + 2;}
if($full_name){$strength_point + 2;}
}
Create an array with the variables instead.
https://3v4l.org/FYTtG
$arr = array("f_name" => true, "l_name" => true, "full_name" => true);
$strength=0;
Foreach($arr as $var){
if($var) $strength = $strength+2;
}
Echo $strength;
As Rizier123 said, you need to increment your strength variable correcly.
You could write a simple function that would accept one of your 50 variables and return the strength increment:
function defineStrength($param)
{
if ($param) {
return 2;
}
return 0;
}
$strength = 0;
$f_name = true;
$l_name = false;
$full_name = false;
$strength += defineStrength($f_name);
$strength += defineStrength($l_name);
$strength += defineStrength($full_name);
However, an array would be a better way to go, as Andreas mentionned.
In your question update you said you use CodeIgniter. As the documentation states you can return the query result as a pure array.
So you could further develop like that :
function defineStrengthFromArray(array $row)
{
$strength = 0;
foreach ($row as $param) {
$strength += defineStrength($param);
}
return $strength;
}
foreach ($query->result_array() as $row){
$strength = defineStrengthFromArray($row);
}

add target='_top" to php header location

I am using some new software that includes a login php setup. Works fine until I decided to open the login page in a lightbox. Now I can't break out of the light box to a normal view browser page for my success destination page. The php code is as follows;
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_name']) && $_POST['form_name'] == 'loginform')
{
$success_page = './club_registered_breeders_only.php';
$error_page = './Error_form_failure.html';
$database = './usersdb.php';
$crypt_pass = md5($_POST['password']);
$found = false;
$fullname = '';
$session_timeout = 600;
if(filesize($database) > 0)
{
$items = file($database, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($items as $line)
{
list($username, $password, $email, $name, $active) = explode('|', trim($line));
if ($username == $_POST['username'] && $active != "0" && $password == $crypt_pass)
{
$found = true;
$fullname = $name;
}
}
}
if($found == false)
{
header('Location: '.$error_page);
exit;
}
else
{
if (session_id() == "")
{
session_start();
}
$_SESSION['username'] = $_POST['username'];
$_SESSION['fullname'] = $fullname;
$_SESSION['expires_by'] = time() + $session_timeout;
$_SESSION['expires_timeout'] = $session_timeout;
$rememberme = isset($_POST['rememberme']) ? true : false;
if ($rememberme)
{
setcookie('username', $_POST['username'], time() + 3600*24*30);
setcookie('password', $_POST['password'], time() + 3600*24*30);
}
header('Location: '.$success_page);
exit;
}
}
$username = isset($_COOKIE['username']) ? $_COOKIE['username'] : '';
$password = isset($_COOKIE['password']) ? $_COOKIE['password'] : '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_name']) && $_POST['form_name'] == 'forgotpasswordform')
{
$email = isset($_POST['email']) ? addslashes($_POST['email']) : '';
$found = false;
$items = array();
$success_page = '';
$error_page = './Error_form_failure.html';
$database = './usersdb.php';
if (filesize($database) == 0 || empty($email))
{
header('Location: '.$error_page);
exit;
}
else
{
$items = file($database, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($items as $line)
{
list($username, $password, $emailaddress, $fullname, $active) = explode('|', trim($line));
if ($email == $emailaddress && $active != "0")
{
$found = true;
}
}
}
if ($found == true)
{
$alphanum = array('a','b','c','d','e','f','g','h','i','j','k','m','n','o','p','q','r','s','t','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7','8','9');
$chars = sizeof($alphanum);
$a = time();
mt_srand($a);
for ($i=0; $i < 6; $i++)
{
$randnum = intval(mt_rand(0,55));
$newpassword .= $alphanum[$randnum];
}
$crypt_pass = md5($newpassword);
$file = fopen($database, 'w');
foreach($items as $line)
{
$values = explode('|', trim($line));
if ($email == $values[2])
{
$values[1] = $crypt_pass;
$line = '';
for ($i=0; $i < count($values); $i++)
{
if ($i != 0)
$line .= '|';
$line .= $values[$i];
}
}
fwrite($file, $line);
fwrite($file, "\r\n");
}
fclose($file);
$mailto = $_POST['email'];
$subject = 'New password';
$message = 'Your new password for Club Login is:';
$message .= $newpassword;
$header = "From: webmaster#whiteshepherdsnz.com"."\r\n";
$header .= "Reply-To: webmaster#whiteshepherdsnz.com"."\r\n";
$header .= "MIME-Version: 1.0"."\r\n";
$header .= "Content-Type: text/plain; charset=utf-8"."\r\n";
$header .= "Content-Transfer-Encoding: 8bit"."\r\n";
$header .= "X-Mailer: PHP v".phpversion();
mail($mailto, $subject, $message, $header);
header('Location: '.$success_page);
}
else
{
header('Location: '.$error_page);
}
exit;
}
?>
Somehow I need to set target="-top" so the success page opens in the same window with normal browser view. Can someone show me how to achieve this please. I have no skills in this stuff just what I pick up from reading these sites and applying to my problem
Thanks
Roger
To keep it short and clear, you will need the # in your url.
header("Location: index.php#top");
That will redirect you to index.php and set the target to #top
Note: Remember that header('Location: ...') should redirect to an url like you would use in your browser. Not the internal server path.
Try with Window-target
header('Window-target: _top');
header('Location: index.php');
Unfortunately WYSIWYG Web Builder only allows the selection of an internal page address and will not allow edit so unable to try that out. However another solution was found using Java script in the head of the destination page:
<script>
this.top.location !== this.location && (this.top.location = this.location);
</script>
this worked perfectly. I will pass your comments on to the WYSIWYG Web Builder Forum.
Thanks
If Your Doing a form way
you can put a target in the form like this.
<form action="" method="" target="_top">
<input type="" name="">
</form>

How to fix Header new line error

I am receiving the following error message "Header may not contain more than a single header, new line detected" I know it says that a new line has been detected, but I cannot figure where this line is coming from. I have tried to trim the variables..I have re-written the header line in different ways, without any result. I added the getallheaders function to see what was being passed, but I see no new line or any extra characters in the output $headers. Even using ob_start() does not help.
<?php
ob_start();
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (isset($_POST['st']))
$st = $_POST['st'];
else
$st = '0';
if (isset($_POST['num']))
$num = $_POST['num'];
else
$num = '0';
if (isset($_POST['type']))
$type = $_POST['type'];
else
$type = '0';
if (isset($_POST['rec']))
$rec = $_POST['rec'];
else
$rec = '0';
if (isset($_POST['option']))
$option = $_POST['option'];
else
$option = '0';
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
//$catalogObj->order_form_type_id = array();
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
//print "order_form_type_id: $order_form_type_id[$i]<br>";
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
//$url = "type=".$type."option=".$option."rec=".$rec."st=".$st."num=".$num;
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
//Header("location: search_catalog_handler.php?" . rawurlencode($url));
if (function_exists('getallheaders'))
{
$headers = getallheaders();
print_r( $headers);
}
exit;
}
}
function getallheaders()
{
$headers = '';
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
?>
First, thanks for the pointers! The problem in the above code was with the $st variable. I am not very experienced with headers and rewriting them but I had add the following conditinal statement:
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
To the beginning of my code, so it the complete code is:
<?php
ob_start();
/*************************************
altered complete 12/20/2013
rjm
*************************************/
include "catalog.obj";
session_start();
$catalogObj = $_SESSION['catalogObj'];
if (!empty($_POST['st']))
{
$st = $_POST['st'];
$num = $_POST['num'];
$type = $_POST['type'];
$rec = $_POST['rec'];
$option = $_POST['option'];
}
if(strcmp($_POST['submit'],"Reset Form") == 0)
{
header("location: search_catalog.php?type=$type&firstTime=1");
exit;
}
elseif(strcmp($_POST['submit'],"Catalog Administration") == 0)
{
Header("Location: administration.php");
exit;
}
else
{
echo "<pre>";
print_r($_POST);
echo "</pre>";
//exit;
$inventory_id_num = $_POST['inventory_id_num'];
$inventory_desc = $_POST['inventory_desc'];
$inventory_revision = $_POST['inventory_revision'];
$quantity = $_POST['quantity'];
$catalog_status_id = $_POST['catalog_status_id'];
$order_form_type_id = $_POST['order_form_type_id'];
$catalogObj->inventory_id_num = $inventory_id_num;
$catalogObj->inventory_desc = $inventory_desc;
$catalogObj->inventory_revision = $inventory_revision;
$catalogObj->quantity = $quantity;
$catalogObj->catalog_status_id = $catalog_status_id;
$catalogObj->order_form_type_id = $order_form_type_id;
$count=count($order_form_type_id);
for ($i=0; $i<$count; $i++)
{
if(strlen($order_form_type_id[$i]) > 0)
{
$catalogObj->order_form_type_id[$i] = $order_form_type_id[$i];
}
}
if(strcmp($_POST['submit'],"Back to Order Form") == 0)
{
Header("Location: order_form.php?num=$num");
exit;
}
else
{
Header("location: search_catalog_handler.php?type=$type&option=$option&rec=$rec&st=$st&num=$num");
exit;
}
}
?>
This allows for a specific type search (with parameters) and a general type search (no parameters) from the sending page.
Assuming that catalog.obj does not output any information to the browser (which would result in an error as well), your $type variable looks like the culprit since it's the only wildcard.
Note that you'll need to do the following for all POSTed variables in your script that you want to use in a URI:
Sine it's possible that $type could be anything (it's using the POSTed variable sometimes), you should clean it up before spitting it back out in your header:
$type = urlencode($type); // Prepares the variable to be inserted in the URI
header("Location: search_catalog.php?type=$type&firstTime=1");

Using paypal IPN to send a random string via EMAIL

Ok I'll cut to the chase, I have this code which produces a random string:
function random_string()
{
$character_set_array = array();
//$character_set_array[] = array('count' => 2, 'characters' => 'AA');
$character_set_array[] = array('count' => 8, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
$pinstart = 'AA';
$pinend = implode('', $temp_array);
$pin = $pinstart.$pinend;
echo $pin;
}
Then in my paypal IPN I have this:
if($p->ipn_data["mc_gross"] > 0 && strcmp ($p->ipn_data["business"],$EMAIL) == 0 && ($p->ipn_data["item_number"]) == 1) {
$user = $p->ipn_data["custom"];
$date = $p->ipn_data["payment_date"];
$prodid = $p->ipn_data["item_number"];
$amount = $p->ipn_data["mc_gross"];
$amountTickets = 1;
$email = 'email#hotmail.com';
$subject = '[CODE] - Thank you for your donation';
$message = 'Your CODE IS, <? echo random_string(); ?>';
mail("$payer_email", "$subject",
$message.random_string(), "From: $email" );
$user = str_replace("_", " ", $user);
$user = str_replace("-", " ", $user);
$user = mysql_real_escape_string($user);
}
It sends the email but its "Your CODE is, , it doesn't post the random string.
I've tried putting in $pin, $pin = random_string(); print $pin nothing works
Change echo $pin; to return $pin in your random_string function because you want it to return a string, not to print out a string on the spot, then
$message = 'Your CODE IS, ' . random_string();
random_string should use return not echo
then
...
$subject = '[CODE] - Thank you for your donation';
$message = 'Your CODE IS,'. random_string();
mail("$payer_email", "$subject",
...

Categories