$text = "Mike is registered on Website";
Mike is a registered user on a website and I want to find his name with strpos()
$find = $db->query("SELECT username FROM users");
$finduser = $find->fetch_object();
if(strpos($text, $finduser->username) !== false) {
echo $finduser->username." is a user on Website.";
}
But it doesn't display the echo Mike is a user on Website..
I don't know if I'm doing everything correct.
Thank you.
To answer your question, let me assume that you want to search all your user in database if it in the text (string) or not.
So what you want to do is loop each row of your database user and check if the username is in the text. Here's how:
while ($finduser = $find->fetch_object()) // Loop all of your database row
{
if(strpos($text, $finduser->username) !== false) {
echo $finduser->username." is a user on Website.";
}
}
What your code provide is only check for row one. Here link for the php doc http://php.net/manual/en/mysqli-result.fetch-object.php
Your code fetches first row from the table. If there are several rows, the first one may be not Mike. The answer of #Hernantas outputs all users just fine. But there are two other pitfalls in your question. First, your code will match user "Website" while your string is "Mike is registered on Website". It's undesirable state, right? Then, second, you should request username directly by SQL:
$searched_name = "Mike";
$find = $db->query("SELECT username FROM users
WHERE username='" . mysqli_escape_string($searched_name) . "'");
if ($finduser = $find->fetch_object()) {
echo "{$searched_name} is a user on Website.";
} else {
echo "{$searched_name} is not found.";
}
Related
The user can enter a password into a POST form and the code will search the wordlist $file for the password. If it finds the password in the wordlist, it will inform the user. This works 90% of the time for generic passwords like Banana123 and Brad101. However, if the user enters a password like BananaK123 the code will return nothing. Is there a way to make the code ignore the letter 'K' in the password BananaK123 so it just searches for Banana123 instead?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
function dictionaryCheck() {
$file = file_get_contents("100k-most-used-passwords-NCSC.txt");
if(isset($_POST['dictionaryCheck'])){
$password = ($_POST['password']);
$password2 = preg_replace("/[^a-zA-Z]/", "", $password);
$pos = stristr($file, $password2);
if ($pos === false) {
echo "The dictionary word '$password2' was not found";
} else {
echo "The dictionary word '$password2' was found ";
echo " and exists at position $pos";
}
}
}
}
dictionaryCheck();
Try looking into similar_text(). You may want to reject strings that match a certain similarity.
https://www.php.net/manual/en/function.similar-text.php
This was just to answer your direct question. However, I would not suggest this way. ZXCVBN is a better solution. The reason I am saying this is that you will not be able to tell your users WHY you are rejecting that password. You may cause a lot of frustration.
I have a forum page and want a simple login for user with usernames from a predefined mysql user table. I use a login.php form file link from the forum, a get $_POST username, then use a login_handle.php file that calls a function to connect to the DB, query the users array, and try to validate that the $_POST username is in the queried list array.
The function is below, and then the call in login_handle.php I'm getting various errors and don't know if this is at all a good approach. I also want to start a session during the form and verification that can grab the $_POST username as a $_SESSION username and apply to subsequent forum pages.
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users";
$result = mysql_query($query);
$usernames = mysql_fetch_assoc($result);
$isUname = true;
if(!in_array("username", $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
------------------handler call-----------
$username = $_POST["username"];
$password = $_POST["password"];
if(isUsername($username)==true){ // Check if username is valid.
//$Uname = $_SESSION['username'];
//echo "Username = " . $Uname;
echo 'go to forum';
}
First, mysql is deprecated. Please use mysqli.
Second, why don't you use something like...
function isUsername($username){
$query = "SELECT username FROM users WHERE username == '" . $username . "'";
Third: did you search and research?
These kind of question can be easily find everywhere.
As simple as it is , you need to query the specific username from $_POST , not the whole usertable.
I think requesting the number of rows ( number of apparition is a good way to get if user is in database or not , you can make it greater (>=) instead of one user condition (==)).
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users where username='$username'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$isUname = true;
if($rows==1) {
$isUname = true;
}else{
echo "Please enter valid user name.<br>";
$isUname = false;
}
return $isUname;
}
I used nearly the same function when I manually assigned a txt array to a variable $username to compare. Now that I am using a user table I merely want to assign the an array of the queried users (thought mysql_fetch_assoc($result) creates the same type of assoc. array) to $username instead of the hard copied elements where it worked with before. Is the array produced with the query different than the $usernames=array("jes34","pes22","jis44","jll124"); that prevents me from doing this?
function isUsername($username){ //Test if proper Username from array.
$usernames=array("jes34","pes22","jis44","jll124");
$isUname = true;
if(!in_array($_POST["username"], $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
-----function call---
if(isUsername($username)==true){ do something }
below is the authorisation script (from login). I want to send a user to a specific page depending on (new column called company to be added to database table) a user and their company.
Current script, even if someone can point me in the direction I would appreciate it:
<title>authorise</title>
<?php
session_start();
$un = $_POST['username'];
$pw = $_POST['password'];
if ($pw != ''){
$_SESSION['user'] = $un;
echo "Incorrect username / password";
}
try
{
$dbh = new PDO("mysql:host=localhost;dbname=login_site","root","black$23");
}
catch (PDOException $e){
echo $e->getMessage();
}
$query = "SELECT * FROM users WHERE LOWER(username)=:username";
$stmt=$dbh->prepare($query);
$stmt->bindValue(':username',strtolower ($_POST['username']));
$stmt->execute();
if ($stmt->rowCount() == 1)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
require('blowfish.php');
require('bcrypt.class.php');
$bcrypt = new Bcrypt(4);
if($bcrypt->verify($_POST['password'],$row['password']))
{
echo"logged in!!";
header("Location: hollyfort/123.php");
}
}
?>
I think you need a table with the userID and a page id (or perhaps w/ the companyID and a pageID), so you can determine the page to be returned by the user or company. Maybe you even want both tables, e.g. if you want all employees of a company to get a certain site, but the CEO should get to a special site where he can see all his employees' activities.
you then first check, if an entry for that user exists (if it does, you return the page). if not, check if an entry for the company exists. if you cannot find an entry, you probably want to return a default page
all is ok - I setup company variables to check against the database column and it works :)
I apologise for the simpleton question but I am having a complete blank, hence why the wording of the title is vague.
I have built a simple PHP/MySQL user favouriting system that works fine, except for one part. Once the user has favourited another user, I cannot think for the life of me how to show the user that they have already favourited that user.
This is what I have so far:
if (($user_data['username'] == $profile_data['username']) === false) {
if () { ?>
// Favourite user
<?php } else { ?>
//See whether favourited or unfavourite user
<?php } } ?>
The table structure of favourites is simply two columns, favouritee being the profile favourited and favouriter being the current user favouriting. This table is joined to a main users table and the columns are populated by username strings.
EDIT
This is what I have got so far:
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
//See whether favourited or unfavourite user
}
(Posted on behalf of the OP):
Working code:
if (($user_data['username'] == $profile_data['username']) === false) {
$username = $user_data['username'];
$favouritee = $profile_data['username'];
$check_fav = mysqli_query("SELECT `id` FROM `favourites` WHERE (`favouritee` = '$favouritee' AND `favouriter` = '$username')");
if (mysqli_num_rows($check_fav) == 1) {
// Favourite user
} else {
// Unfavourited/check
}
}
To find whether a user has favourited another user, assume $myUsername as the logged-in user's username from the session, and assume $otherUsername coming from a profile page of another user (or perhaps a paged list of users).
SELECT 1 FROM favourite
WHERE favouriter = :favouriter AND favouritee = :favouritee
You can then inject parameters $myUsername into :favouriter and $otherUsername into :favouritee and if you get a row, you already have a favourite connection, and if you get zero rows, there is no favourite connection.
This is just the raw query, so of course you'll need to add PHP database code around this. If you're not familiar with this, take a look at the docs for PDO or MySQLi at php.net - both sections will give enough information to get you up and running.
That said, assuming usernames are stored in the user table, I'd be inclined to switch the two columns in the favourite table to integer foreign keys - it'll be faster and will save disk space. I'd call these from_user_id and to_user_id to make it clear what they are foreign keys of, and the direction of the favourite.
I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}