php not working when user click in BACK bottom in browser - php

I have a problem and I don't know if anyone has a solution...
I have an online.php script that gets user ip and data and write it on mysql:
$browser = $_SERVER['HTTP_USER_AGENT'];
$root = $_SERVER['DOCUMENT_ROOT'];
include_once ("$root/config.php");
$ip = $_SERVER['REMOTE_ADDR'];
...
$sb4154 = $on124->num_rows;
if ($sb4154 == 0) {
$url=#$_SERVER['HTTP_REFERER'];
$ihghg = $mysqli_link->prepare("INSERT INTO online (ip, hora, browser) VALUES (?,now(),?)");
$ihghg->bind_param('ss', $ip, $browser);
$ihghg->execute();
$ihghg->close();
}
else {
$ihghg = $mysqli_link->prepare("UPDATE online SET `hora` = now() WHERE `ip` = ? LIMIT 1");
$ihghg->bind_param('s', $ip);
$ihghg->execute();
$ihghg->close();
}
it is basically that. (I use ... to sum up).
My php, when you click in a link it opens the image:
<a href="image.jpg">
So the user needs to click back in the browser to see more pictures. The problem is here, when user click back, this include online.php script not work, the UPDATE time not set the hour.
Why it is not working when user click back in browser?

Related

Sessions are not working when the site is called by an iframe

