how to create username from email address provided - PHP - php

I have a signup page on my website where a user must provide a email address and password only.
I want to be able to create a username for this user automatically by using the first part of the email provided;
User supplies gordon#yourdomain.com, i want to make username 'gordon'
I don't need explanation on how to create form or submission of data to database, just the code to extract data from email provided, and if necessary, if duplicate occurs add number to end.
Hope this makes sense, seems like a basic function but couldn't find examples of it anywhere on net!

This is not a good idea, just use their full email address. The following email addresses could be different people, but they will become the same under your system.
samename#gmail.com
samename#yahoo.com
Adding a number to the end will make the user remember something unique to your system and cause much confusion on their end.

Agreed, you're stripping a necessarily unique ID into a non-unique ID. Unless you want to add some sort of handling to add a number to the username or something. If that's what you really want to do, this should set $username to the stuff before the email address:
<?php
$username = preg_replace('/([^#]*).*/', '$1', $email);
?>

Something like:
$username = left($email, stripos($email, '#'));
should do. You may want to learn regular expressions for these kinds of task.
Then you add the counter:
function countOccurrences($name)
{
$con = mysql_connect(___, ___, ___);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(___, $con);
$result = mysql_query("
SELECT COUNT(*) AS countOccurrences
FROM users
WHERE username LIKE '" . mysql_real_escape_string($name, $con) . "%'
");
$row = mysql_fetch_array($result);
$number = $row['countOccurrences'];
mysql_close($con);
return $number;
}
and then:
$countUsers = countOccurrences($username);
if ($countUsers>0)
{
$username = $username . $countUsers;
}
IMPORTANT: Consider using the whole email as username: you don't want gordon#flash.net to be considered equal to gordon#clash.com
NOTE: example code counts gordon, gordon1, gordon2 but gordonbah, gordonq, gordonxxx too
NOTE: this is pretty rough, and should not be considered best PHP practice; it's just to give the general idea

$username = gordon#example.com;
$username_arr = explode('#',$username);
$username = $username_arr[0];
if( !is_taken( $username ) )
{
//The name is not taken.
}
else
{
//The name is taken, add numbers and do the search again.
}
function is_taken( $username )
{
$db_link = mysql_connect($host,$user,$pass) or die('Could not connect to database');
$username = mysql_real_escape_string( $username );
$sql = "SELECT * FROM `database`.`users` WHERE `username` = '$username'";
$res = mysql_query( $sql , $db_link );
return mysql_num_rows( $res ) == 1;
}

<?php
preg_match('/[^#]+)#/',$email,$matches);
$username = $matches[1];
check_availability($username);
?>

Should suit your needs :D
$username = substr($username, 0, strpos($username, '#'));
$username = mysql_real_escape_string($username);
$result = mysql_query('SELECT `username` FROM `users` WHERE `username` = \'' . $username . '%\';');
if (mysql_num_rows($result) > 0) {
$i = 0;
while ($name_arr = mysql_fetch_assoc($result)) {
$name = $name_arr['username'];
$after = substr($name, strlen($username));
if (ctype_digit($after)) {
if (($after = (int) $after) > $i) {
$i = $after;
}
}
}
if ($i > 0) {
$username .= $i;
}
}

As of PHP 5.3.0 you can also use:
$email = 'test#stackoverflow.com';
$user = strstr($email, '#', true);
This will return all the string from the beginning to the first occurrence of '#'. Which in this case is:
test

I use something like this,
$cust_email = "test#gmail.com";
$parts = explode("#", $cust_email);
$cust_name = $parts[0];
I use to set default User Name if user do not set his / her name in the profile.

You can use strstr function to find specific word from string
<?php
$username = strstr("username#domain.com",'#',true); //get text before #
/*
echo strstr("username#domain.com","#"); // get text after #
*/
check_availability($username);
?>

Related

How do i successfully use function array_intersect() here?

I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}

adding counter to php page to count the unique visitors

