How do I stop others from post requesting my php - javascript

I have a page called index.php. This contains a form which the user submits. Upon submission, it verifies the input from verify-input.php and returns some key information back to index.php. From there, index.php post requests scanner.php ~100 times. This is all done without refreshing index.php.
My question is, how do I stop other websites or other people from post requesting verify-input.php and scanner.php? I only want people to be able to call these files on my website (essentially, I don't want others using my verify-input.php and scanner.php API's for their own gain.
I've added the code below for these files, but I don't think it matters too much. I'm fairly good in PHP but I am terrible at javascript.
index.php
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="display-error" style="display: none"></div>
<form>
<label for="fname">Fruit (only correct input is: banana)</label><br>
<input type="text" id="fruit-name" name="fruit" value="banana"><br>
<button type="submit" id="submit" value="Submit">Submit</button>
</form>
<div id="results">
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {
fruitName: fruitName
},
success: function(data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
(async function() {
var fruitID = data.fruitId;
var min = 1;
while (min < 60) {
await scan(fruitID, min, min + 30);
min = min + 30;
}
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
})();
} else {
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
});
});
});
function scan(vFruitId, min, max) {
return $.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {
vFruitId: vFruitId,
min: min,
max: max
},
success: function(data) {
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div><br>
`);
})
}
});
}
</script>
verify-input.php
<?php
if (isset($_POST['fruitName'])) {
echo(is_valid($_POST['fruitName']));
}
function is_valid($fruit) {
// Verify post data is valid and correct
$names = ['Banana cake', 'Banana pancake', 'Banana bread'];
$colors = ['Yellow', 'Blue', 'Green', 'Purple', 'Black'];
sleep(2);
if ($fruit == "banana") {
$result['code'] = 200;
$result['fruitId'] = rand(1, 9999999);
$result['msg'] = "YAY SUCCESS";
$json = json_encode($result);
return $json;
}
$result['code'] = 400;
$result['msg'] = "ERROR! The correct fruit is banana";
$json = json_encode($result);
return $json;
}
scanner.php
<?php
ini_set('max_execution_time', '300');
define('MAX_SCAN', 30);
if (isset($_POST['vFruitId']) &&
isset($_POST['min']) &&
isset($_POST['max'])) {
$result = roomscanner($_POST['vFruitId'], $_POST['min'], $_POST['max']);
$json = json_encode($result);
file_put_contents("result.txt", $json);
echo($json);
}
function roomscanner($fruitId, $min, $max) {
$result = [];
$i = $min;
while ($i < $max) {
if ($i % 3 == 0) {
$curr['sweetness'] = rand(20, 29);
$curr['calories'] = rand(30, 39);
$curr['bitterness'] = rand(30, 39);
$result[] = $curr;
}
sleep(rand(0, 1));
$i++;
}
return $result;
}

Related

Js on click triggers a php update, it also triggers on load

this works for me on delete button, but this works when I go to this page also, on load of page it triggers status update i dont want that to change unless i click delete
Is it because it is php inside js or what?
var deleted_question = 0;
$(document).on("click", "button[id=removequestion]", function(data) {
var total_question_nr = <?php echo count($questions);?>;
var test_status = <?php echo $test->status; ?>;
if (test_status == 1) {
if ((total_question_nr - deleted_question) == 1) {
var result = confirm("#lang('general.if_questions_zero_test')");
console.log(total_question_nr - deleted_question);
if ((total_question_nr - deleted_question) == 0) {
var status = <?php echo $test->update(['status' => 0]); ?>;
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
if (result) {
var questionid = $(this).val();
$.ajax({
method: "POST",
url: "{{ url('/questions/delete-question') }}",
data: {
_token: "{{ csrf_token() }}",
question_id: questionid,
},
success: function(response) {
$("button[id=removequestion][value=" + questionid + "]").parent().parent().fadeOut('slow');
deleted_question++;
if ((total_question_nr - deleted_question) == 0) {
$('#publish-col').find('a').each(function() {
$(this).addClass("disabled");
});
}
},
error: function() {
console.log("error");
}
});
}
});

How to join two queries from the same table - Jquery Scroll function + Dependent Ajax Filter

How to join two queries from the same table?
The problem is I'm not able to JOIN these 2 MySql queries properly. The 1st query is for fetching the data from the database through AJAX and the second one is for AJAX page scroll.
These work individually, but I'm not getting the required output.
Updated: I was able to join the queries through union all, but when I select the relevant cities, it doesn't run as it should and also scroll isn't working, neither I'm returning the $output at the last for 'no data'.
Thanks!
PHP Code
<?php
require'connect_mysqli.php';
if(isset($_POST["city_id"], $_POST["limit"], $_POST["start"]))
{
if($_POST["city_id"] != '') {
$sql = ("SELECT * FROM playschools_8states WHERE city_id = '".$_POST["city_id"]."' limit 0, 5
union all SELECT * FROM playschools_8states order by city_id DESC LIMIT ".$_POST["start"].", ".$_POST["limit"]."");
}
else {
$sql = "SELECT * FROM playschools_8states limit 0, 5";
}
$result = mysqli_query($link, $sql);
$output = '';
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-12 module">
<div class="img-thumbnail img-responsive pull-right" style="margin:2px;"><img src="'.$row["logo"].'" /></div>
<p class="p_title_PS">'.$row["name"].'
<p class="p_state_city">'.$row["state"].', '.$row["pincode"].' </p>
<p class="p_rohit_adm"><b>School Type: </b> '.$row["schoolType"].'</p>
<p class="p_rohit_adm"><b>Co-Ed: </b> '.$row["coed"].'</p>
<p class="p_rohit_ad"><b></b> '.$row["private"].'</p></div>';
}
if ($output =='') {
echo 'Sorry! No matching results found';
}
else
echo $output;
}
?>
JavaScript
<script>
$(document).ready(function(){
$('#state').change(function(){
var state_id = $(this).val();
$.ajax({
url:"fetch_statedd.php",
method:"POST",
data:{stateId:state_id},
dataType:"text",
success:function(data)
{
$('#city').html(data);
}
});
});
});
</script>
<script>
$(document).ready(function(){
$('#city').change(function(){
var city_id = $(this).val();
$.ajax({
url:"ps_load_data.php",
method:"POST",
data:{city_id:city_id},
success:function(data){
$('#show_playschool').html(data);
}
});
});
});
</script>
<script>
$(document).ready(function(){
var limit = 7;
var start = 0;
var action = 'inactive';
function load_city_data(limit, start)
{
$.ajax({
url:"ps_load_data.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#load_data').append(data);
if(data == '')
{
$('#load_data_message').html("No Data Found");
action = 'active';
}
else
{
$('#load_data_message').html("<h4>Please wait...</h4>");
action = "inactive";
}
}
});
}
if(action == 'inactive')
{
action = 'active';
load_city_data(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
action = 'active';
start = start + limit;
setTimeout(function(){
load_city_data(limit, start);
}, 1000);
}
});
});
</script>

Can't upload multiple image using Ajax with codeigniter

Wana to upload multiple image with the help of Ajax in codeigniter but got some error while calling the function upload_business_photo_do() please help
thanks in advance....
<input type="button" id="uploadBusinessImg" value="Upload">
Ajax Code:- here i call ajax via id="uploadBusinessImg"
<script>
$("#uploadBusinessImg").on("click",function(e)
{
var total_img=$("#txtBusinessImage").get(0).files.length;
if(total_img<=5)
{
var f_size=0;
var f_size_1=0;
var f_type_1="" ,validFileName="",InValidFileName="";
var chkFileValid=true;
for(var i=0; i<=total_img-1; i++)
{
var f_name=$("#txtBusinessImage").get(0).files.item(i).name;
var f_size=$("#txtBusinessImage").get(0).files.item(i).size;
var f_type=f_name.split('.').pop();
//alert(f_type);
var valid_extensions = /(\.jpg|\.jpeg|\.png)$/i;
if(valid_extensions.test(f_name))
{
if(validFileName=="")
validFileName =f_name;
else
validFileName+=","+f_name;
}
else
{ InValidFileName=f_name;
chkFileValid=false;
break;
}
var newFileSize=parseInt(f_size);
f_size_1=parseInt(f_size_1)+parseInt(newFileSize);
}
var totalFileSize=f_size_1;
//alert(totalFileSize);
if(totalFileSize<=1572864 && chkFileValid==true)
{
//alert("allow");
alert(validFileName);
var businessIMAGE=validFileName;
$.ajax({
type:"POST",
url:"<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>",
mimeType:"multipart/form-data",
uploadMultiple: true,
data:{reciveBusinessImg:businessIMAGE},
success: function(reviceUploadImgMsg)
{
alert(reviceUploadImgMsg);
}
});
}
else
{
if(chkFileValid==false)
alert("InValidFileName"+InValidFileName);
else
alert("Image size should be less then 1.5 MB");
}
}
else
{
alert("Not Allow");
}
});
</script>
This is Controller Code:-
function upload_business_photo_do()
{
$reciveBusinessImgName=$this->input->post('reciveBusinessImg');
$newArray=explode(",",$reciveBusinessImgName);
/*code for image*/
$config['upload_path']='./company_image/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($newArray); $i++)
{
$_FILES['userfile']['name']= $_FILES['txtBusinessImage']['name'][$i];
$_FILES['userfile']['type']= $_FILES['txtBusinessImage']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['txtBusinessImage']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['txtBusinessImage']['error'][$i];
$_FILES['userfile']['size']= $_FILES['txtBusinessImage']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
$upload_data = $this->upload->data();
echo "done";
}
}
}

commands in chatroom & defining words after command

Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.

PHP - Sent one value in looping to AJAX / JQuery

I'm having problem to sent only one echo = 'true_user' back to jquery. Right now, the true_user will sent back to jquery based on $id that user have selected.
Second, how to combine when echo ='false' and echo ='failed' are sent back to jquery? I tried to use || and still not working.
jQuery / AJAX
<script>
jQuery(document).ready(function(){
jQuery("#delete_user").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "delete_users.php",
data: formData,
success: function(html){
if (html=='false_user'){
$.jGrowl("Please select user", { header: 'Error' });
alert(html);
}else if (html=='failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if(html=='true'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'User Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='true_user'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'Users Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='false','failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else{
$.jGrowl("Please try again", { header: 'Error' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}
}//success
});
return false;
});
});
</script>
delete_users.php
<?php
error_reporting(E_ALL&~E_NOTICE);
include('dbcon.php');
include('session.php');
//if (isset($_POST['delete_user'])){
$id=$_POST['selector'];
//$id = array(61);
$N = count($id);
if ($N == 0){ //if no selected
echo 'false_user';
} else { //if selected
for($i=0; $i < $N; $i++)
{
$stmt = $conn->prepare("select * from users WHERE user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$result = $stmt->fetchObject();
$userType = $result->user_type;
//$user_type = $row['user_type']
if ($userType >= 1){ //if user type not 0 = developer
if ($id[$i] == $session_id){ // cannot delete own account
echo 'failed';
} else if($N==1){
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
echo 'true';
} else if ($N > 1){ // if select more than one
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
$testing = 'true_user';
//return;
}
}else{ //other error
echo 'false';
}
}
}
?>

Categories

Resources