I want to add a counter in my webpage which counts the number of visitors.
But my problem is that when i refresh my page ,counter increases by 1..i want that counter increases only when a new visitor with another ip reaches to my webpage.
here are my codes..
Sorry for my weak english
index.php
<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$_SESSION['current_user'] = $ip;
if(isset($_SESSION['current_user']))
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
else
{
$count = file_get_contents("counter.txt");
$count = trim($count);
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
}
As database based solution is not preferred, You can try the following file based solution for counting unique visitor. You already have used counter.txt file in your code.
I tried to use the same file that you have used. In my case I am storing IP address in that file. I have used base64 encoding function just to hide the IP address. It is always good to keep that file in a safe place. If that file is lost then the unique visitor IPs will be lost. See the function below:
Function definition
function getUniqueVisitorCount($ip)
{
session_start();
if(!isset($_SESSION['current_user']))
{
$file = 'counter.txt';
if(!$data = #file_get_contents($file))
{
file_put_contents($file, base64_encode($ip));
$_SESSION['visitor_count'] = 1;
}
else{
$decodedData = base64_decode($data);
$ipList = explode(';', $decodedData);
if(!in_array($ip, $ipList)){
array_push($ipList, $ip);
file_put_contents($file, base64_encode(implode(';', $ipList)));
}
$_SESSION['visitor_count'] = count($ipList);
}
$_SESSION['current_user'] = $ip;
}
}
Function call
$ip = '192.168.1.210'; // $_SERVER['REMOTE_ADDR'];
getUniqueVisitorCount($ip);
echo 'Unique visitor count: ' . $_SESSION['visitor_count'];
Output
Unique visitor count: 2
Change:
if(isset($_SESSION['current_user']))
to:
if($_SERVER['REMOTE_ADDR'] == $_SESSION['current_user'])
And, surely you dont need to get $count from a file, and then write the same value back to the file...? If the $_SERVER['REMOTE_ADDR'] matches the SESSION['current_user'] then do nothing..
try to store the user IP in database and check for unique user,
<?php
session_start();
if (!$_SESSION['status']) {
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("ip_log", $connection);
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");
mysql_close($connection);
$_SESSION['status'] = true;
}
?>
Best And Easy Code
Try to store the user IP in database and check for unique user
$`servername` = "";
$username = "";
$password = "";
$`dbname` = "";
$`conn` = new `mysqli`($`servername`, $username, $password, $`dbname`);
if ($`conn`->connect_error) {
die("Connection failed: " . $`conn`->connect_error);
}
$address = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$name = `gethostname`();
$re = "select * from visitor where name='$name'";
$call = `mysqli_fetch_array`($re);
$as = `mysqli_num_rows`($call);
if($as == 0){
$`sql` = "UPDATE visitor SET visits = visits+1 WHERE name = '$name'";
}else{
$`sql` = "INSERT INTO visitor(visits,name,address) VALUE(1,'$name','$address')";
}
$`conn`->query($`sql`);
$`sql` = "SELECT visits FROM visitor WHERE id = 1";
$result = $`conn`->query($`sql`);
if ($result->`num_rows` > 0) {
while($row = $result->fetch_assoc()) {
$visits = $row["visits"];
}
} else {
$visits = "";
//echo $visits;
}
`$conn`->close();
Related
I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
I am trying to store IP's in a MySQL database and I had a few problems with it which i was able to fix but i keep getting 1 error for people that trying to get onto my website. So when someone gets on my website their IP is displayed with a time stamp but it only works when I connect to my website. When I got my friend to go onto my website he got an error saying why u no query? which helps me find out where the problem is. Now the problem is that I have been trying to solve this issue for the past 2 hours with no luck :(
Screenshot of my screen: My screen
Screenshot of my friends screen: Friends screen
<html>
<head>
<title>Your IP!</title>
</head>
<body>
<?php
$db_host = '127.0.0.1';
$db_user = '***************';
$db_pwd = '*************';
$db = '***************';
// Find their IP and tell them what it is.
$con=mysqli_connect($db_host, $db_user, $db_pwd);
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pip = getenv('HTTP_X_FORWARDED_FOR');
$ip = getenv('REMOTE_ADDR');
echo "Your Proxy IP is: ".$pip."(via ".$ip.")";
} else {
$ip = getenv('REMOTE_ADDR');
echo "Your IP is: ".$ip;
}
echo "<br /><br />";
// Try to select the database.
if(!mysqli_select_db($con, $db)) {
// die("why u no use db? ".mysql_error());
die("why u no use db?");
}
// Try to perform query.
// This is a function so it may easily be called multiple times.
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
}
return $result; // Give back result.
}
// Try to see if they are in the database already,
// and if not, then add them.
$result = do_query("select ip from ips where ip='".$ip."'");
$rows = mysqli_num_rows($result);
if($rows == 0) {
do_query("insert into ips (ip) values ('".$ip."')");
}
// Now, display the table.
$result = do_query("select * from ips");
$cols = mysqli_num_fields($result);
echo "<table cellpadding=\"5\" bgcolor=\"#7F7F7F\"><tr>";
for($i = 0; $i < $cols; $i++) {
echo "<td>".mysqli_fetch_field($result)->name."</td>";
}
echo "</tr>";
while($row = mysqli_fetch_row($result)) {
echo "<tr>";
for($i = 0; $i < $cols; $i++) {
if($row[$i] == $ip) { // bold their IP.
echo "<td><b>".$row[$i]."</b></td>";
} else {
echo "<td>".$row[$i]."</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
So first I changed
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die("why u no query?");
to
function do_query($query) { // Take in query.
global $con;
if(!$result = mysqli_query($con, $query)) {
// die("why u no query? ".mysql_error());
die(mysqli_error($con));
Which showed me the error which was Duplicate entry '0' for key 'PRIMARY' and the problem was that I did not set AUTO_INCREMENT on the Primary key.
how can I create system for example when to my mySQL was inserted nickname: ,,Sprunkas'' and say can login not only with ,,Sprunkas'' but with ,,SPRUNKAS'', ,,sprunkas'' and etc. ? Here is some my PHP code:
if(isset($_POST['jungtis'])) {
if($_POST['login_slapyvardis'] != "" && $_POST['login_slaptazodis'] != "") {
$login_slapyvardis = mysql_real_escape_string($_POST['login_slapyvardis']);
$login_slaptazodis = mysql_real_escape_string($_POST['login_slaptazodis']);
$apsaugotaslogin_slaptazodis = md5($login_slaptazodis);
if($login_db == $login_sumazintas) {
$mysql = mysql_query("SELECT * FROM ucp_users WHERE name='$login_slapyvardis'") or die(mysql_error());
$mysqlskc = mysql_fetch_assoc(mysql_query("SELECT * FROM ucp_users WHERE name='$login_slapyvardis'"));
$login_sumazintas = strtolower($login_slapyvardis);
$login_db = strtolower($mysqlskc['name']);
$mysqli = mysql_fetch_array($mysql);
if($mysqli['password'] == $apsaugotaslogin_slaptazodis) {
$_SESSION['Logged'] = $mysqli['id'];
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("UPDATE ucp_users SET lastip = '$ip' WHERE id = '$mysqli[id]'");
header('Location: /home');
Thank you in advance for help!
Firstly you need to convert the post username into lowercase before querying the database.
$login_slapyvardis = mysql_real_escape_string(strtolower($_POST['login_slapyvardis']));
Then in your sql you need to use the LOWER function.
name=LOWER($login_slapyvardis)
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.
I have a signup page on my website where a user must provide a email address and password only.
I want to be able to create a username for this user automatically by using the first part of the email provided;
User supplies gordon#yourdomain.com, i want to make username 'gordon'
I don't need explanation on how to create form or submission of data to database, just the code to extract data from email provided, and if necessary, if duplicate occurs add number to end.
Hope this makes sense, seems like a basic function but couldn't find examples of it anywhere on net!
This is not a good idea, just use their full email address. The following email addresses could be different people, but they will become the same under your system.
samename#gmail.com
samename#yahoo.com
Adding a number to the end will make the user remember something unique to your system and cause much confusion on their end.
Agreed, you're stripping a necessarily unique ID into a non-unique ID. Unless you want to add some sort of handling to add a number to the username or something. If that's what you really want to do, this should set $username to the stuff before the email address:
<?php
$username = preg_replace('/([^#]*).*/', '$1', $email);
?>
Something like:
$username = left($email, stripos($email, '#'));
should do. You may want to learn regular expressions for these kinds of task.
Then you add the counter:
function countOccurrences($name)
{
$con = mysql_connect(___, ___, ___);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(___, $con);
$result = mysql_query("
SELECT COUNT(*) AS countOccurrences
FROM users
WHERE username LIKE '" . mysql_real_escape_string($name, $con) . "%'
");
$row = mysql_fetch_array($result);
$number = $row['countOccurrences'];
mysql_close($con);
return $number;
}
and then:
$countUsers = countOccurrences($username);
if ($countUsers>0)
{
$username = $username . $countUsers;
}
IMPORTANT: Consider using the whole email as username: you don't want gordon#flash.net to be considered equal to gordon#clash.com
NOTE: example code counts gordon, gordon1, gordon2 but gordonbah, gordonq, gordonxxx too
NOTE: this is pretty rough, and should not be considered best PHP practice; it's just to give the general idea
$username = gordon#example.com;
$username_arr = explode('#',$username);
$username = $username_arr[0];
if( !is_taken( $username ) )
{
//The name is not taken.
}
else
{
//The name is taken, add numbers and do the search again.
}
function is_taken( $username )
{
$db_link = mysql_connect($host,$user,$pass) or die('Could not connect to database');
$username = mysql_real_escape_string( $username );
$sql = "SELECT * FROM `database`.`users` WHERE `username` = '$username'";
$res = mysql_query( $sql , $db_link );
return mysql_num_rows( $res ) == 1;
}
<?php
preg_match('/[^#]+)#/',$email,$matches);
$username = $matches[1];
check_availability($username);
?>
Should suit your needs :D
$username = substr($username, 0, strpos($username, '#'));
$username = mysql_real_escape_string($username);
$result = mysql_query('SELECT `username` FROM `users` WHERE `username` = \'' . $username . '%\';');
if (mysql_num_rows($result) > 0) {
$i = 0;
while ($name_arr = mysql_fetch_assoc($result)) {
$name = $name_arr['username'];
$after = substr($name, strlen($username));
if (ctype_digit($after)) {
if (($after = (int) $after) > $i) {
$i = $after;
}
}
}
if ($i > 0) {
$username .= $i;
}
}
As of PHP 5.3.0 you can also use:
$email = 'test#stackoverflow.com';
$user = strstr($email, '#', true);
This will return all the string from the beginning to the first occurrence of '#'. Which in this case is:
test
I use something like this,
$cust_email = "test#gmail.com";
$parts = explode("#", $cust_email);
$cust_name = $parts[0];
I use to set default User Name if user do not set his / her name in the profile.
You can use strstr function to find specific word from string
<?php
$username = strstr("username#domain.com",'#',true); //get text before #
/*
echo strstr("username#domain.com","#"); // get text after #
*/
check_availability($username);
?>