Create a function out of this php code - php

I just need some help creating a php function out of this code or in other words just to wrap this code in a php function :
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
Thanks.

Really easy :)
function yourFunc() {
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
}

function getMyDivElement($name) {
$username = mysql_real_escape_string($name);
if(ctype_alnum($username)) {
$check = mysql_query("SELECT username,first_name FROM users WHERE username='{$username}'");
if(is_resource($check) && ($get = mysql_fetch_assoc($check))) {
$username = $get['username'];
$firstname = $get['first_name']; //You need this?
return '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}
}
return null;
}
//usage
if (isset($_GET['id'])) {
$div = getMyDivElement($_GET['id']);
if($div) {
echo $div;
} else {
header("Location: index.php");
exit();
}
}

Another way to do it is to return the echo statement as a string.

The idea of creating a function is to provide reuseable code. This means you are encapsulating the logic, allowing you to change the inner workings of the code without it affecting the actual usage of the function and to avoid tedious repetition.
In your example you should think about the areas that fall into this category. I personally can see that several functions that could be made here.
Example, not run but should give you ideas.
<?php
function getUser($username)
{
if (is_string($username) && strlen($username)) {
$query = "
SELECT
username, firstname
FROM
users
WHERE
username = :username
";
$result = executeQuery($query, array("username" => $username));
return $result->fetch();
}
}
function getDatabase($host, $db, $user, $password)
{
return new PDO("mysql:host=$host;dbname=$dbname, $user, $pass");
}
function executeQuery($sql, array $params = array())
{
$db = getDatabase();
$conn = $db->prepare($sql);
return $conn->execute($params);
}
function validateInput($input)
{
return ctype_alnum($input);
}
function advanceTo($page, $params)
{
header("Location: $page.php");
exit();
}
if (isset($_GET["username"])){
if (validateInput($_GET["username"])) {
$user = getUser($_GET["username"]);
if (! empty($user)) {
// authUserAndSetSessionForUser($user);
/** This page is then directed to and welcome message shown **/
advanceTo("user-home-page", array($user));
} else {
advanceTo("index");
}
}
}
?>

Related

Fatal error: Call to undefined method User->get_fullname()

I have problem with get data from database.
This is my function:
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
var_dump(mysql_result($result));
if(mysql_result($result)>0){
//$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
else{
print_r('chuj');
}
}
and this is my function call:
$uid = $_SESSION['uid'];
$user = new User();
$register = $user->get_fullname($uid);
What is wrong with my code?
Full class in file Functions.php:
include_once 'config.php';
class User
{
//Połączenie z bazą danych
public function __construct()
{
$db = new DB_Class();
}
//Rejestracja
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
//Logowanie
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
var_dump($_SESSION);
return TRUE;
}
else
{
return FALSE;
}
}
//Pobieranie imienia
public function get_fullname($uid)
{
$result = mysql_query("SELECT * FROM users WHERE uid ='".$uid."'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if($no_rows>0){
$user_data = mysql_fetch_array($result);
//echo $user_data['name'];
return $user_data['name'];
}
else{
print_r('chuj');
return FALSE;
}
}
//Sesja
public function get_session()
{
return $_SESSION['login'];
}
//Wylogowanie
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}
}
?>
Fatal error: Call to undefined method User->get_fullname()
Rizier123's comment is correct, but not the cause of your problem.
I tried to reproduce the error but failed. That means that probably you're using an old version somewhere. If you're using FTP or the like, are you sure you uploaded the User class since you added the function?
Also, make sure that the most recent User class is included in the file where you're using it.

Cannot validate right? Why? New to PDO

I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.

how to confirm logged in to pages?

