Hello, I have some questions about how to protect this script from a straight url?
Members can just can go 'pages/map/hospital.php?status=healed' and voila, they don't need any wait time. How do I fix this?!
<?php
$status = $_GET['status'];
if(isset($status)){
session_start();
include('../../includes/core/member.php');
include('../../includes/core/config.php');
$member_id = $_SESSION['member_id'];
if($status == 'healed'){
mysql_query("UPDATE `members` SET `now_health` = '".$m_max_health."' WHERE `member_id` = '".$member_id."'");
}
}else{
include('includes/core/member.php');
}
$health = $m_max_health - $m_now_health;
$wait_time = $health * 5;
?>
<p id='health'>Healing (<?=$wait_time?>)</p>
<script>
$('#health').one('click', function() {
var count = <?=$wait_time?>;
countdown = setInterval(function(){
$("p#health").html(count + " seconds remaining!");
if (count == 0) {
$.ajax({
url: 'pages/map/hospital.php?status=healed',
success: function(data) {
clearInterval(countdown);
$("p#health").html('you have healed');
}
});
}
count--;
}, 1000);
});
</script>
Server-side validation is required.
I see that you already have the initial $wait_time in a variable. So you would want to leverage this and perform some basic math using a datetime function to ensure the count <= 0.
Related
I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php
I have 2 files:
1. chat.php: contain chat messages.
2. loadSingle.php: grab last new message every 1 second.
When I get the last message it was always return and get the last one. I want to get the last message without duplicate every time.
chat.php:
function loadlastmsg(){
var fromIdl = "<?php echo $chat_from_id;?>";
$.ajax({
type:'POST',
url:'loadSingle.php',
data:{fromIdl: fromIdl,},
cache: false,
beforeSend:function(data){
},
success: function(data)
{
$('#mainmsgs').append(data);
}
});
}
setInterval(function(){
loadlastmsg();
}, 1000);
</script>
Load Last Message
loadSingle.php:
<?php
if(isset($_POST["fromIdl"], $_POST["fromIdl"]))
{
$chat_from_ids = $_POST["fromIdl"];
require_once 'config/config.php';
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query("SELECT * FROM chat WHERE id = (SELECT MAX(id) FROM chat WHERE to_id=$userId AND from_id=$chat_from_ids OR to_id=$chat_from_ids AND from_id=$userId) ORDER BY chat.send_date DESC LIMIT 1");
while ($chinbxsx = mysqli_fetch_assoc($result)) {
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if($from_id != $userId){
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}else{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
// if($get_date > $get_date){
echo "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
// }
}
$conn->close();
}
?>
The mistake is: get the last message every 1 second. every time without stop it. I want to get the last message one time without loop the last message. thanks.
Using Ajax for chat will have poor performance always. You must consider using Web sockets.
See the below link for a sample
https://phppot.com/php/simple-php-chat-using-websocket/
I can't warranty this will be a fixed code, but it will give you the idea of how to discard a message on the client side if already received:
CLIENT SIDE:
<script>
/* Other code ... */
// Global variable for save the latest message ID.
var _latestMessageID = -1;
$(document).ready(function()
{
// Start getting messages...
setInterval(
function() {loadlastmsg();},
1000
);
});
function loadlastmsg()
{
var fromIdl = "<?php echo $chat_from_id;?>";
var formData = {fromIdl: fromIdl};
$.ajax({
type:'POST',
url:'loadSingle.php',
data: $.param(formData),
cache: false,
success: function(data)
{
if (data && data["ID"] > _latestMessageID)
{
$('#mainmsgs').append(data["message"]);
_latestMessageID = data["ID"];
}
}
});
}
</script>
SERVER SIDE:
<?php
require_once 'config/config.php';
if(isset($_POST["fromIdl"]) && $_POST["fromIdl"])
{
$chat_from_ids = $_POST["fromIdl"];
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query(
"SELECT *
FROM chat
WHERE id = (SELECT MAX(id)
FROM chat
WHERE (to_id=$userId AND from_id=$chat_from_ids)
OR (to_id=$chat_from_ids AND from_id=$userId))
ORDER BY chat.send_date DESC LIMIT 1"
);
// Since the query has LIMIT of 1 this should only loop one time.
while ($chinbxsx = mysqli_fetch_assoc($result))
{
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if ($from_id != $userId)
{
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}
else
{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
$msgID = $chinbxsx['id'];
}
$returnArray = array();
$returnArray["ID"] = $msgID;
$returnArray["message"] = "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
echo json_encode($result);
$conn->close();
}
?>
I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});
Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.
I am wanted to get the id's of all the divs on my page with the class archive and put them in a MySQL query to check and see if the ids are archived in the database.
So basically I am wondering how I can do this: $div = $(this).attr('id');
Then I would throw it into the loop to check:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '$div'");
while ($post = mysql_fetch_assoc($matches))
{
if (mysql_num_rows($matches) > 0)
{
//DO THIS
}
}
UPDATE
I have this code for the AJAX now:
$('div.heriyah').each(function() {
var curID = $(this).attr('id');
$.post("admin/btnCheck.php", { div : curID }, function(data) {
if (data == "yes") {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Add Element</div></div></div><div class=\"clear\"></div></div>');
} else {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Set As Editable Region</div></div></div><div class=\"clear\"></div></div>');
}
});
});
And my PHP:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['div']."'");
if (mysql_num_rows($matches) > 0)
{
echo "yes";
} else {
echo "no";
}
What am I doing wrong?
You cannot throw a javascript variable to PHP script like that. You have to send an ajax request to the page
$div = $(this).attr('id');
$.post("yourquerypage.php", { divid : $div }, function(data) {
// Something to do when the php runs successfully
});
Next, configure your query to get the variable from $_POST()
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['divid']."'");
And of course, you have to take measures for injection.
It's simple syntax error. Remove the condition after the else and you should be fine.
else (data == "yes") { // remove (data == "yes")
// snip
}