2
\$\begingroup\$

I have a script that contains functions from login in to posting status to friend request send and receive. Pretty much a social network script. Anyways i think my security is not up to date so if anyone can check my code out or review it live on the web: iphone.hostei.com. email is [email protected] and password is demo123.

Please if anyone can review so my code is probably harder to hack and it functions well.

profile.php

    <?php
    session_start();
    //session_destroy();

    include_once('php/classes/db_config.php');
    include_once('php/classes/class.user.php');

    $user1 = new User($con);
    $is_loggedin = (isset($_SESSION['uid']))? true:false; 
    $is_uid = (isset($_GET['uid']) && !empty($_GET['uid']) && is_numeric($_GET['uid']))? true:false;
    // Set default uid
    $def_uid    =   ($is_uid == true)? $_GET['uid']: $_SESSION['uid'];
    // User valid check
    $user_valid =   ($is_uid == true)? $user1->check_user($def_uid):1;

    $name_id = $_SESSION['user']['uid'];
    $name = $_SESSION['user']['uname'];
    $fullname = $_SESSION['user']['fullname'];
    $bio = $_SESSION['user']['bio'];

    $time = date("Y-m-d H:i:s");

    if(isset($_POST['logout'])) {
        session_destroy();
        header('Location: index.php');
    }

    if(isset($_POST['area_sub'])){
        if(empty($_POST['area'])){
            echo "<script>alert('Empty area field.')</script>";
        }else{
            if($_GET['uid'] == ''){
                $user1 -> post($_SESSION['uid'], $_SESSION['uid'], $name, $_POST['area'], $time);
            }else if($_GET['uid'] == 0){
            }else{
                $user1 -> post($_SESSION['uid'], $_GET['uid'], $name, $_POST['area'], $time);
            }
        }
    }
    if($is_loggedin){
        $check = $con -> Fetch("SELECT * FROM follow_req WHERE user_two_req=".$_SESSION['uid']."");
    }

?>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Only Simple Albanian Social Network, with no ads</title>
    <link rel="stylesheet" href="css/profile.css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>

    <body>
    <?php if($is_loggedin !== true) { 
            include_once 'php/common/head.php'; ?>
    <?php }?>

    <?php
    // If there is a propper UID available
    if(($is_loggedin == true) || ($is_uid == true)) { ?>

    <?php if ($is_loggedin == true){ ?>

    <div id="menu">
        <div id="menu_wrapper">
            <div id="left_menu">

            </div>
            <div id="right_menu">
                <div id='drop-zone'><?php
                    if($check == 0){
                        echo "<h4 class='request'>0</h4>";
                    }else{ 
                        echo "<a href='#' class='request_more'>".count($check)."</a>";
                    }   
                ?></div>
                <form action='' method='post'>
                    <input type='hidden' name='logout' value='true' />
                    <input type='submit' name='submit' value='Logout' id='btn'>
                </form>
            </div>
        </div>
    </div>

    <?php } ?>

    <div id="profile_wrapper">

        <div class="wrapper">

            <div id="profile">  

            <?php

            // If user is valid
            if($user_valid == 1) {
                // User is logged in user
                if($def_uid == $_SESSION['uid']) {
                    include_once 'php/classes/profile_func.php';
                } 
                include_once 'php/classes/user_info.php';

            }else{?>
                <h2>No Such User Exists</h2>
                <h3>Please select a different user or <a href='index.php'>Login</a></h3>
                <?php if($is_loggedin == true){ ?>
                        <h3>Go Back to <a href="profile.php?uid=<?php echo $name_id;?>">My Profile</a></h3>
                    <?php
                }
            } ?>

<?php }else{?>
        <h1>Invalid User</h1>
        <h3>You must be <a href="index.php">Logged IN</a> to see your profile OR you must select a profile (uid) to view.</h3>
<?php } ?>
            </div>
        </div>
    </div>
<?php if($is_loggedin != true){ ?>
    <div id="footer">
        <h4>Per momentin vetem njerezit qe do perzgjidhen do kene akses.</h4>
        <a href="#">
            <div id="button">Kerkese Hyerje</div>
        </a>
        </div>
<?php } ?>

<script>
function LookUp(IdElem,URL){
        $("#drop-zone").html('<div class="loader"></div>');
        $.ajax({
                url: URL,
                cache: false,
                success: function(result) {
                        $("#drop-zone").html(result);
                    }
            });
}
$(document).ready(function() {
        $("a.request_more").click(function(){
            LookUp(this,'requests.php');
        });
});
</script>

</body>
</html> 

profile_funct.php

    <?php $user1->profile_photo(); ?>               
