How to updating specific data from DB at specific periode - javascript

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;
//...

Related

Cache AND display images php

I am using a php script to display images stored as blobs in my database.
I used to display them with the following script.
<?php
if(!empty($_GET['user_id'])){//script to display an image from the database you basicly just get the id from the picture in matter and fucking acess it
include_once "DBH.php";
//Get image data from database
$id = mysqli_real_escape_string($conn, $_GET['user_id']);
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $id");
if($result->num_rows > 0){
$imgData = $result->fetch_assoc();
header("Content-type: image");
echo $imgData['image'];
}else{
echo 'Image not found...';
}
}
?>
In the context where
<img src = 'displayProfilePicture.php?user_id=n'>
The div containing the divs are updated frequently and to update the users image seems like alot of unnecessary processing. I want to cache the profilepictures in the webpage so that i dont have to query them from the database every time. I started reading alot about how you could cache the images but could not find any content on how to display the cached images.
This is a problem for me as the images flicker for a bit every time the img is updated with the php script. In an optimal world i see that the img load one time and then after that it does not have to load.
The context wich i use the display img script is in a chat that is updated with a timer-interval within an ajax-request
$("#chatlogs").load("logs.php");
logs.php
if(isset($_SESSION['chatRoomId'])){
while ($extract = mysqli_fetch_array($result1))
{
$from = $extract['from'];
//make an object to echo.
if($from == $id){
echo "<div class='chatContainer self'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$selfId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}else{
echo "<div class='chatContainer friend'>
<div class = 'imgContainer'>
<img src='displayProfilePicture.php?user_id=$guestId'>
</div>
<div class='content'>
<div class = 'message'>
". $extract['msg'] ."
</div>
</div>
</div>";
}
}
}
I think this is what you looking for:
<?php
if(empty($_GET['user_id']) || !preg_match( '/^[0-9]+$/' , $_GET['user_id'])){
header( '400 Bad Request' );
exit(1);
}
include_once "DBH.php";
$user_id = intval( $_GET['user_id'] );
$result = $conn->query("SELECT image FROM profilePictures WHERE user_id = $user_id");
if($result->num_rows == 0){
// Not Found
header('404 Not Found');
exit(1);
}
$imgData = $result->fetch_assoc();
header("Content-type: image");
$cache_for = 3600; // One hour in seconds
$cache_until = gmdate("D, d M Y H:i:s", time() + $cache_for) . " GMT";
header("Expires: $cache_until");
header("Pragma: cache");
header("Cache-Control: max-age=$cache_for");
echo $imgData['image'];
exit(0);
Comments
First I checked if the user_id is supplied in the request, if so then check if it was a valid number if it doesn't then respond with a 400 error.
And also I have removed a SQLi in your code src='displayProfilePicture.php?user_id=-1 or 1=1.
And I have set the caching headers, so the browser will cache the image for an hour.

Getting PHP session value in JQuery