I have a first site https://www.mydomain1.com in which I use PHP sessions. No problem, everything works fine, when I go from page to page, I can access my session variables.
I have a second site https://www.mydomain1.com in which I display part of my 1st site via an iframe:
<iframe src = "https://www.mydomain1.com" width = "100%" frameborder = "0" style = "border: 0" allowfullscreen = "allowfullscreen" id = "frameLeonard"> </iframe>
And there strangely, the session variables are no longer recognized. I'm not even trying to get my 1st site to access the session variables from the 2nd site (that's not the goal and it's normal that it doesn't work) but just run the 2nd site inside the 1st site.
Strangely, it was still working a year ago.
Has there been any upgrade that would explain the problem?
Thank you in advance for your lights !
Now I found the reason, chrome shows this behaviour. With version 80 (Feb. 2020) it has it's "SameSite by default cookies" enabled as default, which means that including external pages (different domain) inside an iframe, will kill their sessions.
For preventing this, you can disable "SameSite by default cookies" in chrome://flags
Beware: This might be a security issue (but solved my problem for now)
Otherwise - if using PHP 7.3 or newer - you could add one (or both) of the following ini_set() in your PHP before session_start():
ini_set('session.cookie_samesite', 'None');
session_set_cookie_params(['samesite' => 'None']);
Here you get further details:
https://blog.heroku.com/chrome-changes-samesite-cookie#prepare-for-chrome-80-updates
i recommend you use MySQL function for that,
// to add captcha record via img file.
$time = time();
$deltime = time()-1500;
$ip = $_SERVER['REMOTE_ADDR'];
$result = $conn->query("SELECT * FROM `captcha` WHERE `ip` = '" . $ip . "'");
if (($result) && ($result->num_rows >= 1))
{
$conn->query("UPDATE `captcha` SET `captcha` = '".$_SESSION["captcha"]."' WHERE `ip` = '".$ip."'");
}
else
{
$conn->query("DELETE FROM `captcha` WHERE `time` < '".$deltime."'");
$sql = "INSERT INTO `captcha` (captcha, ip, time) VALUES ('".$_SESSION["captcha"]."', '".$ip."', '".$time."')";
if ($conn->query($sql) === TRUE) {
//echo "New record created successfully";
} else {
//echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// on process file to match captcha code
$ip = $_SERVER['REMOTE_ADDR'];
$result = $conn->query("SELECT * FROM `captcha` WHERE `ip` = '" . $ip . "'");
while ($row = $result->fetch_assoc())
{
$captcha = $row['captcha'];
}
if ($captcha == $_POST["access_token"]) { /* do anything */ }
Having the same problem here, but no solution yet.
I made several tests. Seems only to occur, when iFrame loaded content is SSL certificated. If not, it works perfect.
Maybe this is helpful. Or did you get any solution yet?

Tracking number of clicks on a link - php

I have made a tracking website in php which tracks number of clicks on a specific link - for affiliate links tracking. what I am doing is:
When a user clicks a link provided by my website, he goes to my website which after recording its ip address redirects the user to another address mapped to the link user clicked. A counter increments the number of click after validating ip.
The problem I am facing is that when i compare the number of clicks in my website and that of facebook results, my result is many times more. I don't know what is the cause of that.
My results:
Facebook results:
My question is that why is there a difference? if facebook has some additional checks does someone know what they are? or are they private? or facebook just reduces the number of clicks?
Help would be really appreciated. I am stuck here.
Here is my code to check the visitors ip and increment the click counter:
<?php
require_once "dbdata.php";
if(isset($_GET['linkid']) && !empty($_GET['linkid'])){
$id = $_GET['linkid']; //getting link id to fetch data from database
$ip = $_SERVER['REMOTE_ADDR']; // getting visitors ip address
//database connection
#$db = new mysqli(hostname,username,password,dbname) or die(json_encode(array("status"=>"Can not connect (Database Connection Error)")));
//getting data from table
$query = "select * from links_shared where id = $id ;";
$result_link = $db -> query($query) or die(json_encode(array("status"=>"Error Fetching previous income data")));
$row_link = $result_link-> fetch_assoc();
$link = $row_link['orignal']; //the link to be redirect the user to
header("Location:".$link); //redirected
if($row_link['status'] == "live"){ //status of link should be live
$array_ip = explode(",", $row_link['ip']); //comma sepearted string of ips to array
if(!in_array($ip, $array_ip)){ //check if ip is not already present
$query = "select * from links_deleted where url = '$link' ;"; //getting block list
$result_del = $db -> query($query) or die(json_encode(array("status"=>"Can not select deleted")));
if($result_del -> num_rows <1){ //check if link not in block list
$concat = ",".$ip;
echo $query = "update links_shared set clicks = (clicks + 1), ip = concat(ip,'$concat') where id= $id; ";
$result_update = $db -> query($query) or die(json_encode(array("status"=>"can not update clicks")));
}
}
}
}
?>
Either facebook is invalidating clicks that your script accepts (eg: untrusted IPs, repeated IPs, automatic bot detection...) or more simply facebook only sees clicks from its platform but your script receives all clicks from everywhere.
Of course there could also be a problem with your script itself, but since you don't show it, I can't address that.

Prevent script from running again in php

I have a script to give a unique download link. Below:
The problem is when i refresh the page it generates another link.
i tried header but i want to:
Show the unique download link
If refresh page, redirect or echo 'Only one download per IP!
Something like that.
The code is
<?php
//connect to the DB
$resDB = mysql_connect("sql213.byethost10.com", "user", "pass");
mysql_select_db("Nice try", $resDB);
function createKey()
{
//create a random key
$strKey = md5(microtime());
//check to make sure this key isnt already in use
$resCheck = mysql_query("SELECT count(*) FROM downloads WHERE downloadkey = '{$strKey}' LIMIT 1");
$arrCheck = mysql_fetch_assoc($resCheck);
if ($arrCheck['count(*)']){
//key already in use
return createKey();
} else {
//key is OK
return $strKey;
}
}
//get a unique download key
$strKey = createKey();
//insert the download record into the database
mysql_query("INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', 'fernanfloo-OMG.zip', '".(time()+(60*60*24*7))."')");
?>
<html>
<head>
<title>Descargar Fernanfloo OMG sonido</title>
</head>
<h1>By Skyleter</h1>
<p>Su link de descarga es:</p>
<strong>download.php?key=<?=$strKey;?></strong>
<p>Link caduca en 7 días..</p>
</html>
PS: header worked but as i said, i want to show the unique download link, and ONLY IF THE USER REFRESH PAGE, redirect. (and everytime redirect to a page)
<?php
//Get client ip.
$ip = "203.146.92.56";
$d = file_get_contents("ips.txt");
$d = explode(",",$d);
if(in_array($ip,$d))
{
echo "Only one download per ip";
}
else
{
//display download link
fwrite(fopen('ips.txt','a'),$ip.",");
}
ip.txt would look like this
203.146.92.56,117.56.34.21,
Note that, this just a basic way of doing what you need. You could tweak this a lot. Say, individual files for individual users so you can clear logs for X ip every X period of time and so on. Maybe even different logs for different files.
I think you need to investigate controlling sessions for your connecting clients.
The session parameter will be able to be used to prevent new keys being generated.

mysql inserting values: echoing $profile_id from link one through til mysql function?

There's basically pictures on my users profile page that people need permission to see.
I'm basically getting the user to click one link to open a jQuery window and then from within that jQuery window the user needs to click another link and this runs the mysql function and is suppose to insert the user_id which is the users $_session['user_id'] into the table 'ptb_permissions' and the profile id of the user whose pictures that user is trying to see.
So this means the users $profile_id needs to be inserted into 'private_id.
At the moment though only the user_id is being inserted. can someone please show me where I'm going wrong I think I'm loosing the echo at the first link, I don't think I've written the code write here:
<?php
$photo = "data/private_photos/0/_default.jpg";
if (!file_exists($photo)) {
$photo = "data/photos/0/_default.jpg";
}
$thumb = "data/private_photos/0/_default.jpg";
if (!file_exists($thumb)) {
$thumb = "data/photos/0/_default.jpg";
}
echo
"<li><img src=\"$thumb\" width=\"90\" height=\"90\" alt=\"<strong>{$profile[2]}'s Photos</strong>\" /></li>";
?>
after this link is clicked this then opens up a jquery window and the user needs to click:
Let Me See
then i run my function:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
require_once("includes/session.php");
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
session_start();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$sql = "INSERT INTO ptb_permissions (id, user_id, private_id) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\"><strong>Your message has successfully been sent.</strong></div>";
?>
I don't know, but the link syntax is not correct:
request_priv_pix.php?to=?to=...
May be:
request_priv_pix.php?to=...
Looks like you may have a typo in second link?
href="request_priv_pix.php?to=?to="

Help with php blank page?

I run a fantasy basketball league. My php website/sql database is designed to let the person running the team do everything through the website - they can waive a player, and the player automatically goes into the FA pool, etc.
Everything has worked perfectly until about a week ago. Anytime now that a team goes to sign a player, after clicking "Sign", they get a blank PHP page. I have no idea why - I have made no adjustments to any files. It just started happening. Below is the code for the blank PHP page - can someone help?
<?php
$username = "me";
$password = "mypassword";
$database = "mydatabase";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$Team_Offering = $_POST['Team_Name'];
$Fields_Counter = $_POST['counterfields'];
$Roster_Slots = $_POST['rosterslots'];
$Healthy_Roster_Slots = $_POST['healthyrosterslots'];
$Type_Of_Action = $_POST['Action'];
$queryt="SELECT * FROM nuke_ibl_team_info WHERE team_name = '$Team_Offering' ";
$resultt=mysql_query($queryt);
$teamid=mysql_result($resultt,0,"teamid");
$Timestamp = intval(time());
// ADD TEAM TOTAL SALARY FOR THIS YEAR
$querysalary="SELECT * FROM nuke_iblplyr WHERE teamname = '$Team_Offering' AND retired = 0 ";
$results=mysql_query($querysalary);
$num=mysql_numrows($results);
$z=0;
while($z < $num)
{
$cy=mysql_result($results,$z,"cy");
$cyy = "cy$cy";
$cy2=mysql_result($results,$z,"$cyy");
$TotalSalary = $TotalSalary + $cy2;
$z++;
}
//ENT TEAM TOTAL SALARY FOR THIS YEAR
$k=0;
$Salary=0;
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
if ($Check == "on")
{
if ($Type_Of_Action == "drop")
{
if ($Roster_Slots < 4 and $TotalSalary > 7000)
{
echo "You have 12 players and are over $70 mill hard cap. Therefore you can't drop a player! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
}else{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '1000', `droptime` = '$Timestamp' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$topicid=32;
$storytitle=$Team_Offering." make waiver cuts";
$hometext="The ".$Team_Offering." cut ".$playername." to waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
} else {
if ($players_team == $teamid)
{
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
} else {
if ($Healthy_Roster_Slots < 4 and $TotalSalary + $Salary > 7000)
{
echo "You have 12 or more healthy players and this signing will put you over $70. Therefore you can not make this signing. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots > 3 and $TotalSalary + $Salary > 7000 and $Salary > 103) {
echo "You are over the hard cap and therefore can only sign players who are making veteran minimum contract! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} elseif ($Healthy_Roster_Slots < 1) {
echo "You have full roster of 15 players. You can't sign another player at this time! <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.";
} else {
$queryi = "UPDATE nuke_iblplyr SET `ordinal` = '800', `bird` = '0', `cy` = '1', `cy1` = '$Salary', `teamname` = '$Team_Offering', `tid` = '$teamid' WHERE `pid` = '$Index' LIMIT 1;";
$resulti=mysql_query($queryi);
$Roster_Slots++;
$topicid=33;
$storytitle=$Team_Offering." make waiver additions";
$hometext="The ".$Team_Offering." sign ".$playername." from waivers.";
// ==== PUT ANNOUNCEMENT INTO DATABASE ON NEWS PAGE
$timestamp=date('Y-m-d H:i:s',time());
$querycat="SELECT * FROM nuke_stories_cat WHERE title = 'Waiver Pool Moves'";
$resultcat=mysql_query($querycat);
$WPMoves=mysql_result($resultcat,0,"counter");
$catid=mysql_result($resultcat,0,"catid");
$WPMoves=$WPMoves+1;
$querycat2="UPDATE nuke_stories_cat SET counter = $WPMoves WHERE title = 'Waiver Pool Moves'";
$resultcat2=mysql_query($querycat2);
$querystor="INSERT INTO nuke_stories (catid,aid,title,time,hometext,topic,informant,counter,alanguage) VALUES ('$catid','Associated Press','$storytitle','$timestamp','$hometext','$topicid','Associated Press','0','english')";
$resultstor=mysql_query($querystor);
echo "<html><head><title>Waiver Processing</title>
</head>
<body>
Your waiver moves should now be processed. <br>You will be automatically redirected to the main IBL page in a moment. If you are not redirected, click the link.
</body></html>";
}
}
}
}
$k++;
}
?>
Put the following right after the open PHP tag:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
If this doesn't work, there is a probably a parse error and then you'll need to check the error log.
You will also need to escape your values that you are putting in the queries. This maybe causing a MySQL query to fail. If someone puts a " in $_POST['Team_Name'] your first query may fail.
Another final possible problem: are you sure it can still connect to MySQL?
An option to find the problem is commenting out large portions of code and then piece by piece uncommenting sectons.
Edit: So your first problem is the mysql_connect line. It needs to be changed to, notice the quotes: mysql_connect('localhost',$username,$password); Also, the variable $result and $queryt are spelt wrong in this line and used in their correct spelling: $resultt=mysql_query($queryt); I haven't checked the rest, but there maybe other errors that will cause your script to break. Some of the errors list are important to fix, but won't break your script.
Escaping: Check out the following page: http://php.net/manual/en/function.mysql-escape-string.php This basically prevents people from deleting your entire database.
Check the sample code on this page to find out how to connect to MySQL and check to see if you are connected.
Another suggestion: Are you sure none of your queries are failing? You probably want to check if the result from query is false before continuing, like:
if ($resultcat2 === false) {
trigger_error('query failed ' . $sql, E_USER_ERROR);
echo 'Sorry, there was a problem processing your request. Please try again later.';
exit;
}
Turn error reporting on for PHP in your php.ini file and see if any errors or warnings are reported. Also try removing the trailing whitespace at the end of the file before the last ?>, this has caused problems for me in the past.
Added comments to some of the above responses. Please try to dumb down for me as much as possible - I'm extremely new to this. I can't figure out why it would suddenly stop working, though, when I've made no changes at all to the code.
If you made no changes to any files and it just "broke" then that would indicate that either your webhost went thru a configuration change, your database got hosed somehow, or that someone else may've changed something.
To help spot the culprit, after every one of these
if{
else{
while{
or/and after every few statements (statements end with a semicolon ;) add this to the next line
print "<br> made it to this label: some_unique_label_name_here";
Where you should replace the label each time to help you trace the code.
This will be your first step into debugging the script to figure out how far the code execution is reaching.
Without going through your code in too much detail,I would suggest you look for any sections that may loop for a long time,without returning
After enabling error reporting, make sure to put in else statements that correspond with all of your if-statements so you can determine if those statements are being triggered or not. Throw in some echos.
Also, to clarify - I have probably three dozen PHP files on the site - this is the ONLY one that has stopped working.
As an aside, you should change every variable from a get or post such as:
$Team_Offering = $_POST['Team_Name'];
to
$Team_Offering = mysql_real_escape_string($_POST['Team_Name']);
before using it in a mysql query, otherwise you are vunerable to SQL injection attacks.
This is where I got...everything below the print line wouldn't show up if I put the print line below it.
$k=0;
$Salary=0;
print "<br> made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
So an update...nothing. lol
If you review this code:
$k=0;
$Salary=0;
print " made it to this label: some_unique_label_name_here";
while ($k < $Fields_Counter)
{
$Type=$_POST['type'.$k];
$Salary=$_POST['cy'.$k];
$Index=$_POST['index'.$k];
$Check=$_POST['check'.$k];
$queryn="SELECT * FROM nuke_iblplyr WHERE pid = '$Index' ";
$resultn=mysql_query($queryn);
$playername=mysql_result($resultn,0,"name");
$players_team=mysql_result($resultn,0,"tid");
If I put the print statement below while, the page goes blank and it doesn't show up. If the print statement is before while, the statement shows up but there's no action made on the page. The end result is that when running this page, the player selected on the previous page should be removed from Free Agents, added to the user's team, and a story should be posted on the front page announcing it. Obviously none of those are happening here.

Categories