Is there a way to count how many people visited my site? - javascript

Is it possible to find out, how many people have visited your website?
I am looking for solution using Javascript or HTML.
If the user is on my website, it should count +1.
I have no idea and have not tried anything yet.

You can't possibly do it using JS or HTML because you do not have persistent storage. Meaning, once the client is closed all information is lost.
You're going to either need a database to keep track of how many people have visited your website (MySQL + PHP) or something along those lines
OR
You can use an external source such as google analytics which will do everything and more for you.

What you need to do is use persistent data storage. You can use a server side language like PHP to store data in the database or you use write to a file, then retrieve the data using AJAX requests to make it dynamic. As JavaScript is client side you can't do it.
Simple Overview
On load send request to PHP script to increment counter.
Then in that PHP script return the number of views and manipulate the DOM using JavaScript and display it.
Unique Visit Counter
You'd get something like the visitors IP and check if they have visited the site before (you'd insert the IP in to a table) and compare the users IP with the ones in the table.

try to use this code in php:
<?
Session_start();
$today = time();
$query="INSERT into logged_in (Today, SessionID, CurrentPage, BrowserType, IP) VALUES ('".$today."','".$_SESSION['sesid']."','".$_SERVER['PHP_SELF']."','".$_SERVER['HTTP_USER_AGENT']."','".$_SERVER['REMOTE_ADDR']."')";
$result = mysql_query($query);
?>
but you need also logged_in table. I hope this help you!

Related