I have a progress bar and a button.
When it reaches 100%, I use JQuery AJAX to check if the user already has an active giftcode in database or he doesen't. If he doesen't, I generate a new giftcode and insert it into the database.
The generating and inserting is working just fine. My problem is, I need the user account ID in the JQuery script. I'm currently using the hidden input method and it returns my account ID 0 every time, no matter which account I use.
This is the code on main page:
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" data-value="#Request.RequestContext.HttpContext.Session["ID"]" />
This is the JQuery file (where I check if user has active giftcode using AJAX):
$(function() {
var timer = 0;
$('#code').click(function () {
clearInterval(timer)
var value = 0;
timer = setInterval(function () {
value++;
$('.progress-bar').width(value + '%').text(value + '%');
if (value == 100) {
clearInterval(timer);
var sessionValue= $("#hdnSession").data('value');
$.post("checkcode.php",
{
ID: sessionValue
},
function(data)
{
$("#resultDiv").hide().html(data).fadeIn(1000);
});
}
}, 10);
})
});
And this is the .php file which does the checking:
<?php
include_once ('connect.php');
if(isset($_POST['ID']))
{
if(!empty($_POST['ID']))
{
$id = $_POST['ID'];
$select_user = "SELECT * from giftcodes WHERE UserID='$id'";
$query = mysqli_query($con, $select_user);
$row = mysqli_num_rows($query);
if(!$row) {
$randomcode = substr(md5(uniqid(mt_rand(), true)), 0, 8);
$insert_code = "INSERT INTO giftcodes (UserID, Giftcode) VALUES ('$id', '$randomcode')";
$query = mysqli_query($con, $insert_code);
echo'<br><hr><h1 style="color: #5cb85c;">Your generated gift code:</h1><br><pre><kbd style="background-color: #5cb85c; color: #000;">'.$randomcode.'<kbd></pre><hr><p class="small" style="font-weight:bold;">You can generate a new code in 24 hours.</p>';
} else {
echo 'You already have an active gift code!';
}
}
}
?>
So the problem is, var sessionValue= $("#hdnSession").data('value'); returns 0 every time although I'm sure the user $_SESSION['ID'] is set. If I generate a gift code, the UserID will get set to 0 every time.
If your "main page" is a php page you can use this (getting from php the $_SESSION['ID'] value and assign to value for the hidden input field
<div id ="resultDiv" style="text-align:center;"></div>
<input type="hidden" id="hdnSession" value="<?php echo $_SESSION['ID']; ?>" />
I can just use $_SESSION['ID'] in the PHP file.. don't know why I tried to get this so complicated. Sorry.

Session-based login not working as expected

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);
}
}
?>

How to insert value into one cell mysql database according to which page the user is at?

I have a system set up that will display certain pages. I have the paignation set up already. In each page, I want to have 5 radio buttons, each named as "Definitely No", "No", "Second look", "Yes", "Definitely Yes". When the user clicks one of the radio button, php should insert one value (1-5) to a column called "viewed" and a row according to the current page variable ($currentpage). The paignation and each page's code is here:
<?php
// database connection info
require_once "connect_database_viewer.php";
$table = 'JOBARXXX20140709';
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM $table";
$result = $db_server->query($sql) or trigger_error("SQL", E_USER_ERROR);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
// find out total pages
$totalpages = $numrows;
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
$query = "SELECT * FROM $table";
$result = $db_server->query($query);
if (!$result) die ("Database access failed: " . $db_server->error);
$rows = $result->num_rows;
$result->data_seek($currentpage);
echo $currentpage;
$row = $result->fetch_array(MYSQLI_NUM);
$asin = $row[2];
echo $asin;
echo file_get_contents("http://www.amazon.com//dp/$asin/?ie=UTF8");
echo <<<_END
<html>
<head>
<meta charset="=utf-8">
</head>
<body>
<div>
<iframe src="http://camelcamelcamel.com/product/$asin" width="1200" height="2300" align="middle"></iframe>
</div>
<div>
<form action="insert.php">
<input type="radio" name="result" value="1">Definitely No<hr>
<input type="radio" name="result" value="2">No<hr>
<input type="radio" name="result" value="3">Second Look<hr>
<input type="radio" name="result" value="4">Yes<hr>
<input type="radio" name="result" value="5">Definitely Yes<hr>
</form>
</div>
</body>
</html>
_END;
echo $currentpage;
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
How should I write the insert.php? This is a little insert code I wrote but I don't think it is working out.
if(isset($_POST['result']) && !empty($_POST['result'])){
$radioContent= $_POST['result'];
$sql = "UPDATE $table SET viewed='1' WHERE name='$currentpage'";
}
else{
error_log($mysqli->error);
}
}
A few things:
If you want to use the $_POST array, make sure to set your form method to post. <form action="insert.php" method="post"> The form element defaults to using GET.
$table and $currentpage will not be set in insert.php. You will have to send this information with your post. This can be done by making hidden inputs. <input type="hidden" value="<?php echo $currentpage ?>" name="currentpage" />. Now these variables will be accessible in the $_POST array. ($_POST['currentpage'])
ALWAYS escape any data being used for SQL queries. Including the hidden values made in #2. http://php.net/manual/en/mysqli.real-escape-string.php
You need to actually send the query to the database. As it is, you're only setting up the query string.

Pull down updates when user click on updates

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;
}
}

Categories

Resources