I get a string, from an external clientside script, which must later be attached as part of an url. Now I am wondering what is the best way to santitize such data?
The string I get will have a structure like this:
dynamicVal#staticVal:dynamicVal
This value will then be added to an url:
http://the-page.com/dynamicVal#staticVal:dynamicVal
The url is then used as followed:
$link = htmlspecialchars("http://external-page.com/dynamicVal#staticVal:dynamicVal", ENT_QUOTES);
$var = "'Open URL'";
Problem is, htmlspecialchars wont help to prevent execution of random javascript code, e.g. by adding this alert to the value:
dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'
Using rawurlencode wont help either, because it is not a value of a parameter but a real part of the url.
So what is the best way to sanitize the passed string when concatenating to the url?
Thanks in advance.
Edit:
Using rawurlencode only on the dynamic parts actually also didn't solve the issue, the javascript still got executed.
Test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Edit2:
Using json_encode when passing the string as javascript argument didn't help either.
Adapted test snippet:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal\"+alert('breakout')+\"");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode($tmpArr[0]), rawurlencode($tmpArr[1])), ENT_QUOTES);
echo "'Open URL'";
Adaptions done:
Switched the quotes in the malicous JS.
Moved htmlspecialchars around json_encode, because a double quoted string gets returned which would break the html otherwise.
You should use urlencode() for this. Not on the whole string but on the dynamic parts only.
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
EDIT:
OK - I see your problem. I didn't realize that you insert the code into a JavaScript function call. You'll have to ensure that the JavaScript interpreter treats your link as a string argument to window.open():
$link = sprintf('http://external-page.com/%s#staticVal:%s', urlencode('dynamicVal'), urlencode('dynamicVal'));
$var = "'Open URL'";
For completenes, I was able to solve that issue by simply putting addslashes on the dynamic part before using rawurlencode.
Both function calls are needed to prevent breaking out. Using addslashes prevents normal quotes (',") and rawurlencode prevents already encoded quotes (%29,%22) to cause harm.
So final solution looks like this:
$splitVal = "#staticVal:";
$tmpArr = explode($splitVal, "dynamicVal#staticVal:dynamicVal'+alert(\"breakout\")+'");
$link = htmlspecialchars(sprintf("http://external-page.com/"."%s$splitVal%s", rawurlencode(addslashes($tmpArr[0])), rawurlencode(addslashes($tmpArr[1]))), ENT_QUOTES);
echo "'Open URL'";
Related
I have a php page which get response from another page as shown:
while($response!=200)
{
$response = include 'xyz.php?one='.$one.'&two='.$two.'&three='.$three.'';
}
But my link always get's something like:
domainname.com/xyz.php?one=content&two=content&three=content
And due to & getting replaced by & I am getting the page not found issue.
I have tried using %26 and directly putting & instead of &, all in vain.
Is there any other simple solution besides using string replace function of PHP to remove & and replace it with &
Check out html_entity_decode
$response = html_entity_decode($response)
I ran a test based on the code you sent and I don't have a problem. That suggests you have something auto-magical going on in your *.ini file (magic quotes, maybe... ugh...). Try to create the string simply as a variable to remove it from the filename context and echo it out to be sure it's right, then use the variable with your include.
$one = 'abc';
$two = 'def';
$three = "ghi";
$file= 'xyz.php?one='.$one.'&two='.$two.'&three='.$three;
echo "\n\n".$file;
$response = include $file;
You can't use URL parameters when accessing a local file, they have to go through the webserver. Try:
$response = file_get_contents("http://localhost/path/to/xyz.php?one='.$one.'&two='.$two.'&three='.$three);
I have a javascript variable which hold the value taken from somewhere else(lets say from a API call), taken string is given bellow,
He's the reason for this
I assign this string to a variable name 'sample'. But when I print it, it doesn't work since the string has " ' " character. I want to add " \ " before the " ' " character. I tried using this,
var sample = (get the string from a api call).replace(/'/g,"\\\'");
But it doesn't work?
in my javascript file I use window.location.href = "test.php?detail="+sample; to send the data.
Use encodeURIComponent to escape a string for inserting into a URI.
In my test.php, I use $detail = $_GET["detail"]; and echo $detail; to print it.
If you are printing it into HTML then use htmlspecialcharsto make it safe.
If you are printing it into JavaScript then use json_encode to make it safe.
You're overdoing the escape characters:
var sample = (get the string from a api call).replace(/'/g,"\\'");
Is enough, a single quote, delimited by double quotes needn't be escaped, so just escape one backslash.A sidenote, though: if the string you're checking is a return value, the single quotes shouldn't be a problem (if they are, the api code would break before returning the string). If you really really really want to be extra-super-mega-sure and the string is long:
var sample = (get the string from a api call).split('\'').join('\\\'');
//or (to avoid confusion with all that escaping
var sample = (get the string from a api call).split("'").join("\\'");
Splitting is faster for longer strings (not short strings, as the array constructor is called, an array-object is created, looped,...)
Presumably the problem is with (get the string from a api call). If you have some server-side code (PHP?) like this:
var sample = <?php echo $mystring ?>.replace(…);
…and it produces output sent to the browser like this:
var sample = 'my dad's car'.replace(…);
…then your server-side code has produced syntatically-invalid JavaScript that cannot be fixed by more JavaScript. Instead you need to fix it on the server, something like:
var sample = <?php echo json_encode($mystring); ?>;
It's impossible to help you further without your actual code details, however.
Basically I'm sending a formatted string to a PHP script via POST
So say I have the string... "abcdef$ghikl" it will recognize $ghikl as a variable...
Is there any ways to tell PHP that no variables exist within this string?
I know how to hard code it, you just use "'", but since the string is being sent to the script, I don't know what to do...
Thanks guys
For the scope of the question, all the code that's really needed is this:
$string = $_POST['string'];
// a couple strcmp's here, just to see if the string == ""
$array = explode("+", $string);
Try escaping the $
"abcdef\$ghikl"
PHP won't see that as a variable unless you eval() it. Can you show us your code?
What series of steps would be reqired to safely encode and
pass a string from a html href using javascript to construct the link to a php program.
in javascript set up URL
// encodes a URI component.
path = "mypgm.php?from=" + encodeURIComponent(myvar) ;
in php:
// get passed variables
$myvar = isset($_GET['myvar']) ? ($_GET['myvar']) : '';
// decode - (make the string readable)
$myvar = (rawurldecode($myvar));
// converts characters to HTML entities (reduce risk of attack)
$myvar = htmlentities($myvar);
// maybe custom sanitize program as well?
// see [http://stackoverflow.com/questions/2668854/php-sanitizing-strings-to-make-them-url-and-filename-safe][1]
$myvar = sanitize($myvar);
I think the first two lines should be fine. You would use htmlentities if and when you have to output it as text.
Looking at your code, all you really need is this:
$myvar = !empty($_GET['myvar']) ? $_GET['myvar'] : '';
Beyond that, PHP automatically URL decodes. I personally prefer to do my htmlentities() or htmlspecialchars() when I go to output data, i.e.:
<?php echo htmlentities($mydata); ?>
The only other time you specifically need to escape or sanitize data is if you're building a SQL query:
$data = mysql_real_escape_string($mydata);
$query = "SELECT * FROM table WHERE stuff = '$mydata'";
That will prevent SQL injection. Unless you're formatting user input or performing validation, it's not absolutely necessary to do any other kind of sanitization.
Hope this helps!
I want to do define the following variable $url
$url = www.example.com/$link;
where $link is another predefined variable text string e.g. testpage.php
But the above doesn't work, how do I correct the syntax?
Thanks
Try this:
$url = "www.example.com/$link";
When string is in double quotes you can put variables inside it. Variable value will be inserted into string.
You can also use concatenation to join 2 strings:
$url = "www.example.com/" . $link;
Hate to duplicate an answer, but use single quotes to prevent the parser from having to look for variables in the double quotes. A few ms faster..
$url = 'www.example.com/' . $link;
EDIT: And yes.. where performance really mattered in an ajax backend I had written, replacing all my interpolation with concatenation gave me a 10ms boost in response time. Granted the script was 50k.
Needs double quotes:
$url = "www.example.com/$link";
Alternate way:
$url = "www.example.com/{$link}";
$url = "www.example.com/$link";
It'd be helpful if you included the erroneous output, but as far as I can tell, you forgot to add double quotes:
$url = "www.example.com/$link";
You will almost certainly want to prepend "http://" to that url, as well.