0

I would like to concatenate a users avatar to a message they send in a chat system . At the moment I have progressed to the point where I have the image name.jpg for each user showing up in the chat (MEANING: I have an ID for each user to INDEX).

enter image description here

I need to be able now have it so that it display as avatar in the chat with the following code

<?php echo  "<img width='100' height='100' src='avatars/".$row['imagelocation']."' alt='Profile Pic'>"; ?>

I want to display the avatar here wrapped in the span to $new_str which is the message to be sent

    <div id="chat_data">

        <span style ="color:orange; font-size:10px;"><?php echo "<a href=http://localhost/db/view_member.php?id=".$row['username'].">My Profile </a>"?><span style ="color:o; font-size:24px;"><?php echo " |".$row['username']." says :"; ?></span></span> 

        **//LINE I WANT TO ADD THE AVATAR TO**
        <span style ="color:white; font-size:20px;"><?php echo $new_str ;?></span>

        <span style ="float:right; color:brown;"  ><?php echo $row['date']; ?></span>

        //THIS LINE DISPLAYS THE IMAGE BUT ON ALL LINES IN THE CHAT
        <span style ="float:right; color:brown;"  ><?php echo $row['imagelocation']; ?></span>


    </div>

The 3rd span tag above displays the users avatar but on all messages My query is selecting everything from the table so that all users can see the messages, How can I make my query to show and avatar for each user on each line of a message they send (Im using ID as an INDEX for each user) but I'm stuck trying to display the avatar on each line of a message for that user

If I include a WHERE CLAUSE below to index the ID for the user the chat wont display everything to all other users in the chat.

$query = "SELECT * FROM chat ORDER BY id DESC";
    $run = $con->query($query);
    while($row = $run->fetch_array()):
    $new_str = str_replace($row['msg']);



?>

My TABLE STRUCTURE AVID IS THE USERS ID table chat

enter image description here

Below are my query's showing how im getting the ID and image path and then UPDATE table tbl1

 if(isset($_POST['submit'])){  // RETRIVE + UPLOAD THE IMAGE AVATAR FOR THE USER IF THEY SUBMIT A IMAGE TO UPLOAD
            move_uploaded_file($_FILES['file']    ['tmp_name'],"avatars/".$_FILES['file']['name']);
            include('..\db.php');
  $con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
            $q = mysqli_query($con,"UPDATE tbl1 SET imagelocation = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['CurrentUser']."'");
           // $me = mysqli_query($con,"UPDATE chat SET imagelocation = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['CurrentUser']."'");
    }
    }

Note Security has not yet been applied to the avatar upload option

enter image description here

<form>
<textarea name="msg" placeholder="enter message"></textarea> 
<input type="submit" name="submit" value="Send"/>
</form>

<?php
if(isset($_SESSION['CurrentUser'])){ // if session is true
if(isset($_POST['submit'])){
$name = $_SESSION['CurrentUser'];
$msg =  $_POST['msg'];

// GET THE NAME OF FILE FOR THE PATH
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_SESSION['CurrentUser']."'");
                        while($row = mysqli_fetch_assoc($q)){
                                echo $row['imagelocation'];
                                $path = $row['imagelocation'];


                        }

////////// SELECT FROM TBL1 TO GET ID OF USER (separate query )
 $q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_SESSION['CurrentUser']."'");
                        while($row = mysqli_fetch_assoc($q)){
                        echo $row['id'];
                        $onlineid = $row['id'];
                                }



////////// INSERT USERNAME MSG AND TIME + ID OF USER  NAME OF FILE
$query = "INSERT INTO chat (username,msg,date,avid,imagelocation) values ('$name','$msg', now(),'$onlineid','$path')";
$run = $con->query($query);

$me = mysqli_query($con,"UPDATE chat SET imagelocation = '".$path."' WHERE username = '".$_SESSION['CurrentUser']."'");


}
 }
 else {
     echo "You Need to Login to type in this chat";
 }
?>

