can users trigger javascript: function from URL? - php

i have a function that calls javascript:del_release_comment(10,12); from the page, if the user has that particular comment.
I wonder if other users can trigger from the URL bar or somehow else this function to delete comments that aren't their.
10 is the news_id and 12 is the comment_news_id, the id of the comment on that particular news.
THe delete is done via AJAX calling a PHP script that does delete on these 2 parameters.
If the javascript function can be called by hand i'd have to re-enforce the little PHP script that deletes the comment. Also, is it possible to call that particular PHP script by name in the URL directly ? It uses _POST vars, not GET.
Thanks.
code for deleting the comment :
$query_del_comment = "DELETE from myl_news_comments WHERE comment_id='".mysql_real_escape_string($_POST['comment_news_id'])."' AND news_id='".mysql_real_escape_string($_POST['news_id'])."'";
$result_del_comment = mysql_query($query_del_comment) or die('Query failed: ' . mysql_error());

Clients can execute any HTTP request they like using a variety of techniques (including calling your JavaScript functions, or building it manually).
You must perform authentication / authorisation on the server to ensure that the request to delete something is from someone authorised to delete that something.

Related

Avoid changing values in console

How can I avoid that users changing the values in the console. As example my link is:
example.com/delete.php?id=8. When I'm open my console and I change the 8 to 10 then row 10 is deleted.
How can I avoid this? Or by which way I can do it instead of the URL?
The security of an application must never be only on the client side.
You must always consider that URIs called on the client side can be called not just via a form.
If your interface offers a short list of choices, the webservice or server script must check the same reduced choice list before before any other treatment.
You can use a <form method=post action=delete.php ><button type=submit value=8 name=id>delete</button></form> and then, in the PHP, use $_POST['id'] instead of $_GET['id'].
You can also use $_SESSIONs to see if the user is logged in and if he is allowed to delete that id; For instance, when delivering the page set something as $_SESSION['allow_id'] = 8 and then, on the PHP side, you could do something as:
if ((!empty($_SESSION['allow_id'])) && (!empty($_POST)) && ($_SESSION['allow_id'] == $_POST['id'])) { // allow the deletion } else { // don't allow }

Update table value on page view?

I am trying to create a PHP trigger for when a user views certain pages on my website it will update the user table in the points section.
I understand the process would work something like this
on page view > update user > where user id is (**get username from session**) > add 5 to points row
Anyone have any idea how to set up something simple like this for giving users simple points for viewing pages?
My site is using PHP and mySQL for the database.
Use cookies or session variables to keep track of the user details like the username or ID. So making a pageview trigger would be as easy as adding a mysql query at the top of every page which would update the database table for views. Kinda the same way that forums operate.
E.g
<?php
session_start();
$db_connection = mysqli_connect('host','username','password','db');
$user_id = $_SESSION['userid']; //That is asssuming that you had gotten the user id on login
mysqli_query($db_connection, 'UPDATE page_views SET views_column=views_column+1 WHERE userid=$user_id');
?>
Yes, you could do something like (if you own the page the user has to visit):
<?php
$pointsForThisSite = 5;
include "points_adder.php";
?>
While Points_adder looks whether $pointsForThisSite is defined and > 0, then adds the Points to the database as you descripbed.
Is that what you are looking for?
Create a php function and call it everytime the user enter the page.
You don't need a mysql trigger because, the action is at the webpage.
function add_points($user, $page){
//If users visits too many maybe you don't want to gave him some points.
//add points
}
and invoke the function in that pages you want to score
The most unobtrusive way to do this is with an AJAX call after the page has loaded. The call should be to an include file that performs the database update operation and returns a 204 response so that the visitor's browser doesn't wait for response content.
For an Apache server;
header('HTTP/1.0 204 No Content');
header('Content-Length: 0', true);
header('Content-Type: text/html', true);
flush();
// do the table update here

Looking to connect back with the server upon exit. Any form of Javascript / jQuery / AJAX trap out there I can set?

First things first. I'm running CodeIgniter on a PHP/MySQL site.
I've been tasked with creating a "shell" application for a series of movies that a person can view for a training website that I'm building. The idea here is that a person would be able to log on to a page, click "Take Course" and have it log what time the course was taken. Then, when the person exits the page carrying the movie, I would be able to record what time the course was ended. This way I can compare the start and end times, and determine if the user had viewed most of the film in order to give the user credit. Well, the first part is easy. First, I've built a table in my database with the following fields:
intKey (intKey(10))
strHash (varchar(255))
dtBegan (datetime)
dtEnded (datetime)
varIpAddress (varchar(255))
I've put in a controller that does this:
$ip_address = $_SERVER['REMOTE_ADDR'];
$data['hash'] = md5(time() . "Proof of Concept!");
$this->db->query("INSERT INTO pocTime SET strHash = '" . $data['hash'] . "', dtBegan = now(), varIpAddress='$ip_address'");
$this->load->view('welcome_message',$data);
OK... easy enough, yes? I also know that when I am done, I want to launch a file that does this:
$ip_address = $_SERVER['REMOTE_ADDR'];
$this->db->query("UPDATE pocTime SET dtEnded = now() WHERE strHash = '" . $data['hash'] . "' AND varIpAddress='$ip_address'");
What I'm hoping to do is have a page that is called by the 1st block of code, and set a "trap" so to speak so that the 2nd block of code is run by some kind of "post back" if the rendered page is closed. Any suggestions? I know that I could put some sort of big "CLICK HERE TO END YOUR VIDEO" type button that would cover this, but I'm looking to run code on some form of exit from a page, because I don't know what the user would do after viewing the video. Any thoughts?
Simple but should work, using jQuery
$(window).unload(function(){
$.get("test.php?dim1=turn&dim2=off");
});
Using unload which jQuery documentation tells what triggers this:
http://api.jquery.com/unload/
Using get which jQuery documentation is here:
http://api.jquery.com/get/
Or you can use post as well
$(window).unload(function(){
$.post("test.php", { dim1: "turn", dim2: "off" } );
});
http://api.jquery.com/jQuery.post/
You are looking for jQuery's unload event.
I would also recommend that you use Codeigniter's Active Record Syntax in your database queries. Not only does it make writing INSERT and UPDATE queries much easier, it will also escape and sanitize your input to protect you from SQL injection.

login to php website using RCurl

I would like to access with R to the content of a php website
http://centralgreen.com.sg/login.php?login=9-1501&password=mypassword
I have passed an example of login + password in the url, but I don't know how to press the login button through the url.
I would like to use the R package RCurl if possible.
The form submits by post - you are using a get request at the moment by the looks of things, you need to use post.
My guess is that rcurl is based on curl - and I know curl can do this, so should be possible.
recently I've been having the same problem. In my case I solved it like this, using RCurl package (with a POST request).
In this code two requests are done one after the other. The fist one, is in order to gain a session cookie (start session in the server). The application I was calling expected the session to be started by the time it checked the login credentials (this won't happen if you send the form upfront). Otherwise some warning about not having cookie support was raised. This might be the case of the asker (though it was time ago)... or someone else's.
login <- function (xxxx_user, xxxx_pass) {
url_login <- 'http://centralgreen.com.sg/login.php'
curlhand <- getCurlHandle()
curlSetOpt(
.opts = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")),
cookiefile = "cookies.txt",
useragent = 'YOUR R-PACKAGE NAME',
followlocation = TRUE,
# might need this in case the server checks for the referer..
httpheader = "Referer: http://centralgreen.com.sg",
curl = curlhand)
# (1) first call to initializate session. you get the session cookie
getURL(url_login, curl = curlhand)
params<- list( login = xxxx_user, password = xxxx_pass )
# might need to add some other hidden form param in case there are..
# (2) second call, sends the form, along with a session cookie
html = postForm(url_login,
.params = params,
curl = curlhand,
style="POST")
# ... perform some grep logic with 'html' to find out weather you are connected
}
# you call the function...
login("yourusername", "yourpass")
The 'perform some grep logic' note takes care of the fact that since you are targeting a system not designed for this kind of programatical log in, it's not going to give you any nice hint on the result of the attempt ... so you might need to parse the raw html string you receive against some key sentences (eg: 'wrong username or password' ...)
hope it helps

Curing the "Back Button Blues"

Ever stumbled on a tutorial that you feel is of great value but not quite explained properly? That's my dilemma. I know THIS TUTORIAL has some value but I just can't get it.
Where do you call each function?
Which function should be called
first and which next, and which
third?
Will all functions be called in all files in an application?
Does anyone know of a better way cure the "Back Button Blues"?
I'm wondering if this will stir some good conversation that includes the author of the article. The part I'm particularly interested in is controlling the back button in order to prevent form duplicate entries into a database when the back button is pressed. Basically, you want to control the back button by calling the following three functions during the execution of the scripts in your application. In what order exactly to call the functions (see questions above) is not clear from the tutorial.
All forwards movement is performed by
using my scriptNext function. This is
called within the current script in
order to activate the new script.
function scriptNext($script_id)
// proceed forwards to a new script
{
if (empty($script_id)) {
trigger_error("script id is not defined", E_USER_ERROR);
} // if
// get list of screens used in this session
$page_stack = $_SESSION['page_stack'];
if (in_array($script_id, $page_stack)) {
// remove this item and any following items from the stack array
do {
$last = array_pop($page_stack);
} while ($last != $script_id);
} // if
// add next script to end of array and update session data
$page_stack[] = $script_id;
$_SESSION['page_stack'] = $page_stack;
// now pass control to the designated script
$location = 'http://' .$_SERVER['HTTP_HOST'] .$script_id;
header('Location: ' .$location);
exit;
} // scriptNext
When any script has finished its
processing it terminates by calling my
scriptPrevious function. This will
drop the current script from the end
of the stack array and reactivate the
previous script in the array.
function scriptPrevious()
// go back to the previous script (as defined in PAGE_STACK)
{
// get id of current script
$script_id = $_SERVER['PHP_SELF'];
// get list of screens used in this session
$page_stack = $_SESSION['page_stack'];
if (in_array($script_id, $page_stack)) {
// remove this item and any following items from the stack array
do {
$last = array_pop($page_stack);
} while ($last != $script_id);
// update session data
$_SESSION['page_stack'] = $page_stack;
} // if
if (count($page_stack) > 0) {
$previous = array_pop($page_stack);
// reactivate previous script
$location = 'http://' .$_SERVER['HTTP_HOST'] .$previous;
} else {
// no previous scripts, so terminate session
session_unset();
session_destroy();
// revert to default start page
$location = 'http://' .$_SERVER['HTTP_HOST'] .'/index.php';
} // if
header('Location: ' .$location);
exit;
} // scriptPrevious
Whenever a script is activated, which
can be either through the scriptNext
or scriptPrevious functions, or
because of the BACK button in the
browser, it will call the following
function to verify that it is the
current script according to the
contents of the program stack and take
appropriate action if it is not.
function initSession()
// initialise session data
{
// get program stack
if (isset($_SESSION['page_stack'])) {
// use existing stack
$page_stack = $_SESSION['page_stack'];
} else {
// create new stack which starts with current script
$page_stack[] = $_SERVER['PHP_SELF'];
$_SESSION['page_stack'] = $page_stack;
} // if
// check that this script is at the end of the current stack
$actual = $_SERVER['PHP_SELF'];
$expected = $page_stack[count($page_stack)-1];
if ($expected != $actual) {
if (in_array($actual, $page_stack)) {// script is within current stack, so remove anything which follows
while ($page_stack[count($page_stack)-1] != $actual ) {
$null = array_pop($page_stack);
} // while
$_SESSION['page_stack'] = $page_stack;
} // if
// set script id to last entry in program stack
$actual = $page_stack[count($page_stack)-1];
$location = 'http://' .$_SERVER['HTTP_HOST'] .$actual;
header('Location: ' .$location);
exit;
} // if
... // continue processing
} // initSession
The action taken depends on whether
the current script exists within the
program stack or not. There are three
possibilities:
The current script is not in the $page_stack array, in which case it is
not allowed to continue. Instead it is
replaced by the script which is at the
end of the array.
The current script is in the
$page_stack array, but it is not the
last entry. In this case all
following entries in the array are
removed.
The current script is the last entry
in the $page_stack array. This is
the expected situation. Drinks all
round!
That is a good discussion but more to the point you should be looking into Post Redirect Get (PRG) also known as "Get after Post."
http://www.theserverside.com/patterns/thread.tss?thread_id=20936
If you do not understand my article then you should take a close look at figure 1 which depicts a typical scenario where a user passes through a series of screens – logon, menu, list, search, add and update. When I describe a movement of FORWARDS I mean that the current screen is suspended while a new screen is activated. This happens when the user presses a link in the current screen. When I describe a movement as BACKWARDS I mean that the user terminates the current screen (by pressing the QUIT or SUBMIT button) and returns to the previous screen, which resumes processing from where it left off. This may include incorporating any changes made in the screen which has just been terminated.
This is where maintaining a page stack which is independent of the browser history is crucial – the page stack is maintained by the application and is used to verify all requests. These may be valid as far as the browser is concerned, but may be identified by the application as invalid and dealt with accordingly.
The page stack is maintained by two functions:
scriptNext() is used to process a
FORWARDS movement, which adds a new
entry at the end of the stack and
activates the new entry.
scriptPrevious() is used to process
a BACKWARDS movement, which removes
the last entry from the stack and
re-activates the previous entry.
Now take the situation in the example where the user has navigated to page 4 of the LIST screen, gone into the ADD screen, then returned to page 5 of the LIST screen. The last action in the ADD screen was to press the SUBMIT button which used the POST method to send details to the server which were added to the database, after which it terminated automatically and returned to the LIST screen.
If you therefore press the BACK button while in page 5 of the LIST screen the browser history will generate a request for the last action on the ADD screen, which was a POST. This is a valid request as far as the browser is concerned, but is not as far as the application is concerned. How can the application decide that the request is invalid? By checking with its page stack. When the ADD screen was terminated its entry was deleted from the page stack, therefore any request for a screen which is not in the page stack can always be treated as invalid. In this case the invalid request can be redirected to the last entry in the stack.
The answers to your questions should therefore be obvious:
Q: Where do you call each function?
A: You call the scriptNext()
function when the user chooses to
navigate forwards to a new screen,
and call the scriptPrevious()
function when the user terminates
the current screen.
Q: Which function should be called
first and which next, and which
third?
A: Each function is called in
response to an action chosen by the
user, so only one function is used
at a time.
Q: Will all functions be called in
all files in an application?
A: All functions should be available
in all files in an application, but
only called when chosen by the user.
It you wish to see these ideas in action then you can download my sample application.
The part I'm particularly interested in is controlling the back button in order to prevent form duplicate entries into a database when the back button is pressed.
Your premise is wrong. There is no such thing as "Back Button Blues", if you design your application as a web application. If you design your application without any server side state, you will never run into this problem in the first case. This minimalistic approach to web applications works remarkably well, and is usually known as REST.
# troelskn
If you design your application without any server side state ....
It is not possible to design an effective application which does not have state, otherwise all you have is a collection of individual pages which do not communicate with each other. As maintaining state on the client is fraught with issues there is no effective alternative but to maintain state on the server.
#Marston.
I solved the problem with post/redirect/get but I believe the tutorial has some merit and perhaps Tony Marston can elaborate on it. And how it could be used to solve not necessarily my particular problem but perhaps something similar. Or how is it better than post/redirect/get if the functions can in fact be used in solving my particular problem. I think this will be a good addition to the community here.
if ($_POST) {
process_input($_POST);
header("Location: $_SERVER[HTTP_REFERER]");
exit;
}

Categories