Just wondering about a security issue. Right now I'm using the following function to delete movies from my database:
function deleteVideo(video_id){
function mycallbackform(v,m,f){
if(v=="yes"){
$.ajax({
type: "POST",
url: "delete.php?action=video",
data: "video_id=" + video_id,
success: function(html){
if(html == "1"){
//$("#result").html(html);
$("#row_"+video_id).fadeOut("slow");
$("#result").show();
$("#result").html("<div class='notification success png_bg'> <div><?php echo $LANG_video_succesfull_delete; ?> </div></div>");
setTimeout(function(){ $('#result').fadeOut('slow'); }, 5000);
}else{
$("#result").show();
$("#result").html(html);
}
}
});
}
}
$.prompt('Are you sure?',{ buttons: { Ok: 'yes', Cancel: 'no'}, callback: mycallbackform});
}
At the back end the following code is executed:
/*** DELETE data ***/
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("DELETE FROM videos WHERE username=:username AND videos_id=:video_id");
$stmt->bindParam(':username', $currUser);
$stmt->bindParam(':video_id', $video_id);
/*** execute the prepared statement ***/
$stmt->execute();
The username is stored in a session in this case.
Is there any way user A will be able to delete user B data with this code?
I was thinkinig to add a query to check if the current user is the same user who added the video in the database. If not he can't delete the data. But is this necessary or is this code safe enough?
Thanks in advance.
You'd better store a unique user id in the session. What if there are two people with the same username?
Edit: If the username is unique, it is quite safe. It is not possible to change the value of a session variable working the client side, unless you've made a terrible mistake in your PHP code. But if you're sure the session variable is always set correctly, you don't have to worry.
Related
I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.
I'm new to Ajax and PHP in general. So far, I managed to make an Ajax call to my PHP script which fetches data from my database. However, upon testing, I realized that, even if I'm not logged in, I can still access and run the PHP script directly and when that happens, it populates all the data from my table, which I don't want to happen.
Now based on that I see a major security issue where anyone can access and run the script and see user information.
Now I'm not familiar with security and stuff in PHP, kinda new to it. My question is how would I go about to make the script unaccessible directly, or only when the admin is logged in it could be accessible?
I read around that I could check the session, I tried but it didn't work for some reason. So I'll put what I coded below.
Here's the PHP which fetches data, getData.php:
<?php
session_start();
if(isset($_SESSION['id']) && isset($_SESSION['name']) && isset($_SESSION['admin']) && ($_SESSION['admin']==1)){
include_once('config.php');
//Create PDO Object
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//Set Error Handling for PDO
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Query
$sql = "SELECT users.name, users.email, users.admin, stores.admin, stores.name FROM users INNER JOIN stores ON users.id=stores.admin";
//Prepare Statement
$stmt = $con->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch()){
echo '<tr>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>**********</td>';
if($row[2] == 1){
echo '<td>Yes</td>';
}elseif ($row[2] == 0) {
echo '<td>No</td>';
}
echo '</tr>';
}
$con = null;
}
?>
Here's the ajax that does the call to get the data. It's just a snippet, but it's part of a bigger thing(button on click to be precise), myAjax.js:
$.ajax({ //create an ajax request to getData.php
type: "GET",
url: "includes/getData.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#userInfo > tbody").html("<pre>"+response+"</pre>");
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
Finally, this I set the following sessions, when user logs in:
$_SESSION['id']
$_SESSION['name']
$_SESSION['admin']
$_SESSION['admin'] == 1 means the user is an admin. Otherwise it's
not.
Any help is greatly appreciated.
Edit:
Forgot to include what I tried to check the session. I update the PHP.
Thanks
I usually do like this for checking whether the user is loged in or not to display the result or output
use if(!empty($_SESSION['admin'] && $_SESSION['admin']==1 && !empty($_SESSION['name']) && !empty($_SESSION['id']))
using !empty will also check that if the variable is set and has any value or not! using isset shows true even if the value of variable is "null". so It will pass the if conditions argument and show the result.
One More thing:
when you logout you need to unset the session variables using...
<?php
session_destroy();
session_unset();
this technique has worked always with me...thanks
For example I am a user and I want to post a comment and after submitting it and saved to my database. The other page of the admin updates and automatically the data that I inserted displays without refreshing the page of the admin. Help please..
any code can help. Thanks. I'm using php for server-side language. Any language can help javascript or ajax.
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
Somewhere in path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
For more information, please refer to jQuery's post and ajax methods. You can do the same thing without jQuery, but you shouldn't reinvent the wheel.
yourphpfile.php is the php file where you need to do all your database operations (in your case its insert into database).
So,basically you want to show the recently insert data in a webpage without refreshing the page, to do that, we need Ajax.
So, do your insert operation in yourphpfile.php, and if the insert operation is successful, just return the result (inserted data into DB) using echo $output;exit;
where $output = 'recently inserted data';
That's what you need to do in the php side.
Your yourphpfile.php:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
Now in ajax function:
You could use jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
In the reponse variable you would get what you have echoed in the yourphpfile.php.
That is $output. Then you could use the reponse varible inside ajax function and use it to insert into your HTML.
Suppose you have a form and you can use Ajax for sending the data to the backend. The ajax call would look in the following way:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
...and in php you write something as:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}
I need help in this PHP Ajax updating mysql database using PDO. I wanted to update the database if a user checks the checkbox. Below is my code:
JS:
$('input[name=product_new]').click(function(){
var chkbox_id = $(this).attr('alt');
var chkbox_selected = $(this).is(':checked');
if(chkbox_selected == true)
{
chkbox_selected = "checked";
}
else
{
chkbox_selected = "uncheck";
}
$.post({
url: "../products_listing.php",
type: "POST",
data: {product_id: chkbox_id, product_new: chkbox_selected},
cache: false,
success: function(){}
});
});
PHP page with PDO to update database:
$id = $_POST['product_id'];
$product_new = $_POST['product_new'];
if(isset($_POST['product_new']))
{
try
{
$query = "UPDATE productinfo SET new_arrival=? WHERE id=?";
$stmt_new_chkbox = $conn->prepare($query);
$stmt_new_chkbox->bindParam(1, $product_new, PDO::PARAM_STR);
$stmt_new_chkbox->bindParam(2, $id, PDO::PARAM_INT);
$stmt_new_chkbox->execute();
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
It was working when I use mysql but now I've changed it to use PDO, it won't work anymore. I can't find where went wrong. Thanks in advance guys.
Below is the old code from mysql_:
$id = mysql_real_escape_string($_POST['product_id']);
$product_new = mysql_real_escape_string($_POST['product_new']);
if(isset($_POST['product_new']))
{
$upt_new=mysql_query("update products_list set new_arrival='$product_new' where id='$id'");
}
Ok! I know what's wrong already. The damn directory path. I took out ../ and it works! Kinda weird though.
Because my js file is in JS folder and products_listing.php is outside of the js folder. Isn't it supposed to be ../products_listing.php?
Can anyone tell me why it's not working which it is supposed to be?
Thanks in advance guys!
Just split your task into 2 parts: AJAX part and PDO part.
First of all make sure that your PDO part works well. Make a mock $_POST array, and then start playing with PDO calling this script directly, without AJAX. Ask questions here, if something goes wrong. then, as you ret it to work, move to AJAX part, the same way - first, without PDO by just by sending data to server and verifying if it's correct.
Solving 2 problems at once makes things a lot harder. Always split your task into separate parts and solve them one by one.
guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead