Setting PHP variables from AJAX/Json - php

At the moment I have this code:
index.php
var refreshId = setInterval(function() {
$.ajax({
url: ("http://www.example.co.uk/erc/user_data.php?imei="+inCallingNum),
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
$('#right-side').html(data.rightside);
$('#caller').html(data.caller);
$('.location').html(data.location);
$('.battery-level').html(data.battery);
//parse the json data
}
});
});
user_data.php
$profile = array();
$profile['rightside'] = $rightside;
$profile['caller'] = $caller;
$profile['nextofkin'] = $nextofkin;
$profile['location'] = $location;
$profile['battery'] = $battery;
echo json_encode($profile);
This works fine to add the information into the div tags, but what I need to do now is take a PHP variable from the user_data.php file and use it in the index.php file. Is it possible to send/capture PHP variables in that way?
E.g. in user_data.php I have a variable $test and I want to use this $test variable in index.php
Thanks for any help

There are many ways you can do this, and the easiest (and most transparent way of doing so) is by setting a session cookie. This is a small file that sits on the client's computer, and is readable by all sites on your sub-domain (x.mydomain.com.), basically all files in that same folder as the file that set it. You can do this easily in PHP by doing the following things:
On EVERY page you want to set, get, or otherwise check for the variables... use this code
session_start(); // Put this at the TOP of your page, below <? or just before you check the variables.
On the page you want to SET the variables... use this code
$_SESSION['variable'] = "data";
session_write_close(); // Use this after you are done setting the session data, to save it before the page execution is finished. This is a good habit to get in to, it's kind of like when you fclose a file instead of waiting for the script to do it.
On the page you want to GET the variables.. use this code
$test = $_SESSION['variable'];
You can basically use the $_SESSION array to store variables you want to be seen as "global" on your site. Forums use this to store the User ID and session hash, for later authentication on passwords. Other sites use session cookies to limit user activity within a given timeframe.
--
There is also another way you can do this, have a link from your page that generates the value of $test send a GET request to index.php (for example, if the user clicks a link format the link like:
index.php?test=value
Then on index.php simply do:
$test = $_GET{'test'];
This method is good for users who may not have cookie support, or may have cookies disabled; but is very obvious, and users can easily change the value of the cookie (which can have unseen results.)

What you are asking for cannot really be done since index.php is executed before user_data.php. However, since you are sending the result from user_data.php to index.php maybe you can look at consuming the variable with JavaScript. Why not tell us more about what you would like to accomplish so we can suggest how it can be done.

two ways:
either set $test into $_SESSION['test'] and get it on index.php
alternative:
did u try with json_decode()

You have the answer to your question in the question!
Even though you are creating and array to encode as JSON you are in fact just passing values from php to javascript.
You could equally do
$profile['test'] = $test;
and then in your javascript use
data.test
to get your value.
The question is when are you wanting to get the varaible value? Is it before the page is served or during your ajax call?

You should create your JavaScript code dynamically, with PHP:
alert("server name: <?php
echo $_SERVER['SERVER_NAME'];
?>");
Use it with caution, just in rare cases.

Related

Hide PHP Variables in URL with url rewrite

I am working on a site that has to deal with reservation numbers and I need to pass variables to confirmation page. Currently when you arrive at confirmation.php the URL looks something like the below:
http://localhost/confirmation.php?reservation_id=1&proceed=no
These variables are sent via a link to this page from the index page. I need a way to either encrypt the $reservation_id OR rewrite my URL so it looks like this
http://localhost/confirmation.php
...but still have access to my variables. I have tried sessions and some encryption methods, but cant find anything that wont over complicate the page as I am trying to keep it as simple as possible. Forms with hidden fields is not an option, I am printing all the reservations in links with a loop from the database.
Thanks!
Use session variables. Create a random session variable name, and assign the reservation information to it:
foreach ($reservations as $r) {
$random = make_random_string(); // You need to write this function
$_SESSION[$random] = $r;
echo "<a href='reservation.php?id=$random'>...</a>";
}
Then reservation.php can look up $_SESSION[$_GET['id']] to get the reservation information.
It sounds like you need to start a session and pass the data in there. Or, you could POST the data instead (Use a form). But the session is probably the better choice.

Hide var data on ajax

I am making AJAX like function but I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
$live = 'user1';
$fol = 'user2';
function ajax(like){
var data = 'like='+like+'&CURRENTUSER=<?php echo $live; ?>&TOFOLLOW=<?php echo $fol; ?>';
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: data,
success: function(e) {
$('#success').html(e);
}
});
}
Also I want to move this ajax function into ajax.js file, but i am have problem in getting the value $live and $fol of users because echo $live doesn't work on .js.
So, is there any way to do this like Facebook, Twitter AJAX function does ?
This solution works for apache web-server. For interpreting JS file using php, add this line to your .htaccess file:
AddType application/x-httpd-php .js
And put your script inside ajax.js. One other way is using rewrite URL:
RewriteEngine On
RewriteRule ^ajax.js$ ajax.js.php [L]
And put your scripts inside ajax.js.php file. Of course, all these are if you want to show your URL as JS file.
at the top of your ajax.js or ajax.js.php file, before any kind of output, put this:
header('Content-Type: application/javascript');
I have problem that bad user can change the value into any other current user. So, how can I prevent this thing?
Of course you can not do that at all.
HTTP is a stateless protocol – so each and every request that reaches your server is to be mistrusted, period.
You have to check server-side whether the requesting client is authorized to request/perform whatever action it is he wants to trigger – f.e. by checking that the user id that is passed as the “current” user against the session where you stored your login information. (So when you have the id of the current user stored in there, then there’s no need to actually send it from the client any more in the first place.)
This is one of the most basic security principles of any web application – don’t trust any incoming request, until you have verified that the client has the appropriate authorization. So asking for how to “hide” any data that is send from the client is completely the wrong question – that would be what’s called “security by obscurity”, and that does not work.
There can be many solutions for such problem.
Add one of follow user in session before page load so even you dont need to send data in ajax. Just need to confirm action and all data will be taken from session. Hence hackers cant modify users.(This is how i solved the problem in my project)
You can build an function like encode() & decode(). when you are using data in file encode() it first.Then at code end use decode() to extract the info. Since if invalid data came out mean some one has tempered and you will not execute that action. But you have to create such encode() & decode() yourself.
$live = encode(user1);
At php end
$real_live = decode($live);
3. Ajax request to when start php execution you can have a function like
check_auth(user1,user2);
So even if some one used bad data your security rules can filter them.
Hope you can use any of them.

