Getting the user's username - MyBB - php

I was wondering how I would go about getting the user's username. What i want to do is display it like this:
Username here
I tried this:
{$mybb->user['name']}'
But that was unsuccessful and I cannot seem to find anything on Google.
Thanks for any help!

I am not that experienced with MyBB but after some research i found a few different ways.
$user = get_user($uid);
echo $user['username'];
or
global $db;
$qry = $db->query("SELECT uid FROM ".TABLE_PREFIX."users WHERE username = '".$usernamevar."'");

And you can combine all like this, i think.
<?php
define("IN_MYBB", 1);
require ('global.php'); // be sure that u r running this php-code in the same
// directory of global.php, or else change the path.
if($mybb->user['uid'] > 0)
{
$uid = $mybb->user['uid'];
$user = get_user($uid);
$name = $user['username'];
}
// custom else here: in case of not logged-in user
?>
<?echo $name?>

Try to put this one into your template.
{$mybb->user['username']}
No need to use PHP for an existed variable.

Related

PHP: Set current Joomla username as variable

how can I set in a php-script the username of the user, that is logged in at the moment, as a variable?
I know, how I can get and display the current username, but how can I set this as a variable?
This is the code, which I want to set as a variable:
<?php
$user = JFactory::getUser();
$user->username;
?>
Thanks for your help.
It looks like you are already almost doing it.
<?php
$user = JFactory::getUser();
$username = $user->username;
?>
Though, $user->username is already containing this information, so I think that is why everyone is confused.

Get user info from mysql database

i am making my own php game. So far i have made almost everything. Now to finish it, i need to get id from user who is logged in. I'm not so familiar with the functions and sessions. Please help.
This is what i made so far:
In my index page people login. then they are redirected to this.
So $_POST['username'] is where user type his user name in index.
<?php
$username = $_POST['username'];
include("Files/config.php");
$connect = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if($connect) {
if(mysql_select_db(DB_NAME)) {
$sql = mysql_query("SELECT * FROM users WHERE `username`='$username'") or die(mysql_error());
$gatherinfo = mysql_fetch_array($sql);
global $getid;
$getid = $gatherinfo['id'];
echo $getid;
function getuid() {
$_SESSION['getuid'] = $getid;
echo $getid;
}
}
}
else{ echo "Can not connect";}
?>
I searched other scripts for this, i found on one it says just $session->uid and it shows his id from mysql.
In mysql database i have table users with info about them
Id, username, password (password is hashed), email,...
Please help me if you can :D
At the beginning of index file (where your user logging in) start named session (be careful to avoid echo or print any values before session_start:
<?php //index.php
session_name('SAMPLESESSION');
session_start();
then when you will get the logged User ID, write this value to the session variable, like this:
.....
$_SESSION['uid'] = $getid;
.....
in the script you was redirected by your index file start session with the same name and get your user ID:
<?php //redirectedfromindex.php
session_name('SAMPLESESSION');
session_start();
echo $_SESSION['uid'];
....
If I right understand you, these that you need.

This is my php for viewing user profile

My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>
than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli

trying to set session variable

if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.

Show content only if logged in

Hello I have a question. I have set up my login system with cookies and it works. But I wonder is there a more clean version of doing this.
<?
include('../config/db_config.php');
$username = $_COOKIE['user'];
$password = $_COOKIE['pass'];
$result = mysql_query("SELECT * FROM users WHERE isadmin = 1");
while($row = mysql_fetch_array($result))
{
if($username == $row['username'] && $password == $row['password'])
{
//User entered correct username and password
echo("ALLOW");
}
else
{
//User entered incorrect username and password
echo("DENY");
}
}
?>
You see I want all my content to be shown ONLY if I am logged in as admin. So what, now only way of doing this would be ECHO'ing out my HTML/PHP/Javascript instead of echoing ALLOW because if I just include("somepage.php") there that page would still be avialable for usage without logging in, and even if I do same check there I still would be ECHO'ing out everything.
Why are you loading every user, then comparing the username and the password? Wouldn't be easier to load a single user matching the username and the password?
Loading a single user will allow to remove the while().
In PHP, don't use mysql_query; do use PDO (if need, google for it to know why it's better).
Check your input (quite optional here, I agree).
Do never store passwords in plain text format.
You can probably do something like (I haven't used PHP/PDO for years, so the code may be inexact):
if (strlen($username)> 128)
{
// Something wrong. The username is too long.
}
$hash = sha1($password);
$sth = $dbh->prepare('if exists(select * from users where isadmin = 1 and username = :username and password = :password) select 1 else select 0');
$sth->bindParam(':username', $username, PDO::PARAM_STR, 128);
$sth->bindParam(':password', $hash, PDO::PARAM_STR, 40);
$sth->execute();
$isFound = $sth->fetchAll();
if ($isFound)
{
// User entered correct username and password.
echo 'ALLOW';
}
You could set a session variable on your login page (or any page that checks the login) that stores whether or not they're logged in and it will persist across pages. Then you can simple wrap your admin html in an if statement like so:
<?php
if ($_SESSION['isAdmin'] == true) {
?>
<p>My admin html</p>
<?php
} else {
?>
<p>My non-admin html</p>
<?php
}
?>
To save the info in a session, just add this to the part where you have echo("ALLOW");:
$_SESSION['isAdmin'] = true;
You'll also want to add session_start(); to the top of the script.
I would suggest that you do something like that only once, when the user first accesses the page, and then set a $_SESSION['is_admin'] or something for the rest of the time, so that you don't have to make an extra db call each page.
You could always put your "somepage.php" above the document root. This is a common way of preventing direct execution.
For example, if your webserver looks like 'project/public_html/index.php' put your admin-only include in 'project/somepage.php' then reference it using something like include("../somepage.php").
Obviously this will need adjustment according to the real paths you use.

Categories