Set SESSION on php and remove it via JAVASCIPT [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

pass javascript sessionStorage variable to php to insert to mySQL - form not an option

I have been asked to take upon to complete a small mini-project which was left incomplete by a previous front-end developer. The background is, there are 3 html pages with client-side javascript which takes the user input and stores it in a sessionStorage variable. On the second html page, it's the same thing, user response is stored in sessionStorage and finally on the third html page, the user provided data is displayed neatly, very nifty for use within a single user browser session. Now i have been asked to store the data in a backend mysql database. Now please understand that i am system admin and i have only worked on bits and pieces on coding. There is no one at the mo who can help me and i need to get this before the week is out. i have made a copy of the final.html page as final.php and running out from my localhost server, no problems with that.
Could someone please advice me on the quickest way to get this javascript variables to php variables and then i can do the mysql insert statements? Please due to time constraints, forms POST/GET submission is out as i don't want to redesign the whole thing. I was looking at cookies, hidden fields, PHP Sessions?
Sample:
<script>
sessionStorage.setItem("myvar1","1234");
var temper = sessionStorage.getItem("myvar1");
alert(temper);
</script>
<?php
// need help here....
?>
Regards,
Ochen

How can I create this simple alert in javascript?

I am creating a simple website using HTML and JavaScript in dreamweaver. On my home page, I want to show an alert (whenever my home page loads), which says that "Hello, you are visitor no. 12. Welcome to my site!". I want this visitor number to change on every page load of home.html.
I basically want the visitor no. to be stored in a cookie and increase the no. by 1 in the cookie every time the page refreshes.
How can I create such an alert? Please help. Thanks.
Also, I want to know if I add this functionality, would it be an example of dynamic content on a web page or do you HAVE to create database connections and all in order to create dynamic content. Wouldn't this idea of creating cookie also an example of dynamic content?
Edit-1
I want that only. How many times page was visited. I am a beginner and want it all simple. I just want to know how I can store the no. of visits in a cookie and then retrieve that value from that cookie and show it in an alert on page load. Thanks.
If you want to store the number of visitors, you'll need to use a backend scripting framework (PHP, Ruby, Rails, Python, etc) to store the number of visits your page has received in a database. The javascript of displaying the actual number is simple, with alert('message');
If you just want the number of times that specific user has visited, based on their local information, here's a simple solution:
if (localStorage.numVisits)
numVisits = localStorage.numVisits;
else
numVisits = 0;
alert("Welcome, you have visited " + numVisits + " times before.");
localStorage.numVisits++;
To make it really simple for you (without using the database) you can store the number in a .txt file in the server, and use a simple scripting language like PHP to send it in a hidden field to the client. Every time the PHP page runs, it will have to get the current number and increment it. Something like this:
$myFile = "counter.txt";
$fh = fopen($myFile, 'r');
$count = fgets($fh);
$count++;
fclose($fh);
$fh = fopen($myFile, 'w');
fwrite($fh, $count); // write the incremented counter
fclose($fh);
echo "<input type='hidden' id='counter' value='$count'>";
Then, you would have to get this counter value from the javascript (client side) and alert to the user.
var visitCount = document.getElementById('counter');
alert("Hello, you are visitor no. "+visitCount+". Welcome to my site!");
A Cookie is always Client-sided! You can't do it that way. The easiest way to accomplish what you are looking for is to write a simple php counter which reads a number from a file - adds one and writes it back as soon as your page is viewed.
Check google for examples on "counters".
There actually is no way to count clientsided ALL the visitors you have or had - the client can't know that your server was visited x times ;)
for that you need to create the table and every time when session is start u need to increase +1 in there table and alert the visitor no.
table like
id : no
-------
1 : 3
2 : 5
and massage like
echo "
<script type=\"text/javascript\">
alert(\"Hello, you are visitor no. {$row["no"]}. Welcome to my site!\");
</script>
";
You cannot keep a global page view count in a cookie. A cookie is stored in one user's browser and is local only to that browser. All a cookie could show would the page views that occurred in that one single browser.
Page view counts across all viewers must be done at the server level and then the information put into the page when the page is requested. There are some free ways to put page view counts into the page using the free service level of services like StatCounter.
Or, you'd have to implement a counter in your own server that was serving the page (with the count probably stored in a persistent database) and then insert the current count into the page each time it is requested. For just page count information, it's probably easiest to just go with a service like Statcounter.
Cookies are not persistent across different visitors. To give every visitor a visitor number, you need something stored on a server. If you cannot access server-side functions, use a visitor counter - https://www.google.com/#hl=en&q=visitor+counter

Remote poll using jQuery/javascript

I want to let my users create their own polls so they could paste my code somewhere on their website and users may rate their own game characters (with 1-5 stars rating).
I want to use jQuery or javascript for this purposes, but I have no idea how to start developing something like that. It should be free from being spoofed in any way, so I'd like to store the poll records in my database table (MySQL).
You probably had some experiences on this case, so I'm waiting for your suggestions.
Here is what I would do in a nut shell
First you are going host a javascript file and images for the stars somewhere, preferably on a CDN.
Second you need to setup a php file (or java or ruby or whatever you like for server-side) that can send and receive data via JSONP.
From here you ask your users to simply include the remote javascript file in the document head, and div on the page with a special class to signify that star rater (for this example .star).
Tasks:
Javascript: Populate all instances of <div class="star"></div> with your star images and set up.
Javascript: Request current rating tally average from server via JSONP with full identifiers (see step 4).
PHP: Use identifiers to find predetermined average of star rating so far, return current average rating as JSON. If non is found return 'unrated' state in JSON.
Javascript: Style stars so they all look correct, either displaying the current rating average received from ajax, or unrated state.
Javascript: Setup basic behaviors (hover style change ect.)
Javascript: Create click event bindings to stars. When user clicks you will have to send information about the rating to the server via AJAX JSON. This information needs to include the rating itself along with the url of the rater and any other identifiers.
something like:
{
url : 'http://endUsersite.com/pagetoberated.html',
starId : 'pictureOfBillMurray',
rating : 4,
raterIP : 192.168.1.130
date : UTCstringhere
}
Javascript: Restyle to show rating in progress and prevent future ajax from clicks.
PHP: Catch the JSON, process and store it in mySQL
PHP: After successful storage respond to ajax call with JSON stating the rating was successful
Javascript: upon getting 'success-response' of JSON, style stars to show successfully rated.
PHP: process ratings to determine new average.
You will most likely also want to implement some kind of timing system on the server-side to prevent rating spamming from the same IP address.
what have you tried? Searched?
Study the ones provided by sites like http://webpoll.sparklit.com/samples.spark
Obviously you will not see their server-side code, but at least you will see what is being received-stored-computed-sent at the client-side.

Javascript storing variable

I want to store some variable to the client side, currently, I have few selection (javascript variable, cookie, session), because I want to reduce the workload from the server, so the incoming parameter will not check on the server side.
For example,
Client side
<div id="showmoney"></div>
<script>
var money=10000;
$('#showmoney').html(money);
function changemoney()
{
{ pass the variable 'money' by ajax to php...}
}
</script>
PHP side
<?
$money = $_POST['money'];
$sql = "UPDATE user_details SET money = ".$money." WHERE uid = 123";
{ do query...}
?>
Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
thanks a lot~:)
Every variable that you do not want the user to change (such as a price tag) HAS to be stored on the server and not on the client. There are A LOT of ways to change what the client sends to you, and FireBug is just the simplest tool. More sophisticated tools will allow to intercept and edit every HTTP request..
Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
You can never, ever trust incoming data from the client. It can always be manipulated. Essential checks like prices you need to do on server side - a client side check is merely for the user's convenience.
Also, the code you show has a SQL injection vulnerability that you should sort out.
Anything you store in the client (browser) can be manipulated. The fix for your issue, is to verify that the information sent back to the server hasn't been tampered.
People can do just about anything to the page they want.
In the Google Chrome debugger (accessed with Ctrl+Shif+J) they could do the following in the console:
money = 10000000000000; //Or whatever arbitrary value they choose
changemoney();
As other people have said, never trust anything that people pass into the server from the client. The server needs to do a sanity check.
you have to align your desire to store something on the client for performance with the need for security. Sensitive info should only be on the server. Any savvy web user can tweak the javascript. Save bandwidth by putting other, less sensitive info on the client.
are you know about client side database storage the brand new API in HTML5. trying to find sollution with them. maybe helpful for you to save some data on client side.

Categories