Codeigniter single site log on - php

I am trying to have it so if I log on from 1 part of my site, it will log on to the other parts also.
Some Notes:
All logins connect to the same database... lets call it db1
Site 1's table is phpfox
Site 2's table is vbulletin
Right now it successfully logs into phpfox but I can't figure out how to login to the forums also.... I've added a few lines of code below to try to do this but I can't figure it out:
The problem is I have to keep logging in on each part of my website (using the same username and password)
Here is my current code:
function login($username, $password, $passClean = null)
{
$this->faildLogins = new DB_FaildLogins();
$ip = $this->input->ip_address();
$faildLogins = $this->faildLogins->getFaildLoginsByIp($ip);
if($faildLogins){
if($faildLogins->bannedTime > 0){
$timeElapsed = ($faildLogins->lastTryDate + $faildLogins->bannedTime)-time();
if($timeElapsed > 0){
return sprintf('Your ip (%s) was banned for %s please try again after expire ban time!', $this->input->ip_address(), seconds2HumanTimeFormat($timeElapsed));
}
}
}
$result = $this->user_model->get_login_info($username);
if ($result) {
if ($result->status == 'pending') {
return 'INACTIVE';
}
if ($result->status == 'rejected') {
return 'REJECTED';
}
if ($password === $result->password) {
$this->CI->session->set_userdata(array('id'=> $result->id));
$this->user_model->addUserLogin($result->id);
$faildLogins = $this->faildLogins->getFaildLoginsByIp($ip);
if($faildLogins){
$this->faildLogins->resetFaildLoginToIp($ip);
}
return TRUE;
// If passwords don't match
} else {
#mysql_connect('localhost', 'db1', 'db1_password') or die ("Can't connect to DB!");
#mysql_connect('localhost', 'db1', 'db1_password', true) or die ("Can't connect to DB!");
#mysql_select_db('phpfox') or die ("Can't select DB!");
#mysql_select_db('vbulletin') or die ("Can't select DB!");
$phpFoxUser = mysql_fetch_array(mysql_query("SELECT * FROM `phpfox_user` WHERE `user_name` = '{$username}'"), MYSQL_ASSOC);
if($phpFoxUser['user_name'] == $username AND
$phpFoxUser['email'] == $result->email AND
md5(md5($passClean).md5($phpFoxUser['password_salt'])) == $phpFoxUser['password']) {
$DBUsers = new DB_Users();
$rows['id'] = $result->id;
$rows['password'] = md5($passClean);
if($DBUsers->saveIt($rows)) {
$this->CI->session->set_userdata(array('id'=> $result->id));
return TRUE;
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
}
} else {
#mysql_connect('localhost', 'db1', 'db1_password') or die ("Can't connect to DB!");
#mysql_connect('localhost', 'db1', 'db1_password', true) or die ("Can't connect to DB!");
#mysql_select_db('phpfox') or die ("Can't select DB!");
#mysql_select_db('vbulletin') or die ("Can't select DB!");
$result = mysql_query("SELECT * FROM `phpfox_user` WHERE `user_name` = '{$username}'");
$phpFoxUser = mysql_fetch_array($result, MYSQL_ASSOC);
if($phpFoxUser['user_name'] == $username AND md5(md5($passClean).md5($phpFoxUser['password_salt'])) == $phpFoxUser['password']) {
$DBUsers = new DB_Users();
$rows['username'] = $phpFoxUser['user_name'];
$rows['password'] = md5($passClean);
$rows['usergroup'] = 'user';
$rows['email'] = $phpFoxUser['email'];
$rows['activationCode'] = md5(time());
$rows['status'] = 'approved';
$rows['registerDate'] = time();
$rows['registerIp'] = $this->input->ip_address();
$rows['hash'] = uniqid(rand().rand().rand(), true);
$newUserId = $DBUsers->saveIt($rows);
if($newUserId) {
$this->CI->session->set_userdata(array('id'=> $newUserId));
return TRUE;
} else {
return false;
}
} else {
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}
//md5( md5($sPassword) . md5($sSalt) )
}
$this->faildLogins->addFaildLoginToIp($ip);
return FALSE;
}

Set a session variable to something unique to your user, like userid.
$_SESSION['UserId'] = $id;
Then, check for the session variable at the top of your login function.
if (isset($_SESSION['UserId']) // user already logged in
$ret = 'ACTIVE';
Then at the bottom of your function
return $ret;
BTW: I would get rid of the multiple returns in your function and use the $ret variable as in my example. Also, don't forget to delete your session variable when the user logs out:
unset($_SESSION['UserId']);
Also, you can check for the session variable at the top of any page that requires a logged in user, and redirect to the login page, if it is not set.

Related

PHP-script: Write IP-Adress in mySQL-Database. Doing that twice is not working

I use a PHP-Script to submit my IPv4 Address to my own PowerDNS-Server using that link:
script.php?domain=test.dns.com&ipaddr=11.22.33.44&passwd=auth-phrase
Therefore I modified the link in a way that the IPv4 and IPv6 are being updated simultaneously. I modified the update script, but then only one version will be updated (IPv4):
script.php?domain=test.dns.com&ipaddr=11.22.33.44&passwd=auth-phrase&ip6addr=2001:0db8:1234:0000:0000:0000:0000:0000
Here is the script I'm using:
<?php
// DynDNS-Service für PowerDNS
// #date 06.09.2012
$dsn = 'mysql:dbname=pdns;host=127.0.0.1'; // Datenbank DSN
$user = 'pdns'; // Name der Datenbank
$pass = 'password'; // Datenbank Passwort
// Auth-String der als GET-Parameter übermittelt werden muss
$auth = 'auth-phrase';
// Für alle im Array enthaltenen Records dürfen Updates gefahren werden
$allowed = array('ip4.test.dns.tld');
$domain = (isset($_GET['domain'])) ? $_GET['domain'] : null;
$ip = (isset($_GET['ipaddr'])) ? $_GET['ipaddr'] : null;
$ip6 = (isset($_GET['ip6addr'])) ? $_GET['ip6addr'] : null;
$domain6 = 'ip6.test.dns.tld';
if ((empty($domain) || is_null($domain)) || (empty($ip6) || is_null($ip6))) {
die('missing parameter');
exit;
}
if (!in_array($domain, $allowed)) {
die('forbidden domain name');
exit;
}
if (!isset($_GET['passwd']) || $_GET['passwd'] != $auth) {
die('authentification failed');
exit;
}
try {
$dbh = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// HERE THE PROBLEM STARTS
//IPv4 UPDATE
$check = $dbh->prepare('SELECT id FROM records WHERE name = :name AND type = :type');
$check->bindParam(':name', $domain);
$check->bindValue(':type', 'A');
$check->execute();
$result = $check->fetch(PDO::FETCH_ASSOC);
if (empty($result)) {
die('record not found');
exit;
} else {
$update = $dbh->prepare('UPDATE records SET content = :content WHERE id = :id LIMIT 1');
$update->bindParam(':content', $ip);
$update->bindParam(':id', $result['id']);
// if ($update->execute()) {
// die('update successful (' . htmlentities($ip, ENT_QUOTES) . ')');
// exit;
// }
// die('update returned false');
// exit;
}
//IPv6 UPDATE
$check2 = $dbh->prepare('SELECT id FROM records WHERE name = :name AND type = :type');
$check2->bindParam2(':name', $domain6);
$check2->bindValue2(':type', 'AAAA');
$check2->execute2();
$result2 = $check2->fetch(PDO::FETCH_ASSOC);
if (empty($result2)) {
die('record not found');
exit;
} else {
$update2 = $dbh->prepare('UPDATE records SET content = :content WHERE id = :id LIMIT 1');
$update2->bindParam2(':content', $ip6);
$update2->bindParam2(':id', $result2['id']);
if ($update2->execute2()) {
die('update successful (' . htmlentities($ip, ENT_QUOTES) . ')');
exit;
}
die('update returned false');
exit;
}
?>
I already removed the die(); part in the first part of the code. I also tried to rename the variable of the second part (check -> check2). But it's still not working. What did I do wrong? Why isn't it possible to write two times in the mysql-database?
I receive a blank site without any errors. But still: The update didn't work. There is no new updated IPv6 entry in my database.

PHP Login not working - only on ipad

I have a PHP login page on a website in the following form:
<?php
$logincorrect = 'notdefined';
$SubmitLogin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if (isset($_POST['SubmitLogin'])==TRUE)
{
$SubmitLogin = 'yes';
$email = strtolower($_POST['email']);
$passwrd = md5($_POST['nametag']);
}
if($SubmitLogin == 'yes')
{
$link = mysql_connect ('address.website.com', 'restricteduser', 'password_here');
if (!$link)
{
echo '<p style="color:red">* Error: Could not connect to database.</p> ';
}
$email = mysql_real_escape_string(strip_tags($email),$link);
$passwrd = mysql_real_escape_string(strip_tags($passwrd), $link);
$selectDB = mysql_select_db ('database', $link);
if (!$selectDB)
{
echo('<p style="color:red">* Error: Could not select database.</p> ' );
mysql_close($link);
}
$passwrdcheck = mysql_query
(" SELECT * FROM tablename WHERE email = '$email' AND passwrd = '$passwrd'");
if (!$passwrdcheck)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if(mysql_num_rows($passwrdcheck) == 0)
{
$logincorrect = 'no';
echo '<p style="color:red">Login details incorrect. Please try again.</p>';
}
else
{
$logincorrect = 'yes';
if($profile = mysql_fetch_array($passwrdcheck));
{
if($profile = mysql_fetch_array($passwrdcheck));
{
$ID = $profile['ID'];
$languages = mysql_query
(" SELECT * FROM translanguages WHERE ID = '$ID' ");
if (!$languages)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$expertise = mysql_query
(" SELECT * FROM transexpertise WHERE ID = '$ID' ");
if (!$expertise)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
$tracking = mysql_query
(" SELECT * FROM transtracking WHERE ID = '$ID' ");
if (!$tracking)
{
echo('<p style="color:red">* Error: Could not search database.</p> ' );
mysql_close($link);
}
if($profile2 = mysql_fetch_array($languages))
{ if($profile3 = mysql_fetch_array($expertise))
{ if($profile4 = mysql_fetch_array($tracking))
{
$_SESSION['profile'] = $profile;
$_SESSION['profile2'] = $profile2;
$_SESSION['profile3'] = $profile3;
$_SESSION['profile4'] = $profile4;
//echo "Login successful. If you are not automatically redirected, please click <a href='profile.php'> here </a>.";
header ("Location: ./profile.php"); exit;
}
}
}
}
}
}
}
?>
This works fine from my PC and my android phone. However, it does not work from my ipad. I have tried chrome and safari on the ipad and the result is the same: when clicking the 'SubmitLogin' button, the login page just appears to refresh instead of connecting to the database and checking the entered information. No error messages are shown.
I have racked my brain for days, but can't work out why this would be. Any ideas? Thanks!
Edit:
The 'directing back to the login page' part of profile.php is as follows:
$loggedin = 'no';
session_set_cookie_params (3600, $httponly = true);
session_start();
if(isset($_SESSION['profile']) AND isset($_SESSION['profile2']) AND isset($_SESSION['profile3']) AND isset($_SESSION['profile4']))
{
$profile = $_SESSION['profile'];
$profile2 = $_SESSION['profile2'];
$profile3 = $_SESSION['profile3'];
$profile4 = $_SESSION['profile4'];
$loggedin = 'yes';
}
else
{
session_destroy();
header ("Location: ./login.php");
exit;
}

Find method in SQL on my PHP page finds everything, even if the record is null

Ok so I wrote some code to find records on a test database, it works if there is a record and does display the data, if there is no record it still says that it found stuff. It should say it did not. It even finds stuff that is not in the database but obviously has no data to display, its annoying.
I need a new pair of eyes.
I think the error is here:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
But just in case here is the full code minus the login credentials to the db.
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
if ($result)
{
$OutputMessage = 'Record Found';
}
There is your mistake, that means if the query executed successfully (even with 0 records) you are saying records found. You should only say that if the number of records returned are more than 0.
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
But the bigger problem with your code can be solved by this reading
How can I prevent SQL injection in PHP?
This may happen, because if $_POST['KittenID'] is empty, the sql query would look like : SELECT * FROM Kittenzz WHERE KittenID=""; you have to change the above if statement to:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}

Admin Page Access

I have a page which only admins can access once they click a link. If the logged in user is a standard user then they should not be able to access the page. However, when a standard user tries to access the admin page they have access to the page.
I would appreciate a pair of second eyes to see if they can spot anything wrong with the code which would make the functionality work as intended.
Thanks
<?php
if(check_login() && isAdmin()) {
echo 'welcome administrator';
} else {
header('Location: login.php');
exit;
}
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID ='" . $_SESSION['sess_uid'] . "'";
$mainaccess = $conn->query($sql);
print_r($mainaccess);
if(!$mainaccess){
echo $conn->error;
}
if ($mainaccess -> userLevel == 0) {
return true;
} else {
return false;
}
}
function check_login () {
if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
return true;
} else {
false;
return;
}
}
?>
The issue is that you are selecting from the database users where they have admin access already ie
SELECT `userID` FROM `usertable` WHERE `userLevel` = 0
So you are always showing anyone as an admin. The query needs to be changed to check specifically if the logged in user is an admin. So changing the query to something like so
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
Where $_SESSION['sess_uid'] is the userID
We have to remove both the userLevel check, as this is irrelevant when selecting the user, we also have to change from SELECT userID, to SELECT *, as if you only select the userID, you will not have the userLevel in your array and the line
$mainaccess -> 'userLevel' == 0
Will not work. By selecting everything you ensure all attributes can be accessed, ie
$mainaccess -> 'userLevel'
$mainaccess -> 'userID'
Update
The correct way to access the table data will be using either
Object (this is the method you will use)
$mainaccess -> 'userLevel'// Incorrect
$mainaccess->userLevel //correct
Array
$mainaccess -> 'userLevel'// Incorrect
$mainaccess['userLevel'] //correct
Please change this line
You query is also incorrect please use this block of code as your sql query is not pulling in the right info.
function isAdmin()
{
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
if($result = $mainaccess = $conn->query($sql))
{
while($obj = $result->fetch_object())
{
$user = $obj;
}
}
if ($user->userLevel == 0)
{
return true;
}
else
{
return false;
}
}
You really need something like:
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT `userID` FROM `usertable` WHERE `userLevel` = 0 AND userID ='" . $_SESSION['sess_uid'] . "'";
As I said in the comments, you are looking for ANYONE with admin access, but you really want to know whether THIS user has admin access, therefore you have to validate what user you are trying to figure out has access. I just put the code together above, thinking you are storing the userID in the session (as per your later code) but you may need to change this
Your approach is wrong. The link should only be shown to logged in admins.
Try something like this test code.
<?php
session_start();
$_SESSION['admin'] = 0;//set only by logging in
$html ="Test<br>";//page html
if ($_SESSION['admin']== 0) {
$html .="<a href=\"adminpage.php\" >Admin</a>";
}
echo $html;
?>
Modify to suit your requirements.

PHP MySQL query output

I am trying to do a query in which i can see if username and password can match. If it matches, then I will go to the administrator pages. The problem Im having is that i think that the query is not giving me the right results. The database table is called admin, and it has adminame and passadmin. The user im entering IS in the database. The password is encrypted.
<?php
$f_user = $_POST['f_user'];
$f_pass = $_POST['f_pass'];
$status = authenticate($f_user, $f_pass);
if ($status == 1)
{
include("../connections/config.php");
session_start();
//session_register("SESSION_UNAME");
$_SESSION['SESSION_UNAME'] = $f_user;
$SESSION_UNAME = $f_user;
header("Location: unoadmin.php");
exit();
}
else
{
$mensa= "Información Incorrecta...Inténtelo de Nuevo";
header("Location: register.php?mensa=$mensa");
exit();
}
function authenticate($user, $pass)
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query = "SELECT * from admin WHERE adminame = '$f_user'";
mysql_select_db($db);
$result = mysql_query($query, $connection) or die ("Error in query: $query. " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 1)
{
for($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$pas = $row["passadmin"];
}
if(crypt($pass,$pas) == $pas)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
?>
Can someone tell me what is the error? It is leading me to "Información incorrecta. Intentelo de nuevo" or in english "Wrong information. Try again"
It is a bit of a guess, but your authenticate function returns false (error message)
I am not sure what happens in the include, it suggests inclusion of database settings.
You are using 2 different vars for the username: is:
function authenticate($user, $pass) // <-- you pass $user
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query =
"SELECT * from admin WHERE adminame = '$f_user'"; // <-- you use $f_user
Perhaps not a real answer, but it was to long for a comment.
A simple solution of this question is to put your user name and password in variables and match it with database, If result have greater than 1 value than it will go to admin page. For example
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT * FROM admin WHERE username='$myusername' and password=md5('$mypassword')";
$query = mysql_query($sql);
$row = mysql_num_rows($query);
if($row>0) {
header("location:administrator.php");
}
else {
echo"Please check username and password";
}
From your code you have either:
no such entry in your DB with the username you provided
the password is wrong
Furthermore you should check your code for SQL injections!
Please take time to read article below,
Best Way to prevent SQL Injection in PHP

Categories