How to pass a string typed by a user to Javascript, safely?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cool-RR
Forum Newbie
Posts: 2
Joined: Thu Feb 03, 2005 5:14 pm
Contact:

How to pass a string typed by a user to Javascript, safely?

Post by cool-RR »

How can I pass a string typed by a user from PHP to Javascript, safely? I mean, actually I need a user to input something, and then this string would be passed to javascript code and also to MySQL. It will also be in the HTML of the site, for other viewers. Now how do I completely prevent a malicious user from somehow entering something that will give him too much control? I mean, how do I make it [b]absolutely[/b] impossible for the m-user to do some <?php and all the other stuff? I am probably looking for some function that would recieve a raw string and return the safe string.

Thanks very much for your help,
cool-RR.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

absolute impossiblity requires that no server exists, and that the computer is unplugged from any power or any other connection.

with that in mind, you can only prevent it. As such, filtering the text through your favourite filter will handle the bulk of it. This filter could be addslashes() or whatever.. it depends on your query code as to what is vulnerable in SQL. As for Javascript, just escaping the characters used to create the string and making sure the string is a single line are required. So conversion of ' to '' and \n to \\n for instance.
cool-RR
Forum Newbie
Posts: 2
Joined: Thu Feb 03, 2005 5:14 pm
Contact:

Post by cool-RR »

Thanks for the help.
Hasn't a function for this already been written? I mean, I can write it myself, but it's just one of those things that you can never be sure will really work. I mean, I don't want to forget to cover something and then end up with my site deleted. I mean, this task of passing strings from PHP to other modules like JS and MySQL seems like something that's being done a lot, so I would guess that people with experience have written functions which proved to be safe for that procedure, or perhaps thought of some other way to pass commands to MySQL (I really don't know if there's anyway except the query thing). So anyway if anyone has a good function to make strings secure, I'll appreciate if you give me the link or something.
Thanks, cool-RR.
Post Reply