How should I make variable global for all the pages in PHP

Question
I want to make $associate_name and $app_key global variable so I can access them on any page I want. Below is the code from my header file and the get variables are coming to index page. It works fine on index page as the $_GET data is available but when a user moves onto next page but with the same header file included it throws an error saying Undefined index. Please let me know how can I make this variable available on all pages. Thanks!
Code
$associate_name = $_REQUEST['an'];
$app_key = $_REQUEST['key'];
define('associate_name',$associate_name);
define('app_key',$app_key);
//echo "Sorry but there seems to be a problem in your code. We can't find one of the following: App name or App key";
$select_associate = "SELECT * FROM associate_account WHERE associate_name='".associate_name."' and app_key='".app_key."'";
$assoc_result = mysql_query($select_associate) or die($select_associate.mysql_error());
if(mysql_num_rows($assoc_result)<=0){
echo "Oops there seems to be a problem in your iFrame code. Please login into your Associate panel and copy/paste the link again.";
}else{
$row_assoc = mysql_fetch_assoc($assoc_result);
$associate_name=ucwords($row_assoc['associate_name']);
$app_logo=$row_assoc['app_logo'];
$app_intro_content=$row_assoc['app_intro_content'];
$bg_color=$row_assoc['bg_color'];
}
Put those variables you want as session or cookie data. Otherwise, you would have to resort to the global keyword, which is a very bad way of doing things in modern PHP applications.
It would be like this (for session):
$_SESSION["myvar"] = <value>;
It's a bit more complicated with cookies, but this should get you going ;)
Have all your variables/constants in a separate file may be constants.php
Include that constants.php wherever you want to access that variable.
Use $_SESSION
Sessions are your choice in case the value is modified. Otherwise (the value is constant from your configuration and not from user's modification, go for Constants

Hide ?ref string in URL but pass it to script

How can I hide ?ref string from users but pass it to php code so it will grab it?
For example, visitor visits this page:
http://mysite.com/?ref=ref+string
In browser URL I want to hide it, so user will see"
http://mysite.com/
But I want to grab content of ref string via this:
$ref = $_GET['ref'];
Is it possible?
No, if you want to use GET variables, they will always be in the url.
However, you can use an alternative, like $_SESSION or $_POST variables.
You could try something like this at the top of your PHP script:
session_start();
if (isset($_GET['ref'])) {
$_SESSION['ref'] = $_GET['ref'];
header('Location: /');
exit();
}
You would have to use $_SESSION['ref'] to access the value from then on, however.
This is not how the http protocol works with query strings. If you have information that needs to be in the query string that you want to hide or obfuscate from the user, I would recommend a simple encryption to change it. If you're attempting to get rid of this information for aesthetic reasons, you will need to pursue a different method of generating the header or storing the information (session/cookies/etc).

Obtain actual browser URL in PHP

I need to retrieve the actual URL that the user see's in their browser. I have an Ajax request running at page load. Hence, the regular $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"] expression returns the request URL of the Ajax request instead of the actual URL in the browser.
Any idea how to get this?
You could pass it up from javascript in your ajax request, using window.location.href.
Also, it's likely that $_SERVER['HTTP_REFERER'] will contain the browser's current location.
You could also try using $_SERVER['HTTP_REFERER'];. This might work, not 100% sure though.
You can't do that with server-side code, as there is no server-side variable that refers to what the client sees. The only thing you CAN see (and then again, it depends on the browser the user's using, some don't pass this info) is the HTTP_REFERRER variable. This however, is only set when a page calls another, not when users first access your site.
See this for more details.
A possible solution however, might be to use javascript function to send the browser's top URL to the server using an AJAX query, and to fire it client-side whenever a user loads the pages) you want to get this info for.
Edit: Damn, too slow, already answered!
Pass a hidden input that has the browser value set with your ajax request. Unless someone is being malicious, it should suffice.
If you do an Ajax-request, you could pass the address available through Javascripts window.location.href variable as a POST-variable with the request.
With jQuery it would be something like:
$.ajax({
url: 'your-url.php',
type: "POST",
data: { url: window.location.href },
success: function (data) {
// Do something on success
}
});
With such a request you could access the URL on the server-side with a simple:
<?php
$url = $_POST["url"];
?>
Actual Website Link in php
<?php
echo $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
?>
Server-side languages can't see what happens after they've rendered and outputted the page.

Categories