Note : Security has not yet been applied to my query's Thanks in advance

  • sounds like you need to do a `join`: `select * from msgs join users on msg.userid = users.id` so you can get your avatar path. – Marc B Jul 07 '16 at 17:13
  • @MarcB Could you possible correct my query , I'm still not sure exactly . –  Jul 07 '16 at 17:24
  • all said and done but you're missing a lot of security checks - I'd focus on your security before advancing your software (ie: SQL injections inside your queries - use PDO prepare statements!, file upload - you haven't checked its an image and not a malicious script!, data encryption - use SHA256!) – Jaquarh Jul 07 '16 at 22:28
  • @KyleThomas This is not in a live environment , I have to apply security later on all my queries . Thanks For pointing it out though. I will look into SHA256 –  Jul 07 '16 at 22:31
  • I've added an answer for you to look at regarding it all @0v3kShi3ld3r - http://stackoverflow.com/a/38256566/5897602 – Jaquarh Jul 07 '16 at 22:58

2 Answers2

0

I know this is a different way from yours but it still gives the same results and in an easier way.

You can create a function which you can call from anywhere as long as you have the users unique id. Like this:

function get_user($user, $field) {
    // run your db connection here with $con as your db variable, remember we are using `mysqli` and not `mysql`
    $query = mysqli_query ($con, "SELECT $field FROM users_table WHERE id='$user'");
    $sql = mysqli_fetch_array($query);
    $value = $sql[$field];
    return $value;
}

This way you cannot only get the users images but also every value of the user in the users table as long as you have the id, so you can say:

$image = get_user($user_id, 'imagelocation');
$name = get_user($user_id, 'username');

And so on and forth. What I normally do I run this function in an external page which I always include in all my pages.

Hope this helps

KANAYO AUGUSTIN UG
  • 2,078
  • 3
  • 17
  • 31
  • Thanks , This does help . However I have the image location and the id of the user and can index any time . The query I have needs to be corrected to include the file path for each user in the message that is sent but for each user , I think JOIN is what I need but cannot follow the example given –  Jul 07 '16 at 18:42
  • Okay, then if that's the case I think you should show us the two tables required and their connection so we know how to write the query for you – KANAYO AUGUSTIN UG Jul 07 '16 at 20:49
  • Ive added code to show how I'm getting the ID and image path –  Jul 07 '16 at 21:51
0

How can I display a concatenated image in my Software based on user : Covering security issues

Firstly, you'll need to establish that you can't just jump into coding without a mission statement (a plan).

Let's start with your database hierarchy, we already know that we'll need a user and this user needs authentication so a login and register is needed.

USER_TABLE :
    uid (int) 255 PK AUTO_INCREMENT
    username (varchar) 30 UNIQUE
    salt (varchar) 22 UNIQUE
    hash (varchar) 120 UNIQUE
    rcab_rank (int) 255
    email (varchar) 60
    member_since (timestamp) CURRENT_TIMESTAMP
    image_url (varchar) 120
    session_key (varchar) 18 UNIQUE

I want to just highlight the importance of a few things here, having a unique session key makes it harder for people to session hijack or social engineer your clients/members. Using encryption means that if there was a breach of data, the attacker cannot use sensitive data without a lot of stress and time which you'll need to alert your members/clients.

But moving on, as you can see I added an RCAB module inside your structure meaning that you can now invoke power to your members/clients by creating a rank table and giving each rank priveledges and a unique rank id (which you'll need to code of course).

It's important now to decide the best secure approaches to your software, that meaning what connection drivers to use and how to securely use each. In this example, I'll provide you with a written PDO object:

namespace ProjectName\App\Drivers;

interface MyConnection {
    public function query($statement, array $values = []);
}

class Database extends \PDO implements MyConnection {

    public function __construct(
        array $config = ['mysql:host=X;dbname=X', 'user', 'pass']
    ) {
        try {
            parent::__construct($config[0],$config[1],$config[2]);
        } catch (PDOException $ex) {
            die($ex->getMessage());
        }
    }

    public $Result;

    public function query(
        $statement, array $values = []
    ) {
        $smpt = parent::Prepare($statement);
        (empty($values)) ? $smpt->execute() : $smpt->execute($values);
        $this->Result = $smpt;
        return $this;
    }
}

You can use this Object like so:

require_once dirname(__FILE__) . '/path/to/file/pdo.php';
$con = new ProjectName\App\Drivers\Database();
$smpt = $con->query('SELECT * FROM table WHERE column = ?', ['value'])->Result;
foreach($smpt->fetchAll() as $row):
    echo $row['column'];
endforeach;

It's now important to firstly hash (one-way encrypt) your members/clients credentials:

Click here to view a relatable StackOverflow question about creating a randomised string for your salt and session key.

$password = $_POST['password'];
$salt = 'UNIQUE STRING';
$hash = hash('SHA256', $password.$salt);

$con->query('INSERT INTO table (salt,hash) VALUES (?,?)', [$salt,$hash]); // ect..

Finally, checking your upload types is important - any user can easily upload a malicious script to your server using a file uploader unless you protect yourself: this being said, never check the file extension - you should always check the file MIME type.

That in conclusion, security is an important part of software and preventing it may seem a pain in the neck but you'll thank me later ;).

Just to say finally, you should rename the file before upload to a image directory on your server to something like $_FILES['upload']['name'] = time() . '-' . $user_id_here and then simply add it to your chat by storing that image path in the database in it's own table with a reference to the user by user id.

Community
  • 1
  • 1
Jaquarh
  • 6,493
  • 7
  • 34
  • 86