I wonder how to make every pages that need go through login page. If the person doesn't log in, it will redirect to login page.
I include a function
confirm_logged_in();
in every page but it keeps asking for the login even after I log in. Please tell me how to fix that It only needs to log in once but still the keeps people from entering a direct link manually.
I do have session_start(); in every page!
Here the code for login page
$username = "";
if (isset($_POST['submit'])) {
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
} else{// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}
Here the code for functions:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function logged_in() {
return isset($_SESSION['admin_id'] );
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php");
}
}
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='admin' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function find_client_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='client' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$client_set = mysqli_query($connection, $query);
confirm_query($client_set);
if($client = mysqli_fetch_assoc($client_set)) {
return $client;
} else {
return null;
}
}
function attempt_login_admin($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["hashed_password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
}
I don't understand if the functions attempt_login_admin() and attempt_login_client() return a bool or an array. If you fix that, It should work. You can return a bool in the associative array by assigning the return bool value to $found_admin['bool'] and verifying the bool in the if-block by if($found_admin['bool']) { ... }.

PHP Login Script Broken

Hello Ladies and Gentlemen, I have been working on this project for some time now. And all of a sudden when I go into the web page to login I just get a blank screen at the 'success_login.php' which is literally just the login script that runs once login is clicked on my screen.
Here is the success_login.php script:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/luke/classes/userFunctions.php');
$userFunctions = new userFunctions();
session_start();
//assign all posted values to a session
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
$_SESSION['login_info'][$key] = $value;
}
}
//Get the username and password
$username = htmlentities($_POST["username"], ENT_QUOTES);
$password = htmlentities($_POST["password"], ENT_QUOTES);
//Get the user id if the login was valid
$userId = $userFunctions->validLogin($username,$password);
if($userId != 0) {
$_SESSION['login_info']['username'] = $username;
$_SESSION['login_info']['password'] = $password;
$_SESSION['login_info']['user_id'] = $userId;
header('LOCATION: home.php');
exit;
}
header('LOCATION: login.php');
exit;
?>
and here is the function it refers to:
public function validLogin($username,$password) {
$dbact = new DbInteraction();
$query = "select * from person";
$result = $dbact->interact($query,true);
$row = mysql_numrows($result);
$valid = false;
$userId = 0;
while ($row = mysql_fetch_array($result)) {
//Check to see if the username and password are valid
$validUsername = strcmp($username,$row['username']);
if($validUsername == 0) {
$hashedPassword = md5($password . Constants::SALTED);
$validPassword = strcmp($hashedPassword,$row['password']);
if($validPassword == 0) {
$valid = true;
$userId = $row['idperson'];
}
}
}
if(!$valid) {
$_SESSION['login_info']['username'] = "error";
$_SESSION['login_info']['password'] = "";
header('LOCATION: login.php');
exit;
return $userId;
} else {
$_SESSION['login_info']['username'] = "";
$_SESSION['login_info']['password'] = "";
return $userId;
}
}
Like I said, its been working for months and now all of a sudden its not anymore, and it has me really worried. Could someone shed some light for me?
Thanks a million for your time!

Undefined variable?

I'm getting an undefined variable error for $id variable in lines 15 & 21, could someone please explain why? I can't see what the problem is.
<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password, $id))
{
include 'db.inc.php';
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['id'] = $id;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
$GLOBALS['loginError'] = 'The specified email address or password was incorrect.';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['id']);
header('Location: ' . $_POST['goto']);
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsAuthor($_SESSION['email'], $_SESSION['password'], $_SESSION['id']);
}
}
function databaseContainsAuthor($email, $password, $id)
{
include 'db.inc.php';
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
$sql = "SELECT COUNT(*) FROM author
WHERE email='$email' AND password='$password'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for author.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The variable $id is defined in databaseContainsAuthor($email, $password, $id), then stored in the $_SESSION['id'] session so naturally $id = mysqli_query($link, $sql); should have passed but it's not?
Variables changed (or defined) inside a function will not affect the rest of the script. For example:
<?php
function changeVariabe($person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Alice!
This can be avoided by passing the variable by reference, like this:
<?php
function changeVariabe(&$person) {
$person = 'Bob';
}
$person = 'Alice';
changeVariable($person);
echo "Hello $person!"; // Outputs: Hello Bob!
You can also use global variables, like this:
<?php
function changeVariabe() {
global $person;
$person = 'Bob';
}
$person = 'Alice';
changeVariable();
echo "Hello $person!"; // Outputs: Hello Bob!
a few things
the variable $id should be defined (not required but good practice) before you use it
so for example
$id = NULL;
if (databaseContainsAuthor($_POST['email'], $password, $id))
also setting the $id inside the databaseContainsAuthor function doesn't mean that $id will change outside the scope of that function.
You could make it global but that is considered bad practice
also your function databaseContainsAuthor
contains this code
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
which will return TRUE or FALSE. but note that once the code returns a value, none of the code after it will be run
which means this part might as well be commented out, as it is after the return statement it will never be run
$sql = "SELECT id FROM author
WHERE email='$email'";
$id = mysqli_query($link, $sql);
if (!$id)
{
$error = 'Error searching for id.';
include 'error.html.php';
exit();
}

Categories