I have been developing a PHP and mysqli based social network as a side project. All has been going well up till this point. Everyone can register and I am using the crypt function to store passwords.
I am using an if and else statement with the password_verify function where I set $_SESSION variables and cookies in order to login. Again this works and once logged in the system redirects me to my user profile as it should.
However my site-top.php file does not work as it should; what should happen is that the dynamic login link buttons should change from the login and register buttons to the logout, profile and notification buttons.
Also the add as friend button and block button are disabled on my profile (as it should as I don't want to block or friend myself) but they are also disabled when I visit another's profile which it should not.
Here is the code for my site top for the time being. I have also got a check-login-status file should you wish me to post the code for that or any others:
<?php
// It is important for any file that includes this file, to have
// check_login_status.php included at its very top.
$envelope = '<img src="assets/note_dead.png" width="33" height="33" alt="Notes" title="This envelope is for logged in members">';
$loginLink = '<li><a class="tooltip-bottom" data-tooltip="Register an Account" href="signup.php">Register</a></li>
<li><a class="tooltip-bottom" data-tooltip="Login" href="login.php">Login</a></li>';
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$notescheck = $row[0];
$sql = "SELECT id FROM notifications WHERE username='$log_username' AND date_time > '$notescheck' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if ($numrows == 0) {
$envelope = '<img src="assets/note_still.png" width="33" height="33" alt="Notes">';
} else {
$envelope = '<img src="assets/note_flash.gif" width="33" height="33" alt="Notes">';
}
$loginLink = '<li><a class="tooltip-bottom" data-tooltip="Logout" href="logout.php">Logout</a></li><li>'.$log_username.'</li>';
}
?>
OK this is my check-login-status.php script for all that wanted it...
<?php
session_start();
include_once("db_conx.php");
// Files that inculde this file at the very top would NOT require
// connection to database or session_start(), be careful.
// Initialize some vars
$user_ok = false;
$log_id = "";
$log_username = "";
$log_password = "";
// User Verify function
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
$query = mysqli_query($conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
$log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
$log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
$log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
$_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
$_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
$_SESSION['password'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['pass']);
$log_id = $_SESSION['userid'];
$log_username = $_SESSION['username'];
$log_password = $_SESSION['password'];
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
if($user_ok == true){
// Update their lastlogin datetime field
$sql = "UPDATE users SET lastlogin=now() WHERE id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
?>
Related
What is the way to keep update the info about if user has got new notifications?
When page is opened it includes content of pageTop.php. There it checks database, if there are some unchecked notification. And loads note_NO or note_YES in base of query.
How is the approach to have new info at certain time period ?
Next page works on page load or refresh. But I don't want to reload header.php each time.
header.php:
<?php include_once("pageTop.php");?>
<div id="pageMidle"></div>
<div id="pageFoot"></div>
pageTop:
$sql = "SELECT id FROM note WHERE user='$l_user' AND did_read ='0' ";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_row($query);
$nrows = mysqli_num_rows($query);
if ($numrows == 0) {
$envelope = '<img src="images/note_NO.jpg" width="30" height="30" alt="Notes">';
} else {
$envelope = '<img src="/images/note_YES.gif" width="30" height="30" alt="Notes">';
}
html:
<div id="envolopeDIV">
<?php echo $envelope; ?>
</div>
You can use a session to keep track of time between requests in the backend. If your specified time period has passed, include the snippet for querying the database.
session_start();
const TIME_PERIOD = 123456;
$currentTimestamp = time();
$previousTimestamp = $_SESSION['previous_timestamp'] ?? 0;
if ($previousTimestamp + TIME_PERIOD > $currentTimestamp) {
// check notifications
}
$_SESSION['previous_timestamp'] = $currentTimestamp;
//...
I have two problems.
First one:
I have a two tables in my database (gmembers and groups) and I want to check if a user quit from the group and there are no memebrs remaining in it delete that group. Firstly I collected every groups that has no members in an array called junk. Then I used a for loop to access every item of the junk array and delete from the database. But since I want to delete from two tables at the same time I had to use JOIN. I don't know why but this only delete from the gmembers table and nothing happens with the groups table.
I tried to tear it into two parts and delete once from the gmembers and then from the groups in another sql but I got the same result as I got with the JOIN one.
Code:
<?php
if(isset($_POST["action"]) && $_POST['action'] == "quit_group"){
// Empty check
if($gS == "" || $uS == ""){
exit();
}
// Make sure already member
$sql = "SELECT id FROM gmembers WHERE gname=? AND mname=? AND approved=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss",$gS,$uS,$one);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$numrows = $stmt->num_rows;
if($numrows < 1){
exit();
}
// Remove from the database
$sql = "DELETE FROM gmembers WHERE mname=? AND gname=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$uS,$gS);
$stmt->execute();
$stmt->close();
// If the group is empty remove from the database
$junk = array();
$sql = "SELECT * FROM gmembers WHERE approved=? AND admin=?";
$stmt = $conn->prepare($sql);
$stmt->bind_result($zero,$zero);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
array_push($junk, $row["gname"]);
}
$stmt->close();
for($i=0; $i<count($junk); $i++){
// Delete from gmembers
$groupa = $junk[$i];
$sql = "DELETE * FROM gmembers gm JOIN groups gr ON gm.gname = gr.name WHERE gm.gname=? AND gr.name=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss",$groupa,$groupa);
$stmt->execute();
$stmt->close();
}
echo "was_removed";
exit();
}
?>
Second One:
I'm also having problems with ajax.responseText. When a group has been created and there are no erros I want to header the user to that groups that he/she has just created. So when everything is fine I echo the name of the group ($name) and the was created title. Then with javascript I check for these and I header them to the group page. But at this point my code fails. It only echos group_created|example group in an alert box and window.location = "group.php?g="+sid; does not work.
PHP Code:
<?php
// Create new group
if(isset($_POST["action"]) && $_POST['action'] == "new_group"){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$name = preg_replace('#[^a-z 0-9]#i', '', $_POST['name']);
$inv = preg_replace('#[^0-9.]#', '', $_POST['inv']);
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
if ($inv == "1"){
$inv = "0";
}
if ($inv == "2"){
$inv = "1";
}
$sql = "SELECT id FROM groups WHERE name=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$name);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
$n_check = $stmt->num_rows;
// FORM DATA ERROR HANDLING
if($name == "" || $inv == ""){
echo "The form submission is missing values.";
exit();
} else if ($n_check > 0){
echo "The group name you entered is alreay taken";
exit();
} else if (strlen($name) < 3 || strlen($name) > 50) {
echo "Group name must be between 3 and 50 characters";
exit();
} else if (is_numeric($name[0])) {
echo 'Group name cannot begin with a number';
exit();
} else {
$stmt->close();
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Add group to database
$gicon = "group_icon.png";
$sql = "INSERT INTO groups (name, creation, logo, invrule, creator)
VALUES(?,NOW(),?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss",$name,$gicon,$inv,$uS);
$stmt->execute();
$stmt->close();
// Add to group member to database
$sql = "INSERT INTO gmembers (gname, mname, approved, admin)
VALUES(?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss",$name,$uS,$one,$one);
$stmt->execute();
$stmt->close();
if (!file_exists("../groups")) {
mkdir("../groups", 0755);
}
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("../groups/$name")) {
mkdir("../groups/$name", 0755);
}
$gLogo = '../images/group_icon.png';
$gLogo2 = "../groups/$name/group_icon.png";
if (!copy($gLogo, $gLogo2)) {
echo "failed to create logo.";
}
echo "group_created|$name";
exit();
}
exit();
}
?>
The error handling, inserting, folder/file creating etc. works perfect except this line: echo "group_created|$name";
JS Code:
function createGroup(){
var name = _("gname").value;
var inv = _("invite").value;
if(name == "" || inv == ""){
alert("Fill in all fields");
return false;
}else{
status.innerHTML = 'please wait...';
var ajax = ajaxObj("POST", "php_parsers/group_parser.php");
ajax.onreadystatechange = function(){
if(ajaxReturn(ajax) == true){
var datArray = ajax.responseText.split("|");
if(datArray[0] == "group_created"){
var sid = datArray[1];
window.location = "group.php?g="+sid;
}else{
alert(ajax.responseText);
}
}
}
ajax.send("action=new_group&name="+name+"&inv="+inv);
}
}
Here I check for what ajax gives back and I split into two part the echo "group_created|$name"; but the window.location function does not work.
For the Second One
Use:
window.Location.assign("group.php?g="+sid);
Or:
window.Location.replace("group.php?g="+sid);
I want to get the clicked number
and load the data from the database according to this number. The column that the numbers are stored is named as id.
I have this code in order to display the numbers(id)...
$sql = "SELECT id FROM work WHERE username='$username' order by id asc limit 10;";
$result = mysql_query($sql);
if ($result != 0) {
$num_results = mysql_num_rows($result);
for ($i=0;$i<$num_results;$i++) {
$row = mysql_fetch_array($result);
$id = $row['id'];
echo '' .$id. '';
}
}
And then I want to load the data from this number in a form which the code for the form is...
function kotoula() {
$username = $_SESSION["username"];
if($query = mysql_query("SELECT job_title,company,website,start_date,end_date,start_year,end_year,work_history FROM work WHERE id>'$id' AND username='$username' order by id asc limit 10") or die(mysql_error()))
{
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$job_title = $row['job_title'];
$company = $row['company'];
$website = $row['website'];
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$start_year = $row['start_year'];
$end_year = $row['end_year'];
$work_history = $row['work_history'];
}
}
}
}
Just put it in the URL using GET. Something like:
http://yoururl.com/user.php?id=12345
Then, user.php will receive that value on $_GET array. Example:
$_GET['id'];
Hello people please help me with this! what i want to achieve is similar to twitter update notification bar that displays the number of new tweets and when you click on it; it drops the latest tweets on the previous tweets. i have been banging my head over this for days now, Here is what i tried.
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
interval = setInterval(function(){
check_update($latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data);
}); //checks for number of updates
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty($_POST['get_num_update']) && is_numeric($_POST['get_num_update']))
{
$old_feed = $_POST['get_num_update'];
$query = "SELECT id FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$num_updates = mysqli_num_rows($exec);
echo ($num_updates > 0) ? $num_updates.' new updates' : '';
}
if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
//
when the user clicks on the update_bar div which will be displaying something like '5 new updates' i want the update to pull down the latest feed from the hidden div, so everything doesn't really work as i would expect someone please help me out
Not tested, but it should approximately work...
//feed.php
<?php
session_start();
$cxn = mysqli_connect('localhost','root','','my_db');
$query = "SELECT insertion_time FROM feeds ORDER BY insertion_time DESC LIMIT 0,1";
$result = mysqli_query($cxn, $query) or die (mysqli_error($cxn));
$latest_feed = mysqli_fetch_assoc($result);
$_SESSION['latest_id'] = $latest_feed['insertion_time'];
$latest_news = $_SESSION['latest_id'];
echo $check = <<<JS_SCRIPT
<script>
// made the parameter of check_update a js variable and not hard coded in PHP
var latest_new=$latest_news;
// add a temp js variable for the last feed received (but not displayed)
var last_received=$latest_news;
interval = setInterval(function(){
check_update(latest_news);
},5000);
</script>
JS_SCRIPT;
?>
<script src='jquery.js'></script>
<script>
function check_update(old_feed)
{
// change your AJAX request to deal with JSON data and received several informations (number of new feed, insertion time of the last one)
$.post('server.php',{get_num_update: old_feed},function(data){
$("#update_bar").html(data.number_recents+" new updates.");
last_received=data.last_time;
},'json');
$.post('server.php',{retrieve_update: old_feed},function(data){
$("#hidden_div").html(data);
}); //retrieves the update into a div
}
$(function(){
$("#update_bar").click(function(){
$("#hidden_div").prependTo("#news_feed_container").fadeIn(500);
latest_new=last_received;
});
});
</script>
//server.php
if(isset($_POST['get_num_update']) && !empty(get_num_update']))
{
// header to serve JSON data
header('application/json');
$old_feed = $_POST['get_num_update'];
// request the number of new feed and the mst recent insertion time
$query = "SELECT count(*) as number,max(insertion_time) as last_time FROM feeds WHERE insertion_time > $old_feed ORDER BY insertion_time DESC";
$exec = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$feed_info = mysqli_fetch_assoc($exec);
//write the JSON data
echo '{"number_recents":'.$feed_info['number'].',"last_time":'.last_time.'}';
} else if(isset($_POST['retrieve_update']) && !empty($_POST['retrieve_update']) && is_numeric($_POST['retrieve_update']))
{
while($result = mysqli_fetch_assoc($exec))
{
extract($result);
echo <<<HTML
//inserting the variable into html
HTML;
}
}
i am having some trouble with some script on my site.
i followed part of a tutorial as i liked the friend adding part but didn't want to change the whole site.
i used his code but obviously had to change some it to work on my site.
the idea is you visit someone else's profile and you can click to either block or send a friend request.
i am not sure where the issue is. i cant see any thing wrong in the php but is is possible i am missing something there as i am no expert, i am even less of an expert with javascript/ajax so this leads me to believe i have broken something in that.
here are my codes.
//Script on the profile.php page
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $username; ?>.");
if(conf != true){
return false;
}
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
_(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
_(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $id; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&id="+id);
}
//php script for the friend_system.php page
<?php
include_once("scripts/checkuserlog.php");
?>
<?php
if (isset($_POST['type']) && isset($_POST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_POST['id']);
$sql = "SELECT COUNT(id) FROM myMembers WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$exist_count = mysqli_fetch_row($query);
if($exist_count[0] < 1){
mysqli_close($db_conx);
echo "$username does not exist.";
exit();
}
if($_POST['type'] == "friend"){
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$id' AND blockee='$logOptions_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$logOptions_id' AND blockee='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count3 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count4 = mysqli_fetch_row($query);
if($blockcount1[0] > 0){
mysqli_close($db_conx);
echo "$user has you blocked, we cannot proceed.";
exit();
} else if($blockcount2[0] > 0){
mysqli_close($db_conx);
echo "You must first unblock $user in order to friend with them.";
exit();
} else if ($row_count1[0] > 0 || $row_count2[0] > 0) {
mysqli_close($db_conx);
echo "You are already friends with $user.";
exit();
} else if ($row_count3[0] > 0) {
mysqli_close($db_conx);
echo "You have a pending friend request already sent to $user.";
exit();
} else if ($row_count4[0] > 0) {
mysqli_close($db_conx);
echo "$user has requested to friend with you first. Check your friend requests.";
exit();
} else {
$sql = "INSERT INTO friends(user1, user2, datemade) VALUES('$logOptions_id','$id',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "friend_request_sent";
exit();
}
} else if($_POST['type'] == "unfriend"){
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
if ($row_count1[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else if ($row_count2[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else {
mysqli_close($db_conx);
echo "No friendship could be found between your account and $user, therefore we cannot unfriend you.";
exit();
}
}
}
?>
i have been looking at it now for a couple of days and am starting to not see the wood for the trees.
When i click on the request as fiend button, i get the dialog box fine, click ok and then it replaces the button with "please wait..." but that is where it stops. i have checked and nothing is being added to the database niether.
any help you could offer would be much apreciated.
thanks
I have provided an example of using jQuery to do this simply.
Here is what your button and response box would look like.
<div id="responsemessage<?php ///YOU USER ID FROM PHP// ?>" style="padding:2px; display:none;"></div>
<input name="" type="button" value="Friend Me" onClick="friendToggle('friend','<?php ///YOU USER ID FROM PHP// ?>')"/>
<input name="" type="button" value="Block Me" onClick="friendToggle('block','<?php ///YOU USER ID FROM PHP// ?>')"/>
This is what your jQuery function would look like. You will need to include the jQuery lib in your header.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>function friendToggle(type,user){
///This is the ajax request via jQuery///
$.ajax({
url: 'friend_system.php?action='+type+'&user='+user,
success: function(data) {
///This is where the response from you php is handled. Sky's the limit//
if(data == 'good'){
$("#responsemessage"+user).html('You now have a friend.');
}else{
$("#responsemessage"+user).html(data);
}
}});
}</script>
</head>
And here is the php to process the requests this would be in your friend_system.php
<?php
include('YOUR CONNECTION DETAILS FILE');
$act = $_REQUEST['action'];
if($act == 'friend'){
$a = mysql_query("SELECT * FROM friends WHERE user1 = '".$_REQUEST['user']."'");
if(mysql_num_rows($a) > 0){
echo 'You are already friends.';
}else{
mysql_query("INSERT INTO friends SET user1 = '".$_REQUEST['user']."', user2 = '', datemade = '".date('d-m-Y H:i')."'");
echo 'good';
}
}
if($act == 'block'){
mysql_query("INSERT INTO blockedusers SET blocker='YOUR ID HERE, HOPE ITS PASSED VIA SESSION' AND blockee='".$_REQUEST['user']."'");
echo 'You have blocked this user.';
}
?>
I hope this helps you... Also be sure to check out http://jquery.com/