I want to add a counter in my webpage which counts the number of visitors.
But my problem is that when i refresh my page ,counter increases by 1..i want that counter increases only when a new visitor with another ip reaches to my webpage.
here are my codes..
Sorry for my weak english
index.php
<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$_SESSION['current_user'] = $ip;
if(isset($_SESSION['current_user']))
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
else
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
As database based solution is not preferred, You can try the following file based solution for counting unique visitor. You already have used counter.txt file in your code.
I tried to use the same file that you have used. In my case I am storing IP address in that file. I have used base64 encoding function just to hide the IP address. It is always good to keep that file in a safe place. If that file is lost then the unique visitor IPs will be lost. See the function below:
Function definition
function getUniqueVisitorCount($ip)
{
session_start();
if(!isset($_SESSION['current_user']))
{
$file = 'counter.txt';
if(!$data = #file_get_contents($file))
{
file_put_contents($file, base64_encode($ip));
$_SESSION['visitor_count'] = 1;
}
else{
$decodedData = base64_decode($data);
$ipList = explode(';', $decodedData);
if(!in_array($ip, $ipList)){
array_push($ipList, $ip);
file_put_contents($file, base64_encode(implode(';', $ipList)));
}
$_SESSION['visitor_count'] = count($ipList);
}
$_SESSION['current_user'] = $ip;
}
}
Function call
$ip = '192.168.1.210'; // $_SERVER['REMOTE_ADDR'];
getUniqueVisitorCount($ip);
echo 'Unique visitor count: ' . $_SESSION['visitor_count'];
Output
Unique visitor count: 2
Change:
if(isset($_SESSION['current_user']))
to:
if($_SERVER['REMOTE_ADDR'] == $_SESSION['current_user'])
And, surely you dont need to get $count from a file, and then write the same value back to the file...? If the $_SERVER['REMOTE_ADDR'] matches the SESSION['current_user'] then do nothing..
try to store the user IP in database and check for unique user,
<?php
session_start();
if (!$_SESSION['status']) {
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("ip_log", $connection);
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");
mysql_close($connection);
$_SESSION['status'] = true;
}
?>
Best And Easy Code
Try to store the user IP in database and check for unique user
$`servername` = "";
$username = "";
$password = "";
$`dbname` = "";
$`conn` = new `mysqli`($`servername`, $username, $password, $`dbname`);
if ($`conn`->connect_error) {
die("Connection failed: " . $`conn`->connect_error);
}
$address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$name = `gethostname`();
$re = "select * from visitor where name='$name'";
$call = `mysqli_fetch_array`($re);
$as = `mysqli_num_rows`($call);
if($as == 0){
$`sql` = "UPDATE visitor SET visits = visits+1 WHERE name = '$name'";
}else{
$`sql` = "INSERT INTO visitor(visits,name,address) VALUE(1,'$name','$address')";
}
$`conn`->query($`sql`);
$`sql` = "SELECT visits FROM visitor WHERE id = 1";
$result = $`conn`->query($`sql`);
if ($result->`num_rows` > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
$visits = "";
//echo $visits;
}
`$conn`->close();

PHP/MySQL log in system -

I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.

SQL / PHP if NULL show else

We are trying to complete / fix the below code, We cant seem to do the following.
Check if 'Check_Activation' is set to 'NULL' within the Database
IF value is NULL direct the user to one of the forms (1,2,3)
And finally if the 'Check_Activation' has already been activated and isn't 'NULL' prevent user from accessing one of the 3 forms.
I know its basicly there but we can't seem to figure out the final bug.
Please have a quick look at the code below and if anyone notices anything that isn't right please advice us.
Paste Bucket / Version
Website URL
<?php
$username = $_POST['username'];
$activation_code = $_POST['activation_code'];
$activation_codeurl = $activation_code;
$usernameurl = $username;
$db_host = "localhost";
$db_name = "aardvark";
$db_use = "aardvark";
$db_pass = "aardvark";
$con = mysql_connect("localhost", $db_use, $db_pass);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$checkcustomer = mysql_query("SELECT `Check_Activation` FROM `members` WHERE `Username` = '".$username."' & `Activation` = '".$activation_code."'; ");
$array = mysql_fetch_array($checkcustomer);
if (is_null($array['Check_Activation'])) {
$username = substr($username, 0, 1);
if($username == '1') {
$redirect_url='form-one.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '2') {
$redirect_url='form-two.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
} elseif($username == '3') {
$redirect_url='form-three.php?membernumber='.$usernameurl.'&activation_code='.$activation_codeurl;
}
header("Location:". $redirect_url);
}
else
{
?>
Try this, You need to fetch the row from table and then you can check the values,
$val = mysql_fetch_array($checkcustomer);
if (is_null($val['Check_Activation']))
instead of
$val = mysql_query($checkcustomer);
if ($val == 'NULL')
NOTE: Use mysqli_* functions or PDO instead of using mysql_* functions(deprecated)
before I get into the technicality of what your are trying to accomplish, I have some advice for your code in general. You should avoid using the mysql api as it is deprecated, and use the mysqli api instead. I think you will also find that it is easier to use.
Now for the code:
You have this line in your code which seems to be incorrect, $checkcustomer is a result set from your previous query, so why are you running it as a query again?
$val = mysql_query($checkcustomer);
You already have the result set so do this:
$array = mysql_fetch_array($checkcustomer);
And then take the value of Check_Aviation;
if (is_null($array['Check_Aviation'])) {
//Do Something
}
Should solve your issue

I'm trying to retrieve data from mysql using php for my Flex Mobile application, but no luck

I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.

Categories