In my ajax.php has:
if(urlvar(2) == 'uploadphoto'){
do... echo '<img... />';
}
But this functions is only called by a jquery, returning on a specific div.
But if I visit the URL: [http://localhost/projectname/ajax/uploadphoto], this page returns the result of function with some erros (because the parameters are sent by jquery)
How I can prevent returns, if the file is accessed without jquery?
*SOLVED:
Use this function in functions that cannot be accessed without jquery method.
function isHttpRequest()
{
if( #$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
return true; //acessed by jquery
}
exit; // or return false -> from access the file without method
}
When you access the file via jQuery, you write something like:
method: "get" or method:"post" (The default, if not specified, is GET, I think)
So, at the beginning of your ajax.php - put:
if(!$_GET){
//[...the ajax.php code, here ...]
}
I personally create a hash in every form
and i check if that hash is correct , this prevents people from submitting forms from other servers too and it may help in your situation
http://code.tutsplus.com/tutorials/secure-your-forms-with-form-keys--net-4753
if the hash is wrong then it's abviously not coming from the form that it should come from
Modify your ajax.php to check if the request is an ajax call.
if(empty($_SERVER['HTTP_X_REQUESTED_WITH'])
|| strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
// not an ajax request
} else {
if(urlvar(2) == 'uploadphoto'){
do... echo '<img... />';
}
}
Or just check at the beginning of ajax.php
Related
I need only PHP answers.
Setup : Apache Server and PHP version 7.4.
I'm working on a CAPTCHA plugin for WordPress. On that purpose, I thought I'd validate the CAPTCHA field before validating any other request.
This means I want to perform the CAPTCHA POST request before any other $_REQUEST is complete.
These other requests can be multiples, and I won't be able to handle their scripts.
I thought I'd detect if a POST or GET request has been made, then maybe call sleep() and perform my POST meanwhile.
The problem is : sleep() pauses the whole script whereas I only want the other POST and GET requests to be paused...
if ($_SERVER['REQUEST_METHOD'] === 'POST' OR $_SERVER[‘REQUEST_METHOD’] === 'GET' AND $_POST["myRequest"]) {
// Pause every POST and GET requests apart from $_POST["myRequest"] until $_POST["myRequest"] is performed
} else {
continue;
}
You could use session and keep track of the request and save the request if $_POST['myRequest'] is not present, than load the previous request from session or a file. Like this:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST' OR $_SERVER[‘REQUEST_METHOD’] === 'GET') {
// POST myRequest has been done before
if(isset($_SESSION['.my-request.lock'])) {
// If present remove it
unset($_SESSION['.my-request.lock']);
if(isset($_SESSION['my-data.json'])) {
$my_prev_request = json_decode( $_SESSION['my-data.json'] );
unset($_SESSION['my-data.json']);
}
// Process other requests
} else {
if(isset($_POST['myRequest'])) {
$_SESSION['.my-request.lock'] = true;
// Do your own thing
} else {
// No myRequest and no file, save request data to load it after POST myRequest
$_SESSION['my-data.json'] = json_encode( $_REQUEST );
}
}
} else {
// Display Error ?
continue;
}
i would like to know if its possible to set up my script so it can be handled by http ajax call and alternatively also the classic post way:
on the top i am first doing this:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
$AnswerType = 'die';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$AnswerType = 'session';
}
Then i check if either of these two is set by doing the following:
if ($AnswerType == 'die' || $AnswerType == 'session' ){
*here i run my script*
}
When the script ends i finally try to send all responses in my $respond_message array back the way the form where initialy posted:
if ($AnswerType = 'die'){
die(print_r($respond_message));
}
if ($AnswerType = 'session'){
$_SESSION['formrespondmessage'].= print_r($respond_message);
header("Location: /");
}
You want the script to react different on ajax and on simple post request? I think in this case the best solution is just to pass any variable, which indicates, that data is being sent by ajax. Like this:
postparams['ajax']=1;
$.post(...
And then in php make check like this:
if (isset($_POST['ajax'])) {
code for ajax request
} else {
code for simple post request
}
Not sure about your code, I prefer not to use so complicated scripts, at least you need to add () after serializeArray, possibly everything else looks ok. I would do like this:
<form name="form1" id="form1">
<input type="text" name="qq" value="ww">
</form>
<input type="button" onclick="dt=$('#form1').serializeArray();dt[dt.length]={name: 'ajax', 'value': 1};$.post('test.php', dt, function(data) {alert(data)});">
And in php file just check if isset($_POST["ajax"]). For example, my looks like this:
<?
if (isset($_POST["ajax"])) print_r($_POST);
?>
I have the following javascript loop which correctly alerts the value I need to use in a Codeigniter method. Here is the js loop:
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
alert ($(this).prop('value'));
}
});
}
Instead of alerting the required value, I need to somehow execute this Codeigniter method:
//this would never work because it mixes JS with PHP, but I need a workaround
$this->appeal_model->myMethod($(this).prop('value'), 888, 999);
Is there someway that I can run this PHP code inside the javascript loop? I know about PHP being server-side and JS being client-side, but I'm sure there must be a solution to my problem that I'm just not aware of yet. Thanks.
The solution to this is to make an ajax call to the server, you can have a method on your controller which calls your codeigniter method. This divides your php call and your client side call.
If you are inserting something into the database, you should use the ajax post method.
http://api.jquery.com/jQuery.post/
function myInsert() {
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
var value = $(this).prop('value');
$.post("controllername/functionname", { value: value }, function(data) {
alert(data); // Returned message from the server
});
}
});
}
Use ajax to store data to the server side:
The code should be something like this:
function myInsert(){
$dataArray=[];
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
dataArray.push($(this).prop('value'))
}
});
if(dataArray.length>0)
{
$.ajax({
url:"your file name",//this file should contain your server side scripting
type:"POST",
data:{dataName : dataArray}
success:function(){
}
});
}
}
you can use $.post from jquery
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
$.post('<?php echo site_url("controllerName/functionName")?>',
{"post1": $(this).prop('value'), "post2":888, "post3": 999 },
function(data.res == "something"){
//here you can process your returned data.
}, "json"); //**
}
});
}
In your controller you can have:
function functionName()
{
//getting your posted sec token.
$post1 = $this->input->post('post1');
$post2 = $this->input->post('post2');
$post3 = $this->input->post('post3');
$data['res'] = "something";// return anything you like.
// you should use json_encode here because your post's return specified as json. see **
echo json_encode($data); //$data is checked in the callback function in jquery.
}
Since this will be dumping data directly into your db, make sure this is secured in some manner as well, in terms of who has access to that controller function and the amount of scrubbing/verification done on the data being passed.
Well, another try:
this is all the jquery code i'm using maybe i made something wrong in the code before $.post(); i call the following function with the onclick of the same form...
function setLogin()
{
$('#login-form').submit(function(e) {
e.preventDefault();
//passing form field to vars
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
//checks on fields lenght
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
//the url
'?module=login',
//data got from login form
{
"username": formUsername,
"password": formPassword,
},
//response
function(data){
$("#ajax-output").html(data.reply)
},
//type
"json"
);
}
});
}
i tried with only this code in php file and it still doesn't return anything...
function Login()
{
//just to try
echo json_encode(array('reply'=>'foo'));
}
it still doesn't work...
Are you sure the post is being run in the first place?
Use Firebug! (or chrome's built-in developer tools)
You can use firebug to pick apart every bit of a web page.
It has a "net" tab that shows every request that is made by the browser, including AJAX requests, and their results, headers and contents.
Use it to see if your requests is really being made, and what the result is. Then take it from there.
Make sure that you're setting a header for the content type when responding - the browser may not attempt to use the JSON if it doesn't know it's receiving JSON.
function Login()
{
header('Content-Type: application/json');
echo json_encode(array('reply'=>'foo'));
}
How would you go about using tokens with the following?
$('#DIV').load('child.php?id='+id);
So that you couldn't access child.php straight from the browser and type child.php?id=1
If this is not possible with tokens would there be any other way?
Thought about XMLHttpRequest as follows:
var mygetrequest=new ajaxRequest();
mygetrequest.onreadystatechange = function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("DIV").innerHTML = mygetrequest.responseText;
} else{
alert("An error has occured making the request");
}
}
}
mygetrequest.open("GET", "child.php?id="+id, true);
mygetrequest.send(null);
Many thanks.
What you need is to check if the request is an ajax request (from load()) or not, this can be done by the following:
child.php:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// it's an ajax request validate id and continue!
} else {
// this is not an ajax request, get out of here!
}
You could use jQuery post to send the parameters "behind the scene" and then check if the request was sent from a certain location or IP within the actual php file. If the location or IP does not have the authority to access it, simply output an error using e.g. the die() method before anything else has been output.