Is it unsecure to embed PHP code in a javascript function?
My friend told me not to do it.
My script just inserts a number in the database if the message has been clicked (read).
<!--Insert into database when click-->
<script>
function insert()
{
<?php
include 'db_connect.php';
$usermsg = $_SESSION['username'];
$message_id = $_GET['messageid'];
mysql_query("UPDATE messages SET message_read='1' WHERE id='$message_id' AND to_user='$usermsg'");
?>
}
</script>
Should i do this any otherway? Or drop including php & mysql in my script and start over?
Your friend probably told you not to do it because it makes no sense whatsoever.
PHP is a preprocessing language whose parser runs on the webserver. The result of running PHP is the HTML/Javascript that your browser sees. Your PHP does not output anything (merely silently performing the SQL query whilst your HTML/Javascript page is being generated), so the Javascript that your browser sees is:
<script>
function insert()
{
}
</script>
PHP cannot be "inside" a Javascript function at all. There is no such concept.
Instead, consider an HTML form, or read up about "AJAX" when you're slightly more familiar with the web technologies heirarchy.
If you try that code, it won't even work that way. You cannot embed server side code in javascript function.
What you want is to make a sepearate request that will handle the request. This method is called AJAX. With jQuery library you can make AJAX POST request like this:
<script>
function insert()
{
//Example: Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { messageid: "1" } );
}
</script>
In test.php:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['messageid'])) {
include 'db_connect.php';
$usermsg = $_SESSION['username'];
$message_id = $_POST['messageid'];
mysql_query("UPDATE messages SET message_read='1' WHERE id='$message_id' AND to_user='$usermsg'");
}
?>
Read the Beginners Guide to Using AJAX with jQuery
And don't forget to use parametrized sql to prevent sql injection attacks as this code in its current state is vulnurable.
It's insecure in that it's entirely possible for PHP to insert some text into the page that breaks the javascript. e.g.
<?php
$name = "O'Brien";
?>
<script type="text/javascript">
var name = <?php echo $name ?>;
</script>
This would produce:
var name = O'Brien;
which is illegal JS syntax. You're assigning an undefined variable O, which is immediately followed by an unterminated string literal 'Brien. Surrounding this with quotes in the PHP page accomplishes nothing either:
var name = '<?php echo $name ?>';
^ ^-- added quotes
which now gives
var name = 'O'Brien';
Now you've got a slightly different problem: Assigning a perfectly valid string literal 'O', followed immediately by an undefined variable Brien, followed by an unterminated string literal ';.
The proper way to have PHP output text into a JS code block safely is to use json_encode:
var name = <?php echo json_encode($name) ?>;
which produces:
var name = "O'Brien";
and off you go.
PHP/MySql runs on the web server. Javascript runs on the browser.
You should also think that anything that comes from the browser may be faked - therefore should validate/verify it. Javascript just makes the users experience more interactive as it does not require communication across the network. Use AJAX or forms to do the comms.
Related
I am trying to set a session variable in a php script and get the variable in
a javaScript.
In the php program I put an echo command to see if the variable
is generated. Nothing happens.
In the javascript I try to write the variable to the screen and I see nothing. If I put single quotes around the get command I just get a display of that command.
php:
$full_name = $_POST['Full_Name']; // required
$names = explode(" ", $full_name);
$_SESSION['myvar'] = $names[0];
echo ($names[0]);
javascript:
<script type="text/javascript">
var name = #Session["myvar"];
document.write(name);
</script>
Direct use of PHP in a JS-script is really not useful if you want to make it scalable.
Use it like this
myprintoutscript.js
function writeOnDocument(name){
document.write(name);
}
In most cases it is better to call a js-function from the outside with a variable (in your case the session)
index.php
<script>
//referencing to function in myPrintOutScript.js
writeOnDocument("<?= $_SESSION['myvar'] ?>");
</script>
Or readout a html data-attribute, for example a body
index.php
<body data-session-name="<?= $_SESSION['myvar'] ?>">
and call it from a script:
windowIsLoadedScript.js
var body = document.getElementsByTagName("BODY")[0],
name = body.getAttribute("data-session-name");
//referencing to function in myPrintOutScript.js
writeOnDocument(name);
The more you keep things separated, the easier it is to make your building blocks stack on to each other.
Writing JavaScript with PHP...hmmm...as a programmer that has inherited code where other programmers did this...Please don't. It's hard to see what's going on when you start mixing languages together.
As to your actual problem...generally, you put stuff into the Session that you want to keep "secret", or stuff that you have already properly secured, like the User's ID value of who is logged in so that when they go to the next page, you see the User ID in a session and you trust that data because it came from your server rather than the user. POST, GET, and COOKIE data is insecure, so you don't trust what the user is sending you.
In any case, for stuff that you want to be accessible to both PHP AND Javascript, if you're not using web services, I would suggest using cookies might be the better practice.
setcookie('FirstName',$_SESSION['myvar']);
http://php.net/manual/en/function.setcookie.php
Admittedly, getting cookie values with JavaScript is a pain in itself, but people have already written the code for you, so it shouldn't be as painful:
Get cookie by name
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var name = getCookie('FirstName');
[EDIT] I would also say that the other poster's answer, putting it into a data-attribute within the HTML, is also a good practice and more clear than writing to JS directly.
<body data-first-name="<?php echo htmlspecialchars($firstName) ?>">
write session_start(); at the starting of the php file.
then catch the variable into js like this.
<script type="text/javascript">
var name ="<?php echo $_SESSION['myvar'];?>";
document.write(name);
</script>
Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");
How do I use php and javascript together? from doing my own research, it seems impossible. I understand that they are different, and they each have their own special things that they do. But let's say you are validating a form. You use javascript to validate the form, then if there are no errors, you run php to insert a record. How would you do this? Is there any way to run php in javascript or call on a php method?
Generally you will see Javascript used as client side code. This means that a browser that visits your website will download your Javascript code, compile it, and run it itself. Client side code simply means that the client (person who visits your website) runs the code.
PHP, on the other hand, is used as server side code. This means that your web server parses and runs your code. Server side code simply means that the code is run on your web server.
You can give information to Javascript from PHP code. For example:
<?php
$myVariable = 'a testing variable';
?>
<script type='text/javascript'>
var fromTheServer = '<?php echo $myVariable; ?>';
</script>
The Javascript variable fromTheServer is set to the value of the php variable myVariable. All this is really doing is outputting the value of the php variable as a string, which Javascript uses. This approach can be useful, say if you wanted a Javascript array of shopping cart items the user currently has in their cart.
<?php
// get some shopping cart items using a function
$shoppingCartItemsArray = getShoppingCartItems();
?>
<script type='text/javascript'>
var shoppingCartItemsArray = "<?php echo implode('|', $shoppingCartItemsArray); ?>";
// split the string value by the | delimeter to get an array
shoppingCartItemsArray = shoppingCartItemsArray.split('|');
</script>
Now you have seen how you can integrate php with Javascript a little bit. Once again, this isn't really integrating, just outputting information from the server. What about sending information to the server? This is where AJAX comes in.
Say you are implementing a drag and drop shopping cart with Javascript. The idea is that the user picks an item from your site and drags it to their shopping cart. Upon letting go of the item, the item should be added to the users cart on the server. You would be using AJAX to post the item number to the server and wait for the server to tell you whether the item was successfully added. Note: You can build your own AJAX methods making use of native Javascript code, however, why do that when you can use a framework that has it built in? I generally use jQuery, but there are a number of other JS frameworks out there you can use.
The following very simple example shows how an interaction with Javascript and php could look like under the above circumstance. It uses jQuerys $.ajax(); function.
<?php
/** File: https://www.example.com/cart.php **/
// .. code
if($_POST['action'] === 'addItem'){
$result = addItemToCart($_POST['itemId']);
echo $result;
}
// ... code
?>
<script type='text/javascript'>
// code ....
$.ajax({
url: 'https://www.example.com/cart.php'
type: 'POST',
data: {
action: 'addItem',
itemId: getDraggedItem() // get the item id from a function
}
success: function(result){
$('#ServerMessage').html(result);
}
});
// code ....
</script>
Ok, so now you can very briefly see how php and Javascript are acting if javascript is being used as client side code.
Javascript can also be used as Server Side code, for example, IIS allows you to run JScript in tangent with VBScript.
<script type='text/javascript' runat='server'>
Response.Write("MS Server here.")
</script>
In addition to this, CommonJS provides an API for server-side Javascript code which many projects are now implementing. You may have heard of some of these, Node.js in particular. One of these projects may allow you to run php and javascript in conjunction with eachother, you'll have to look.
The bottom line is, Javascript is not only client side code. It's simply code that can be executed on either the server or the client, or as a way to clean up your iTunes library.
You need to validate in both JavaScript and PHP. But most important is PHP validation because remember: Javascript is frontend code, therefore can be modified or simply disabled by the user. So before inserting you must validate in PHP.
There are thousands of javascript validation plugins, a good one is jQuery Validate:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
You have an example here on PHP validation:
http://buildinternet.com/2008/12/how-to-validate-a-form-complete-with-error-messages-using-php-part-1/
You can validate using javascript and insert records using php. But, it is much better if you will validate the records with javascript and php. Why? Because javascript validation will be useless when you turn off javascript in your browser, that means, if browser javascript is off, no validations will run and that means the invalid records will be inserted to your database. So it is much better to have a backup php validation.
<?php
if(PHP VALIDATION) {
echo 'You were not validated';
} else {
echo "<script src=\"FILE WITH UR JAVASCRIPT\"><script>"
}
?>
This javascript will only load and executed if the php validation is complete.
lets have this simple example:
the example given uses jquery, you might google that up.
html:
<html>
<body>
<input type = "text" name = "username" id = "username"></input>
<input type = "button" name = "submit" id = "save_button" value = "insert"></input>
<div id = "save_stat"></div> <!--This will be the status of the insertion. "loading or sucess!"---->
<script>
$('#save_button').click(function(){ //assign an event handler
//grab values
var name = $('#username').val(); //get the value of whatever the user entered
//perform HTTP ajax request
//could be $.get instead
$.post('phpfile.php', (name:name)/*this could be modified to (name:name, password: password) etc.*/, function(data){ //send the data to the php file.
$('#save_stat').html(data);
});
});
</script>
</body>
</html>
Now all that is left to do is create the php registration page and link it instead of the "phpfile.php"
And to load values in that file, sinply use $_POST['name'];
OR $_POST['password']; etc.
The above answers(suggested by others) are perfect, as they suggest the essence of what you actually require to create an in-sync Javascript and php application.
***EDIT NOTICE********
When creating the php, use echo statement when giving the user messages, i.e
if(!empty($_POST['name'])){
echo "You successfully entered your name!";
}else
echo "you forgot to enter a name";
Sample #2
if(!empty($_POST['name'])){
$message = "You successfully entered your name!";
}else
$message = "you forgot to enter a name";
echo $message;
i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.
Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);