Escape quotes when building javascript from php - php

Basically, I'm taking user input and passing it to a javascript function in a page from php. But because the user use's apostrophes, I'm getting errors. What's the proper escape function in php to use on a variable that will be surrounded by quotes. IE:
Some php:
$userString = "Joe's Pizza";
// escape here
echo "<script type=\"text/javascript\">myFunction('$userString');</script>";
Thanks much!

Wrap it in an object/associative array and use json_encode.
$array = array('data' => $userString);
$encoded_array = json_encode($array);
echo "<script type=\"text/javascript\">myFunction($encoded_array);</script>";
myFunction could look like:
function myFunction(obj)
{
var data = obj.data;
...
}
This also allows you to easily make the object more complex if needed.

addslashes; e.g.
$userString = addslashes("Joe's Pizza");
print '<script type="text/javascript">myFunction('$userString');</script>";;

Related

Echoing JSON Data in php

Im trying to echo some JSON Data. The problem is the data contains variables but my code isn't putting the variables into the string.
Heres my code:
$status = $row['Status'];
$priority = $row['Priority'];
echo '{"status":"$status","priority":"$priority"}' ;
this php is echoing
{"status":"$status","priority":"$priority"}
when I need to echo
{"status":"Completed","priority":"High"}
for example. How can I fix this?
Just use json_encode function
echo json_encode($row);
json_encode($row)
Will give you the desired output.
The problem here is that PHP does not substitute variables in single quotes, only in double quotes (see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double).
For example:
$test = "a";
echo 'This is $test test and'.chr(10);
echo "this is $test test.".chr(10);
/*
Creates the following output:
This is $test test and
this is a test.
*/
Note: chr(10) creates the new line.
And the solution to your problem is to use json_encode() and json_decode() as other people have suggested already.
http://php.net/manual/en/function.json-encode.php
The problem is in your single quotes, PHP get all vars inside as strings, so break the string as follow:
echo '{"status":"'.$status.'","priority":"'.$priority.'"}' ;
On top of that, you can use json_encode() in order not to build your JSON object manually.

How to dynamically pass condition of if statement

I am in a situation where I'll get comparison string in a variable, and I want to use that variable in IF
$xyz = '$abc<200'; // Dummy Dynamic Text
if($xyz) { // It should execute like if($abc<200)
echo 'you are dynamic';
}
In the example above the comparison string coming dynamically in $xyz variable and I want to put that variable in if condition, How do I do that?
You cannot use quotes as it is making the string out of it. Do it this way:
$xyz=($abc<200); //or, as well, $xyz=$abc<200
if($xyz) {
echo 'you are dynamic';
}
If however you want to keep that condition text in string, you could use eval:
$xyz='$abc<200';
if(eval("return $xyz;")) {
echo 'you are dynamic';
}
Eval is sometimes disabled. This is for security reasons. Often with suhosin. Eval can be evil! Think about code injections.
You could try to use an anonymous function.
<?php
$func = function($abc) {
return $abc<200;
};
if ($func($abc)) {
// great
}

jQuery to PHP - serialized strings

I'm currently AJAX'ing a login form.
var data = $(this).serialize();
This is the data I'm sending, I get this with PHP using Codeigniter like so:
$ajax = $this->input->post('data');
This returns username=john&password=doe as you'd expect.
How do I turn that into an array? I've tried doing unserialize() and I get null.
I believe you can use PHP's parse_str() function: http://php.net/manual/en/function.parse-str.php
<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>
Using your code it would be:
parse_str($this->input->post('data'), $ajax);
echo $ajax['username'] . "/" . $ajax['password'];
Short answer is with parse_str;
parse_str($ajax, $array);
$array === array('username'=>'john', 'password'=>'doe');
However, the way you send your ajax data is a bit odd. Why are you serializing to a formencoded string and sending that string as a value to the 'data' parameter? Why don't you just send it directly? Then you could use $this->input->post('username') === 'john' without the extra level of deserializing.
For example, do this:
$.post(url, $(form).serialize());
instead of this (which you seem to be doing:
$.post(url, {data:$(form).serialize()});
Use parse_str()
http://php.net/manual/en/function.parse-str.php
$parameters = array();
foreach ( explode( '&', $ajax ) as $parameterAndValue ) {
list ( $parameter, $value ) = explode( '=', $parameterAndValue );
$parameters[$parameter] = $value;
}
I guest we could use normal request, it's defend on the request type from ajax, using GET or POST, and then in the php we could use like normal post, like $_POST['username'] or $_GET['username'] we don't have to use function to unserialize that, and for validation using CI just call like normal use, $this->input->post('username'),am i wrong ?
Simply use as follows
<?php $username = $this->input->post('username');?>
<?php $password= $this->input->post('password');?>
You can do anything with above variables

Php variable in a variable

I have a piece of code that looks like this:
$result = mysql_query($queryc) or die(mysql_error());
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo $row['$field'];
}
}
Say that code was in a function and I wanted to pass $field to the $row[''] how would I accomplish that?
In other words I'm attempting to use $row['$field']; and $field is defined elsewhere
suppose you have this function definition:
function foo($field) {
// from that code you have given
....
echo $row[$field]; // no need of the quotation marks around $field
....
}
You'd not put any quotes around $field... like this:
echo $row[$field];
Variables are not expanded in single quotes; they are only expanded in double quotes or in the heredoc syntax:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
So either use double quotes or, even better, just omit them:
$row[$field]
Single quotes inhibit variable substitution.
echo $row["$field"];
or just
echo $row[$field];
The latter is highly recommended as it does not require PHP to parse $row["$field"] into $row[$field]. Saves you some microtime in each iteration.

How to extract two variables from this string in PHP

I have a string like this :
oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc
How can I extract the two variables oauth_token and oauth_token_secret from the about string using PHP
NOTE: this is not coming from the URL( we can do that using $_GET)
Thank YOU
Use parse_str() for parsing query string parameters.
// Extract into current scope, access as if they were PHP variables
parse_str($str);
echo $oauth_token;
echo $oauth_token_secret;
// Extract into array
parse_str($str, $params);
echo $params['oauth_token'];
echo $params['oauth_token_secret'];
You may wish to urldecode() the variables after you've extracted them.
try this
$text = "oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc"
;
$i=explode('&',$text);
$j=explode('=',$i[0]);
$k=explode('=',$i[1]);
echo $j[0]."<br>";
echo $j[1]."<br>";
echo $k[0]."<br>";
echo $k[1]."<br>";
1, split the two parts of the $string,
$str_array = explode('&',$string);
2, get the part after the "=" sign, so for the oauth_token part:
$oauth_token_array = explode('=',$str_array[0]);
$oauth_token = $oauth_token_array[1];
EDIT: ignore this, it's definitely verbose. BoltClock's the solution.
The best way (most reusable) is to use a function which returns an array similar to $_GET.
edit There is already a function for this: http://www.php.net/manual/en/function.parse-str.php This will work with array get values too.
$values = array();
parse_str($query_strng, $values);
Quite an ugly function, why can't it just return the array of values. It either stuffs them into individual variables or you need to pass in a reference. Come on php, you can do better. /rant

Categories