<div id="friends">
<?php 
    echo "
        <h2 class='u_name'><a href=profile.php?uid=".$name_id.">@".$name."</a></h2>
        <br/>
        <p>".$fullname."</p>
    ";

    $MyFollows  =   $con->Fetch("SELECT * FROM follow WHERE (user_one='$def_uid') OR (user_two='$def_uid')");
    $count_posts = $con->Fetch("SELECT * FROM post WHERE user_id=".$_SESSION['uid']." ");
    echo  "<p>Posts ".$cnt = ($count_posts !== 0)? '<a href="posts.php" class="posts_all">'. count($count_posts) .'</a>' : 0;"";
    echo " - Friends: ".$following = ($MyFollows !== 0)? '<a class="frnd_a" href="friends.php">'. count($MyFollows) .'</a></p>' : 0;"";
?>
</div>
<div id="post_wrapper">
    <p>Update Status</p>
    <div id='post_form'>
        <form action='' method='POST'>
            <textarea id='area' name='area'></textarea>
            <input type='submit' name='area_sub' id='sub_btn' value='Update'/>
        </form>
    </div>
</div>
<?php 
if($_GET['uid'] == 0){
    $user1 -> getResults();
}else{
    $user1 -> getResults();
}?>

user_info.php

  <?php if($def_uid != $_SESSION['uid']) {
    $info = $con->Fetch("SELECT * FROM users WHERE uid='$def_uid'"); ?>
    <h1>User Profile: <?php echo $info[0]['fullname']; ?></h1>
    <?php
    $action = ($user1->check_req($_SESSION['uid'], $def_uid))? true : false;
    $friends = ($user1->check_friends($_SESSION['uid'], $def_uid))? true: false;
    $c = ($user1->checking($def_uid, $_SESSION['uid']))? true: false;

    $post = $con->Fetch("SELECT * FROM `post` WHERE rec_id=".$_GET['uid']."");
    ?>

<?php
    if($friends == true){
        echo "Welcome to ", $info[0]['uname'],"'s wall";

        if($is_loggedin == true){
            echo "<br/>Go Back to <a href='profile.php?uid=".$_SESSION['user']['uid']."'>My Profile</a><br/>";
        }

        ?>
        <br/>
        <form action="" method="POST">
            <textarea id='area' name='area' placeholder="Say something nice <?php echo $name;?>"></textarea>
            <input type='submit' name='area_sub' value='Go'/>
        </form>
        <br/>
        <?php

        if($_GET['uid'] == $post[0]['rec_id']){
            echo "<br/>".$user1 -> getResults();
        }
        echo "<br/><a href='actions.php?action=unfriend&uid=".$def_uid."'/>Unfriend</a><br/>";

    }else{

        if($is_loggedin == true){
?>
            <a href="actions.php?action=
            <?php if($action == true){ $un = "cancel";echo $un;}else{echo "send";}?>&uid=
            <?php echo $def_uid; ?>">
            <?php if($c == true){
                    echo"<a href='actions.php?action=accept&uid=".$def_uid."'>ADD</a><br/>"; 
                    echo "<a href='actions.php?action=ignore&uid=".$def_uid."'>Ignore</a>";
                }else if($action == true){
                    echo $un;
                }else{
                    echo "send";
                }?>
            </a>

            <br/>Back to my <a href="profile.php?uid=<?php echo $_SESSION['user']['uid']; ?>">Profile</a>

            <?php

        }else{
            echo "Not Logged In. Log in <a href='index.php'>Here</a>";
        }

    }
}
?>

class.user.php

    <?php
