i've create a chat in ajax, but i still have some problem that i can't recognize.
When the page is loaded, the php load all the opened chat and relative mex, then there's an addmex ajax function: when the user hits enter it's called passing this.value and the cod_chat. The ajax function send these data to the php, which insert them into the db and add the last mex into the chat. Every X seconds an update function is called, to update the chat.
It all works until it gets to the addmex function: the php works, because it add the mex into the db, but for some reason it refresh the page. Could i use RTMP?
This is the code of the form:
<input type='text' class='chat_input' value='write something' onkeydown='if (event.keyCode == 13){addmex(this.value); this.value='';}'/>
and this is the code of the ajax function (don't worry about the php variables because this function is loaded by echo):
function addmex(mex)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addmex.php?cod_contatto="+' . $cod_contatto . '+"&mex="+mex,false);
xmlhttp.send();
document.getElementById("messaggi_' . $cod_contatto . '").innerHTML+=xmlhttp.responseText;
}
I set Async as false because it respond slowly, and if i set true works only with some alert that let the server part complete. Any idea?
I've made a mini project script with mysql and this works realy perfect ! You dont need HTTPS for to hidding ajax file. Try this. THIS 100 % WORKS !
MYSQL CODE :
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `ajax_sessions`;
CREATE TABLE `ajax_sessions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sid` text NOT NULL,
`sip` varchar(18) NOT NULL,
`open` int(1) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE FILE NAMED security.php AND INCLUDE IT INTO MAIN PAGE LIKE index.php
INSERT AND SAVE THIS CODE
// INCLUDE YOUR MYSQL CONNECT FILE
require '/engine/config/mysql.php';
// SESSION IP ADDRESS
$sip = $_SERVER['REMOTE_ADDR'];
// COUNT IF TABLE FOR THIS IP ADDRESS EXISTS
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM ajax_sessions WHERE sip = '".$sip."'"));
// COUNT VAR
$count = $count['COUNT(*)'];
// GENERATE RANDOM SESSION ID
$sid = substr(str_shuffle("_-0123456789-_-abcdefghijklmnopqrstuvwxyz-_-ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"), 0, 50);
// YOUR AJAX / XMLHTTP / (LOAD) CALL
echo '
<script>
$("button").click(function() {
$(".container").load("/ajax/request.php?sid='.$sid.'");
});
// CHEC IF CODE WORKS
console.log("Ajax - Session control is activated.");
</script>';
// IF TABLE FOR THIS IP ADDRESS NOT EXISTS INSERT IP,SESSION AND OPEN SESSION.
if($count<1) {mysql_query("INSERT INTO ajax_sessions (sid,sip,open) VALUES ('".$sid."','".$sip."','1')");
} else {
// IF THIS IP ALREADY EXISTS INTO TABLE JUST UPDATE IT AND INSERT SESSION ID.
mysql_query("UPDATE ajax_sessions SET sid = '".$sid."', sip = '".$sip."', open = '1'");
}
PLACE THIS PHP CODE IN TO AJAX FILE
// IF GET sid ( SESSION ID )
if($_GET) {
// CHECK IF SESSION ID IS SET
if(isset($_GET['sid']) && $_GET['sid'] == $_GET['sid'] && !empty($_GET['sid'])) {
// SESSION REMOTE IP ADDRESS
$sip = $_SERVER['REMOTE_ADDR'];
// GET SESSION ID WE GOT
$sid = $_GET['sid'];
// COUNT IF THIS SESSION EXISTS IN MYSQL BASE
$fetch = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM ajax_sessions WHERE sid = '".$sid."' AND sip = '".$sip."' AND open = '1'"));
// COUNT SESSION
if($fetch['COUNT(*)'] == 1) {
// IF SESSION EXISTS CATCH IP ADDRESS AND CLEAR SESSION ID FOR THIS IP AND CLOSE IT, BUT NOT REMOVE
mysql_query("UPDATE ajax_sessions SET sid = NULL, sip = '".$sip."', open = '0'");
} else {
// DIE IF SESSION NOT EXISTS AND DO NOT SHOW CODE
die;
}
// IF IT WORKS OPEN JS CONSOLE LOG WITH F12 FOR GOOGLE CHROME
echo '<script>console.log("Session unseted !")</script>';
}
// AJAX POST CONTENT. IF POST
} else if($_POST) {
echo 'Call request';
}
I KNOW THAT THIS IS HARD TO UNDERSTAND BUT ITS REALY WORKS AND I'M USE IT.
How is your insert field implemented? If it is in a HTML form, it will send the form when you hit enter. So if this is given, you need to prevent the default enter action in order to prevent the page refresh:
Just get the js event (onkeydown), do what you need to do and return false.
EDIT
You may assign the handler in a diffrent way:
Give the input an ID so this will work:
document.getElementById(yourID).onkeydown = function(event) {
if(event.keyCode == 13){addmex(this.value); this.value='';}
return false;
}
EDIT 2
Your first code has a syntax error, it should be:
.... this.value="";}'/></form>
You cant use the same quotes in the inner String: '''' are like 2 strings, while '""' is one string in another.
SOLUTION For those who happen to read this.
The form tag was unnecessary and caused the page to refresh (sometimes preventing default does not work?!).
Finally there was the refreshing via ajax missing. Just do a setInterval() with the function and it should work all fine.
Maybe you can try ArcusNode or Cumulus. I suggest ArcusNode to proceed with. It's an OpenRTMFP protocol.
Related
I want to update a MySQL field after when the site was opened for X Seconds.
I get the Seconds/Time from MySQL and want to update in MySQL when the seconds are over.
I tried
sleep($adddisplaytime);
but then the site waits complete and does not run the things over first
Is there a way to run my update after some seconds when the site is opened?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
Can be in PHP or MySQL
NOTE: This will do what you want, but could be exploited by someone hitting the AJAX endpoint repeatedly, you would want to build in some protections for that.
You will need an additional PHP file, the job of that PHP is to only update the db. You will need to take that update OUT of your page loading script.
Your HTML / JS / PHP for initial load
<script>
setTimeout(function() {
$.ajax('/your/ajax/endpoint.php', {
data: {
'adid': 'your id'
/*
If this is in your PHP file, you can echo the ID straight there.
Not totally recommended, but that's one way An additional /
better way is to add it to a div with a data attribute and
use jQuery to select the data off of there
*/
}
}); // Probably lots more you can do here, but in this case, for simplicity, just sending and that's it
}, 2000); // This will do a 2 second wait
</script>
Your new additional PHP file that is at /your/ajax/endpoint.php
<?php
// THIS FILE DOES THE UPDATE
$adid = $_POST['adid'];
// As mentioned by tadman in his comment.. I would use prepared statements
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = ?";
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare($query1);
$sth->execute(array($adid));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
NOTE:
Again, for security's sake, you really want to consider having your first PHP script generate a unique ID (and store it in the db), that is passed to the page, and having the AJAX send that unique ID with the adid, and if the unique ID you gave is in the database only THEN would you know it's a legitimate request. Remove the unique ID from the database and do the update.
If you want to wait for some seconds after a page is opened and then run the update statement , then write the following codes on the top of the page:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");
Hello everyone so I have partly working code. However I also have issues with it. But let me start off to tell you what I am trying to achieve... On my site I have a login facility which sends all users to a home page once and only if the user is logged in. I would like to display who else is logged in on my page showing there usernames in a list.
My codes current ability...
Okay so i can code it to add the users on joining the site to a database and also then display each user on that database into a div which is great as it displays everyone online...
Where the problem stands...
However, when a user leaves the page there username needs to be deleted from the online user database. In the past I would simply do this with a on window close option in java. But due to Google safari and Firefox no longer supporting this option I am forced to find another way of doing it.
What the code bellow does...
So the code bellow loads an interval so after so much time it will repeat the code within it. The code first adds the user to the database, it then displays the user in a list on the site and then it deletes the user from the database just in case they are to then go offline.
Where the problem stands...
This all being very well for one user, but once a second user gets involved there intervals fall at a different time. So I have deleted the user from the database after it shows the list but then it means the second user displays the database and the first user isn't in it as they are deleted... This also causes a problem should a user go offline half way though the function happening, then it leaves them in the database and doesn't get around to deleting them out of the database.
The following is the java code...
$(document).ready(function() {
var user_name = "<?php print $username ?>";
setInterval(function() {
$.post('onlineusers.php', { name: user_name, action:"joined" });
$.post("onlineusers.php", { action2: "list" }, function(data){
$('#listusers').html(data);
});
$.post("onlineusers.php", { nameleft: user_name, action3:"left" }, function(data){
$('#errorrreport').html(data);
});
}, 5000);
}):
Now there is the PHP document code
//------------User joined page put into database --------
if( $_REQUEST["name"])
{
$user_name = $_REQUEST['name'];
};
if( $_REQUEST["action"])
{
$action = $_REQUEST['action'];
};
if ($action == 'joined') {
user_joined($user_name);
};
//-----------Listing online users within page -------------
if( $_REQUEST["action2"])
{
$action2 = $_REQUEST['action2'];
};
if($action2 == 'list') {
foreach (user_list() as $user){
echo $user . "<br />";
};
};
//------------ User left delete from the database ------------
if( $_REQUEST["nameleft"])
{
$user_nameleft = $_REQUEST['nameleft'];
};
if( $_REQUEST["action3"]){
$action3 = $_REQUEST['action3'];
};
if($action3 == 'left') {
user_left($user_nameleft);
};
//------ Functions what to do... --------
function user_joined($user_name) {
$user_name = mysql_real_escape_string(htmlentities($user_name));
mysql_query("INSERT INTO users (user_name)VALUES('$user_name')") or die("this didn't happen");
}
function user_left($user_nameleft) {
$user_name = mysql_real_escape_string(($user_nameleft));
$query = mysql_query("DELETE FROM users WHERE user_name = '$user_nameleft'")or die("failed to delete from table");
}
function user_list() {
$user_list = array();
$users_query = mysql_query("SELECT user_name FROM users") or die ("Unable to collect userlist");
while ($users_row = mysql_fetch_assoc($users_query)){
$user_list[] = $users_row['user_name'];
}
return $user_list;
}
The above code
Sorry it is slightly messy due to my recoding of it so many times in order to get it to work.
I would appreciate it if anyone could give me any help towards getting this to work. Now if it's not just simple off the code from above I can add the user to the online user database on entrance to the page and get it to list who is online frequently from listing the users on the database.
The real issue and where i am asking for your help with please...
However, if you have any idea on the code for the following that would be great... The user leaving the page is where the problem comes up. I need some method of checking the user is still active and if they are not then deleting them from the database so when the list then refreshes the user is no longer on the list. Such as pinging something until it ends up with no response and deletes the user from the database.
As my current code has problems with multiple users and synchronization of the interval function it needs to take that into account different users will see the list refresh at different times.
P.S. I have also looked at using $SESSION however i am still not sure on how to make this work with checking for offline users and then deleting them from the database this might be a method of doing it.
Thank you, I hope there is enough information to go on.
I've taken a different approach:
JS:
Loop of 5 seconds, AJAX requests onlinenow.php and displays the returned html in the online users box - This is mostly copied and pasted from W3C with the URL changed.
setInterval("getOnline()",5000);
function getOnline()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("onlineNow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.path.com/to/onlinenow.php",true);
xmlhttp.send();
}
PHP:
Takes user/ip/identifier and stores/updates that + unix timestamp in the DB
Returns a list of all rows with unix timestamp in the past 10 minutes
<?php
header('Access-Control-Allow-Origin: *');//Pretty sure this enables cross domain AJAX
$session = $_SERVER['REMOTE_ADDR'];
$time=time();
$time_check=$time-60; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="pass"; // Mysql password
$db_name="custom"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// Check if user is already in the DB
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
//User is not in the DB, lets add them
$sql1="INSERT INTO $tbl_name(session, time, ip)VALUES('$session', '$time', '".$_SERVER['REMOTE_ADDR']."')";
$result1=mysql_query($sql1);
}
//Update this user's entry
else {
//User is in the DB, Update their entry
$sql2="UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
//Done updating info, time to get the user list
// if over 10 minute, delete session - Could just get all in past 10 mins instead
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
//Get total users (Could get a list of names if you preferred and store the info)
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
if ($count_user_online == 1) {
$plur = "";
}
else {
$plur = "s";
}
echo " $count_user_online user".$plur." online now ";
// Close connection
mysql_close();
?>
I've used this logic several times with and without usernames shown (sometimes just a number).
The code, of course, could be improved, but the basic principle is a fairly good solution.
You could try instead of deleting to include a timestamp (server based) when inserting.
Then have the javascript code insert/update every minute or so.
Then your query of who's on is simply which rows have a recent timestamp (like the last 65 seconds)
You'll have to clear out old rows in the table eventually, of course, unless you want a log of everyone who was ever on and when.
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
Sorry for the vague, title! I have a website with a lot of PDF files and limited monthly bandwith. What i would like to achieve (in PHP) is a way to limit each user ($_SESSION?) to a certain limit - say 50MB, and beyond that when they clicked to download another file they would be redirected to a webpage denying any further downloads (for the next 24 hours, say).
Is this possible? I'm not sure if my download "counter" can only count .pdf files (I dont want vistors to be blocked from browsing the site if they reach the limit). Any psuedo code would be greatly appreciated.
If you have all of your downloads go through a single php script:
<a href="download.php?file='filename.pdf'" />
You can do pretty much whatever you want. That php file can deliver all of your files (keeping them out of the webroot), write to your _SESSION, and it can perform your redirect. Enjoy.
If you already have a user system, I would recommend to store all information within the users profile.
So there's no problem if he deletes all his cookies and relogins!
And for guests, I would recommend captchas and session or IP based restrictions.
// Pseudo code
// download.php
function UserHasReachedLimit($file)
{
$info = $Database->QueryUserInfo('limit');
$max = $Database->GetLimitForFile($file);
if ( $info[$file] > $max )
return false;
else
return true;
}
if ( IsUser() )
{
if ( UserHasReachedLimit() )
error();
else
download();
}
else // guest
{
// session or IP based restrictions...
}
I'd probably stay away from sessions for this. Sessions are volatile and susceptible to various browser behavior. For example, in Firefox if a session is initialized, I can close Firefox, visit the same site, and session is still active. However in IE if I open up multiple tabs and visit the same site, each tabbed instance gets a new session id.
I'd recommend setting up an account system where a user has to log into your site. Then you can track their download amount at the account level, which will persist between multiple sessions.
I think you are trying to avoid forcing user to register in your site, while you are trying to track per visitor bandwidth with is unpractical with the common ways(cookies, ip ...). So, the best way(in my opinion, of course there are many improved solutions) is to make a simple registration form, say name, password and email, put an activation system per email to protect your site from of user, now each user logged in and tried to download a file, you process his request in the following steps:
1) user request for file name.pdf (check its availability and size(important)).
2) check user bandwidth:
$query = sql_query("SELECT Bandwidth, LastDownload FROM Users, Stats WHERE USER_ID=5");
$result = sql_fetch($query);
if ($result['Bandwidth'] < 50M)
showDownloadLink();
else if($result['LastDownload'] - currentTime() !=0)
echo "please wait to the next 24h";
Database should be like this:
Users:
ID_U int(key, auto increment), Name varchar(25), email varchar(255), password varchar(32), Bandwith float
Stats:
ID_S int(key, auto increment), LastDownload time, ID_U integer
Note:
Each time user download a file, you update Bandwidth row for the right user, so later you can check if particular user reach its limit or not. You have also to reset it after each 24H.
This is a generic solution and many thinks have to be checked, like the counter bandwidth must be reset every 24H.
Create a table to store count downloads
CREATE TABLE IF NOT EXISTS `downloaded` (
`ip` varchar(200) NOT NULL,
`count` int(11) NOT NULL DEFAULT '0',
`last_access` datetime DEFAULT NULL,
UNIQUE KEY `ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<?php
/*
$limit => Number of Downloads Allowed
$period => In minutes
*/
function UserHasReachedLimit($limit, $period) {
$ip = addslashes($_SERVER['REMOTE_ADDR']);
$dl = false;
$sql = sprintf("SELECT UNIX_TIMESTAMP(last_access) last_time, count FROM downloaded WHERE ip = '%s' ORDER BY last_access DESC", $ip);
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) { // There is a registered IP already
$last_xs = mysql_result($res, 0, 'last_time');
$last_xs += $last_xs+$period * 60;
$count = mysql_result($res, 0, 'count'); // number of downloads by this ip
if ($count == $limit && $last_xs > time()) { // we check if downloads reached in this period
$dl = true;
} else {
$sql = sprintf("UPDATE downloaded SET count = CASE WHEN count >= %s THEN 0 ELSE count+1 END, last_access=now() WHERE ip ='%s'", $limit+1, $ip); // we just update download count + 1
mysql_query($sql);
}
} else { // There is not a registered IP and we create it
$sql = sprintf("INSERT INTO downloaded VALUES ('%s', '0', NOW());", $ip); mysql_query($sql);
}
return $dl;
}
/*
Usage
*/
$limit = 2;
$period = 2;
if(UserHasReachedLimit($limit, $period) == true) {
// User reached number of 2 downloads in 2 minutes
} else {
// Continue downloading
}
?>
I'm working on my CMS and I want it to log activities by users and other admins.
For example: when new user registers or admin makes a new news post -> update last activity.
I want to know what is the best and easiest way.
Create a table in your database to
log your user activity.
Define the various activity types
that can happen in your App.
Create a common function that logs
any activity to that table.
Call that function from anywhere
you perform log-worthy activities in
your app.
You can then write a reporting tool that gives your admins access to those logged activities, you can filter by user, time and activity types.
In my log-framework, I specially mark activities which could be seen as malicious actions and assign them different numeric threat-values. If the sum of a user's thread-value reaches a certain threshold I log-out the user.
Ideally if you write an Application, you write your infrastructure code like logging at the very beginning and then use it in all your business logic code later.
Edit for cleanup:
Over time you may collect lots of records in that table. Depending on your requirements you could do different things.
Delete any entries older than x days (maybe a year)
Delete any entries of certain types older than x days, but keep entries of other types for longer, or forever.
Move entries older than a certain threshold into an archive log table. This keeps your main table small but allows you to access older log data if you really have to. I have a checkbox Use archive on my review logs page.
Basic Answer
Instead of doing this yourself, from scratch, check out how some existing systems do it, and if their license allows, use their design and code (make sure you document what code you've used and add a copyright notice to your CMS somewhere).
Possibly Helpful Example
I'm not sure about PHP CMS's which do this, but I know Django's admin app does. Django is implemented in Python, but it should be fairly straightforward to port this code over to PHP. Even if the code isn't a straight port, the design could be ported.
The file which contains the logging is in the admin module in models.py.
Some key aspects:
The data model for the logging table:
class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)
objects = LogEntryManager()
And the LogEntryManager, which saves the actual log entries:
class LogEntryManager(models.Manager):
def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message)
e.save()
I use two tables for activities, one that gives each activity an id, and another one that just logs the user id, activity id, and a timestamp. I do this because an int takes up less space than a string, so why log the same strings over and over? The second one isn't really necessary, you just just as easily keep the action codes in a text file for your own reference, but the db just seems like a easier place to remember.
In the past I've used a function to handle the actual logging actions, but the next time I do it I'm going to be using the Observer pattern. It appears to be a lot more flexible, and I've already had to edit out logging function calls from older code I have that wasn't going to log anything. I much prefer reusing code with no editing required.
Its very simple to do with PHP/JAVA FUNCTION JQUERY and its AJAX data posting method...
Before posting the solution -- Lets read these two lines
Why and What we want to record ?
--- As we know only to record transaction with in the database --not all the clicks and checks -- but yes its possible with this solution....
Here is the solution step by step: -
1. create a DB Table -- to record these things
a) Page Name.
b) logged in user name
c) session details (To record all the sessions).
d) POST/GET data details (To record all the post/get data for the
page)
e) Record Created Date.
or any other thing that you want to record.
2. Create a Jquery function or PHP function -- which will be auto triggered with every page.
3. This function will collect all the session of that page,user logged in details and what data passed to that page.
Apart from this - you can also record -- from which page this new page is called -- Its pretty simple and best way to implement loggs recording features even in already running old software's :)
If you want all the Code i mentioned above to use -- Search it over the NET the mechanism i have defined just you need FUNCTION CODE -- AUTO execute function code -- simple
PHP AND MYSQL
Create a Table to save the logs
CREATE TABLE `test_loq` (
id int(11) PRIMARY KEY AUTO_INCREMENT,
page varchar(255) NOT NULL,
username varchar(255) NOT NULL,
log_time datetime DEFAULT CURRENT_TIMESTAMP,
log_action longtext NOT NULL,
log_name varchar(255) NOT NULL,
user_id int(11) NOT NULL,
ip int(11) NOT NULL
)
explain :
log_action is the kind of action made here you can write a lot of information about the action that has been made.
page is the page that the action was made of, the name of the php file
log_name is the name of the action that was done
username is the name of the user that hade made this action
user_id is the id of the user that made this action
ip is the ip adress of the user
2. Create a Class
class log
{
CONST ENVIRONMENT = 'developemnt';
private $id;
protected $log_action;
protected $username;
protected $page;
protected $ip;
protected $log_name;
private $user_id;
public function __construct(string $log_action, string $username, string $log_name)
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if(!empty($_SESSION['id'])){
$id = $_SESSION['id'];
} else {
$id = 0;
}
$this->log_action = $log_action;
$this->username = $username;
$this->log_name = $log_name;
$this->user_id = $id;
$this->page = basename($_SERVER['PHP_SELF']);
$this->ip = $ip;
}
public function createAction()
{
global $conn;
if(!$conn) {
echo mysqli_error($conn); die;
}
$sql = "INSERT INTO test_log (`log_action`,`username`,`log_name`,`page`,`user_id`,`ip`) values ('".$this->log_action."','".$this->username."','".$this->log_name."','".$this->page."','".$this->user_id."','".$this->ip."')" ;
$sql_query = mysqli_query($conn,$sql);
if(!$sql_query){
echo mysqli_error($conn); die;
}
if(ENVIRONMENT == 'development'){
$_SESSION['msg'] = 'A new log was created ' . $this->log_name;
}
} }
explain:
ENVIRONMENT can be development or production , if it's in development it will show flash messages about the log that has been made
3.Log An Action!
example: log action for login attempts
Create a php file logincheck.php
<?php
session_start();
include("include/configurationadmin.php");
//include_once('../include/classes/config.inc.php');
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$sql = mysqli_query($conn,"select * from ".$sufix."admin where username='".$username."'") ;
// HERE HOW TO LOG ACTION
$log = new log("Logging in attempt from $username" , $username ,'Login Attempt' );
$log->createAction();
//SIMPLE AND COOL RIGHT?
if(mysqli_num_rows($sql) > 0)
{
$rows = mysqli_fetch_assoc($sql);
if(md5($password) == $rows['password']) {
$_SESSION['id'] = $rows['id'];
$_SESSION['username'] = $rows['username'];
$_SESSION['usertype'] = $rows['type'];
mysqli_query($conn,"update ".$sufix."admin set lastlogin='".date('Y-m-d')."' where id = '".$rows['id']."' and username='".$rows['username']."'") ;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('rrdssrdda', $rows['id'], time()+120, '/', $domain, false);
header("Location: http://localhost/test/admin-new/dashboard");
exit();
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
}
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
} ?>
Happy Coding!