class User
    {
        public  $db;
        public  $error;

        public function __construct($con){
                $this->db = $con;
        }

        /*** for login process ***/
        public function check_login($username='', $password=''){
                // Validate that your email is a real one
                if(filter_var($username,FILTER_VALIDATE_EMAIL) !== false) {
                        $password   =   md5($password);
                        $sql        =   "SELECT uid from users WHERE (uemail='$username' or uname='$username') and upass = '$password'";
                        $result     =   $this->db->Fetch($sql);

                            if ($result !== 0) {
                                    // this login var will use for the session thing
                                    $_SESSION['emailusername']  =   $result[0]['uemail'];
                                    $_SESSION['uid']            =   $result[0]['uid'];
                                    $_SESSION['user']           =   $this->get_fullname($result[0]['uid'],0);
                                    $_SESSION['login']          =   true;
                                }
                            else
                                $this->error['Invalid Account'] = '<h3 id="error">Invalid Username or Password</h3>';
                    }
                else
                    $this->error['Email'] = '<h3 id="error">Invalid Email Address</h3>';

                return  (!isset($_SESSION['emailusername']))? false:true;
            }

        /*** for showing the username or fullname ***/
        public function get_fullname($uid, $write = 1){

                // --> You can prepare, bind, and execute your values here replacing what you have now....<--

                $sql                =   "SELECT * FROM users WHERE uid = '$uid'";
                $user_data          =   $this->db->Fetch($sql);

                if($user_data !== 0) {
                        $user['uname']      =   $user_data[0]['uname'];
                        $user['fullname']   =   $user_data[0]['fullname'];
                        $user['uemail']     =   $user_data[0]['uemail'];
                        $user['uid']        =   $user_data[0]['uid'];
                        $user['bio']        =   $user_data[0]['bio'];

                        // This gives the option of returning an array (setting session array) or echoing
                        if($write == 1)
                            echo implode("<br />",$user);
                        else
                            return $user;
                    }
            }

        public function check_user($uid)
            {
                $sql        =   "SELECT * from users WHERE uid= $uid ";
                $result     =   $this->db->Fetch($sql);
                $count_row  =   ($result !== 0)? count($result): 0;

                return $count_row;
            }

        /*** starting the session ***/
        public function get_session()
            {
                return $_SESSION['login'];
            }

        public function user_logout()
            {
                $_SESSION['login'] = FALSE;
                session_destroy();
            }
        public function check_req($is_uid, $def_uid){
            $sql        =   "SELECT * from follow_req WHERE user_one_req = '$is_uid' AND user_two_req = '$def_uid'";
            $result     =   $this->db->Fetch($sql);
            $count_row  =   ($result !== 0)? count($result): 0;
            return $count_row;
        }
        public function insert($is_uid, $def_uid){
            $sql        =   "INSERT INTO follow_req (user_one_req, user_two_req) VALUES (:user_one_req, :user_two_req)";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':user_one_req'=>$is_uid, ':user_two_req'=>$def_uid));

            return $q;
        }
        public function delete($is_uid, $def_uid){
            $sql        =   "DELETE FROM follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':user_one_req'=>$is_uid, ':user_two_req'=>$def_uid));
            return $q;
        }
        public function checkimg($img_id){
            $sql        =   "SELECT * from users WHERE img_id = '$img_id'";
            $result     =   $this->db->Fetch($sql);
            $count_row  =   ($result !== 0)? count($result): 0;
            return $count_row;
        }
        public function img($img_id, $part){
            $sql        =   "UPDATE users SET img_id='$img_id', image='$part' WHERE uid=".$_SESSION['uid']."";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':img_id'=>$img_id, ':image'=>$part));
            return $q;
        }
        public function check_friends($is_uid, $def_uid){
            $sql        =   "SELECT * from follow WHERE (user_one = '$is_uid' AND user_two = '$def_uid') OR (user_one = '$def_uid' AND user_two = '$is_uid')";
            $result     =   $this->db->Fetch($sql);
            $count_row  =   ($result !== 0)? count($result): 0;
            return $count_row;
        }
        public function del_friends($is_uid, $def_uid){
            $sql        =   "DELETE FROM follow WHERE (user_one = :user_one AND user_two = :user_two) OR (user_one = :user_two AND user_two = :user_one)";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':user_one'=>$is_uid, ':user_two'=>$def_uid));
            return $q;
        }
        public function checking($def_uid, $is_uid){
            $sql        =   "SELECT * from follow_req WHERE user_one_req = '$def_uid' AND user_two_req = '$is_uid'";
            $result     =   $this->db->Fetch($sql);
            $count_row  =   ($result !== 0)? count($result): 0;
            return $count_row;
        }
        public function accept_req($def_uid, $is_uid){
            $sql        =   "INSERT INTO follow ( user_one, user_two) VALUES ( :user_one, :user_two)";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':user_one'=>$def_uid, ':user_two'=>$is_uid));
            return $q;
        }
        public function delete_req($def_uid, $is_uid){
            $sql        =   "DELETE FROM follow_req WHERE user_one_req = :user_one_req AND user_two_req = :user_two_req";
            $q = $this->db->prepare($sql);
            $q -> execute(array(':user_one_req'=>$def_uid, ':user_two_req'=>$is_uid));
            return $q;
        }
        public function post($a_id='', $r_id='', $name, $area='', $time){
            $sql = $this->db->prepare("INSERT INTO post (user_id, rec_id, user, area, time) VALUES ( ?, ?, ?, ?, ?)");
            $sql -> bindParam(1, $a_id);
            $sql -> bindParam(2, $r_id);
            $sql -> bindParam(3, $name);
            $sql -> bindParam(4, $area);
            $sql -> bindParam(5, $time);
            $sql -> execute();
        }
        public function profile_photo(){
            $get_name = $this->db->Fetch ("SELECT * FROM users WHERE img_id=". $_SESSION['uid']."");            
            if($get_name[0]['img_id'] == $_SESSION['uid']){
                echo "<img id='profile_img' src='test/upload/".$_SESSION['uid']."_".$get_name[0]['image']."'/>";
            }else{  
                echo "<img id='profile_img' src='classversiondontdelete/images/default/profile_icon.gif'/>";
                //echo "<img src='test/upload/".$_SESSION['uid']."_".$get_name[0]['image']."'/>";
            }
        }
        public function getResults(){
            if($_GET['uid'] == ''){
                $result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = ".$_SESSION['uid']." ");
            }else if($_GET['uid'] == 0){
                $result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = ".$_SESSION['uid']." ");
            }else{
                if(is_numeric($_GET['uid']))
                    $result = $this->db->Fetch("SELECT * FROM post WHERE rec_id = '".$_GET['uid']."'");
            }
            if(is_array($result)){
                foreach ($result as $row) {
                    ?><div id="post"><?php
                    $get_name = $this->db->Fetch("SELECT * FROM users WHERE img_id = ".$row['user_id']."");
                    if($get_name[0]['img_id'] != 0){
                        echo "<img id='post_img' src='test/upload/".$row['user_id']."_".$get_name[0]['image']."'/>";
                    }else{  
                        echo "<img id='post_img' src='classversiondontdelete/images/default/profile_icon.gif'/>";
                    }
                    echo "
                        <h3 id='text'>".$row['area']. "</h3>
                    ";
                    ?></div><?php
                }
            }
        }
    }
?>
\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

I can't comment on security as I haven't had time to go through and understand the code, but I have written comments in regards to coding style, search for // ### to see my comments.

I will have another look later if I get time

<?php
session_start();
//session_destroy();

include_once('php/classes/db_config.php');
include_once('php/classes/class.user.php');

$user1 = new User($con);

// ### no point using tenary operator here given isset returns a boolean anyway
// $is_loggedin = (isset($_SESSION['uid']))? true:false;
$is_loggedin = (isset($_SESSION['uid']));

// ### you don't need to test isset and empty, empty takes care of both
// $is_uid = (isset($_GET['uid']) && !empty($_GET['uid']) && is_numeric($_GET['uid']))? true:false;
$is_uid = (!empty($_GET['uid']) && is_numeric($_GET['uid']));

// Set default uid
// ## this can also be shortened although not essential
// $def_uid    =   ($is_uid == true)? $_GET['uid']: $_SESSION['uid'];
$def_uid = ($is_uid) ? $_GET['uid'] : $_SESSION['uid'];

// ### what if $_SESSION['uid'] is not set?

// User valid check
// ### what does 1 mean, perhaps define a constant or use true/false instead
$user_valid = ($is_uid == true) ? $user1->check_user($def_uid) : 1;

// ## if $_SESSION['user'] doesn't exist these assignments will generate warnings
$name_id = $_SESSION['user']['uid'];
$name = $_SESSION['user']['uname'];
$fullname = $_SESSION['user']['fullname'];
$bio = $_SESSION['user']['bio'];

$time = date("Y-m-d H:i:s");

if (isset($_POST['logout'])) {
    session_destroy();
    header('Location: index.php');
    // ### need to exit after header or your script keeps executing
    exit;
}

if (isset($_POST['area_sub'])) {
    if (empty($_POST['area'])) {
        echo "<script>alert('Empty area field.')</script>";
    } else {

        // ### i would simplify this block of code
//        if ($_GET['uid'] == '') {
//            $user1->post($_SESSION['uid'], $_SESSION['uid'], $name, $_POST['area'], $time);
//        } else if ($_GET['uid'] == 0) {
//            // ### what is the point of this condition?
//        } else {
//            $user1->post($_SESSION['uid'], $_GET['uid'], $name, $_POST['area'], $time);
//        }

        $uid = $_GET['uid']; // assuming it is set
        if ($uid == '') {
            $uid = $_SESSION['uid']; // assuming it is set
        }

        $user1->post($_SESSION['uid'], $uid, $name, $_POST['area'], $time);
    }
}
if ($is_loggedin) {
    // ### you used prepared statements elsewhere, why not here?
    $check = $con->Fetch("SELECT * FROM follow_req WHERE user_two_req=" . $_SESSION['uid'] . "");
}

?>
\$\endgroup\$
1
  • \$\begingroup\$ Hello. This is much better? if($is_loggedin){ $sql = "SELECT * FROM follow_req WHERE user_two_req= :user_two_req"; $query = $con->prepare($sql); $query->execute(array( ':user_two_req' => $name_id)); } \$\endgroup\$
    – Love_PHP
    Commented Nov 20, 2014 at 2:56
0
\$\begingroup\$

You dont prepare your SELECT and UPDATE statements, and dont use md5; http://php.net/manual/en/faq.passwords.php#faq.passwords.fasthash

You should atleast add "salt" to your passwords; http://php.net/manual/en/faq.passwords.php#faq.passwords.salt

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.