Loss special characters while converting session var to javascript var - javascript

I put an array containing name of cities into a session variable.
Example of array :
Saint-Tite, QC
Saint-Émile, QC
Sainte-Adèle, QC
Sainte-Agathe-des-Monts, QC
When I converting this session variable array into a javascript array
var availableTags = <?php echo json_encode($_SESSION['villeDB']) ?>;
The array will look like this now :
Saint-Tite, QC
null
null
Sainte-Agathe-des-Monts, QC
How can I keep special characters while converting my array of cities name ?

json_encode requires that strings be encoded in UTF8.
Personally, I like to program in a single-byte character set. It's just so much less of a headache in general. But in this case, I have a helper function:
function json_output($json) {
if( is_array($json))
array_walk_recursive($json,function(&$a) {if(is_string($a)) $a=utf8_encode($a);});
elseif( is_string($json))
$json = utf8_encode($json);
$j = json_encode($json,true);
return $j;
}

Related

Detect specific info from variable [duplicate]

I have an HTML form field $_POST["url"], having some URL strings as the value.
Example values are:
https://example.com/test/1234?email=xyz#test.com
https://example.com/test/1234?basic=2&email=xyz2#test.com
https://example.com/test/1234?email=xyz3#test.com
https://example.com/test/1234?email=xyz4#test.com&testin=123
https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com
etc.
How can I get only the email parameter from these URLs/values?
Please note that I am not getting these strings from the browser address bar.
You can use the parse_url() and parse_str() for that.
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
If you want to get the $url dynamically with PHP, take a look at this question:
Get the full URL in PHP
All the parameters after ? can be accessed using $_GET array. So,
echo $_GET['email'];
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don't like polluting the current context, so providing a second parameter puts all the variables into an associative array.
$url = "https://mysite.com/test/1234?email=xyz4#test.com&testin=123";
$query_str = parse_url($url, PHP_URL_QUERY);
parse_str($query_str, $query_params);
print_r($query_params);
//Output: Array ( [email] => xyz4#test.com [testin] => 123 )
As mentioned in another answer, the best solution is using parse_url().
You need to use a combination of parse_url() and parse_str().
The parse_url() parses the URL and return its components that you can get the query string using the query key. Then you should use parse_str() that parses the query string and returns
values into a variable.
$url = "https://example.com/test/1234?basic=2&email=xyz2#test.com";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // xyz2#test.com
Also you can do this work using regex: preg_match()
You can use preg_match() to get a specific value of the query string from a URL.
preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // xyz2#test.com
preg_replace()
Also you can use preg_replace() to do this work in one line!
$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// xyz2#test.com
Use $_GET['email'] for parameters in URL.
Use $_POST['email'] for posted data to script.
Or use _$REQUEST for both.
Also, as mentioned, you can use parse_url() function that returns all parts of URL. Use a part called 'query' - there you can find your email parameter. More info: http://php.net/manual/en/function.parse-url.php
You can use the below code to get the email address after ? in the URL:
<?php
if (isset($_GET['email'])) {
echo $_GET['email'];
}
I a created function from Ruel's answer.
You can use this:
function get_valueFromStringUrl($url , $parameter_name)
{
$parts = parse_url($url);
if(isset($parts['query']))
{
parse_str($parts['query'], $query);
if(isset($query[$parameter_name]))
{
return $query[$parameter_name];
}
else
{
return null;
}
}
else
{
return null;
}
}
Example:
$url = "https://example.com/test/the-page-here/1234?someurl=key&email=xyz5#test.com";
echo get_valueFromStringUrl($url , "email");
Thanks to #Ruel.
$web_url = 'http://www.writephponline.com?name=shubham&email=singh#gmail.com';
$query = parse_url($web_url, PHP_URL_QUERY);
parse_str($query, $queryArray);
echo "Name: " . $queryArray['name']; // Result: shubham
echo "EMail: " . $queryArray['email']; // Result:singh#gmail.com
A much more secure answer that I'm surprised is not mentioned here yet:
filter_input
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.
I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:
$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
$uri = $_SERVER["REQUEST_URI"];
$uriArray = explode('/', $uri);
$page_url = $uriArray[1];
$page_url2 = $uriArray[2];
echo $page_url; <- See the value
This is working great for me using PHP.
In Laravel, I'm using:
private function getValueFromString(string $string, string $key)
{
parse_str(parse_url($string, PHP_URL_QUERY), $result);
return isset($result[$key]) ? $result[$key] : null;
}
A dynamic function which parses string URL and gets the value of the query parameter passed in the URL:
function getParamFromUrl($url, $paramName){
parse_str(parse_url($url, PHP_URL_QUERY), $op); // Fetch query parameters from a string and convert to an associative array
return array_key_exists($paramName, $op) ? $op[$paramName] : "Not Found"; // Check if the key exists in this array
}
Call the function to get a result:
echo getParamFromUrl('https://google.co.in?name=james&surname=bond', 'surname'); // "bond" will be output here

echo statement not working? Seems to be formatted correctly

I'm creating a object in javascript echo'd by PHP, the syntax seems to be correct but it is giving me an error.
The variables I am passing to the object are strings and I have tried putting them in quotes, etc. I also tried creating a JS function to do this and it had similar results.
<?PHP
$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.
echo '<script type="text/javascript">';
while($TED = $TEDS->fetch_assoc())
{
echo 'var pos = {lat: '.$TED['latitude'].', lng: '.$TED['longitude'].'};'; //THIS ECHO STATEMENT IS THE ONE GIVING ME PROBLEMS.
}
echo '</script>';
?>
It's highly likely that one of your latitude values does not have a value, causing it to print something like the following:
var pos = {lat: , lng: 1234}
Without a value to go with the property, the JavaScript parser would unexpectedly see the comma. This would greatly explain an unexpected comma syntax error.
So, first of all, you do NOT manually construct JSON. PHP has json_encode() that converts PHP arrays into JSON. Use that to correctly build JSON for you.
Next, your code prints pos repeatedly, overriding the previous values. If you only care about the last value, don't print everything. If you do care about all the values, store them in an array:
<?php
// Get your TEDS
$teds = $TEDS->fetch_assoc();
// Using array_map to convert the items from latitude-longitude to lat-lng.
$teds_array = array_map(function($ted) {
return ['lat' => $ted['latitude'], 'lng' => $ted['longitude']];
}, $teds);
// Serialize to JSON
$teds_json = json_encode($teds_array);
?>
// positions will be an array of objects with lat-lng.
var positions = <?php echo $teds_json; ?>
Lastly, be careful of XSS. Do not just print unsanitized values like above. Make sure your data is clean before printing it on the page.
i would try to write the full text, after the loop. This way you can build a full json array:
<?PHP
$TEDS = $db->query("
SELECT a.*
FROM TEDS a
");
//Add each TED location into a javascript array.
echo '<script type="text/javascript">';
$text = 'var positions = [';
while($TED = $TEDS->fetch_assoc()) {
$text .= '{lat: '.$TED['latitude'].', lng: '.$TED['longitude'].'},';
}
// remove last comma
$text = substr($text,0 , strlen($text)-2);
$text .= '];'
echo $text;
echo '</script>';
?>
Another way would be to just json_decode($TED).

Get variable value by name from a String

This is for server side, regardless of client.
$data= file_get_contents('textfile.txt');
The textfile.txt contains
var obTemperature = "55";
var obIconCode = "01";
What can I enter so I can get echo obTemperature value of 55?
is there not a simple php interface to read var values by name?
please no over complicated /half answers /trolling,
You would be better off explaining what you want to do in general, but if you are tied to this file format and the format is consistent:
$data = str_replace('var ', '$', $data);
eval($data);
echo $obTemperature;
echo $obIconCode;
However, any other types of JavaScript code will cause a parse error.
Also, you can treat it as an ini file:
$data = str_replace('var ', '', parse_ini_string($data));
echo $data['obTemperature'];
Or just:
$data = parse_ini_string($data);
echo $data['var obTemperature'];
You can use a regular expression:
preg_match('/var obTemperature = "(\d+)";/', $data, $match);
$temperature = $match[1];
DEMO

Rawurlencode not Using Value of Variable but Script that Generated the Value

I'm trying to do a rawurlencode, but it is not working as I though it would do. The data I'm trying to encode is coming from javascript and I stored the information on a variable. The value of the variable seems to be correct (did echo in a couple of places) everywhere except after the encoding. It seems that instead of using the value of the variable for the encoding is using the script that generated the value and encoding that.
<?php
//getting the author name using javascript
$author1="
<script type=\"text/javascript\">
jsauthor1 = document.getElementsByTagName(\"span\")[8].innerText;
document.write(jsauthor1);
</script>";
// checking Author name is correct
echo $author1." : Author name after Javascript extraction". "<br>";
$params = array(
"Service" => "AWSECommerceService",
"Operation" => "ItemSearch",
"AWSAccessKeyId" => "AKIAJSGKPYO6HFNCED7A",
"AssociateTag" => "hobbytryout0a-20",
"SearchIndex" => "Books",
"Sort" => "price",
"Author" => $author1,
);
// checking that array have correct values (taking the value of "$author" correctly)
echo $params[Author]." : Author name after creating array using variable <br>";
// convert $params[Author] to a String to test the encoding
$test = (string)$params[Author];
echo $test." : Author name after creating string from array"."<br>";
echo rawurlencode($test)." : Author name after rawurlencode"."<br>";
?>
This is what I get:
Jules Verne : Author name after Javascript extraction
Jules Verne : Author name after creating array using variable
Jules Verne : Author name after creating string from array
%20%0A%20%20%20%20%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20%20%20%20jsauthor1%20%3D%20document.getElementsByTagName%28%22span%22%29%5B8%5D.innerText%3B%0A%20%20%20%20document.write%28jsauthor1%29%3B%0A%20%20%20%20%3C%2Fscript%3E
: Author name after rawurlencode
Shouldn't it be Jules%20Verne ?
Thanks
To encode the Javascript value, call encodeURIComponent from the Javascript:
$author1="
<script type=\"text/javascript\">
jsauthor1 = document.getElementsByTagName(\"span\")[8].innerText;
document.write(encodeURIComponent(jsauthor1));
</script>";

Japanese/korean into MySQL table

i am trying to store some info in my db. One of the fields are Japanese names. I am getting a error:
Warning: #1366 Incorrect string value: '\xE3\x83\xA9\xE3\x83\x87...' for column 'japan-name' at row 1
So i cannot chnage the charset of my db. Can i use PHP or Javascript to convert Japanese/Korean to something else, and them when i go read it, reconvert to Japanese/Korean?
PHP offers the base64_encode() and base64_decode() functions. They are fast, and impose a storage penalty of about 33%. You can use the first to convert your utf-8 east Asian text to what looks like gibberish in ASCII before you store it in your table. The second will convert it back after you retrieve it.
Here's an example:
$jp = " 私はガラスを食べられます。それは私を傷つけません。";
$jpe = base64_encode ($jp);
$jpd = base64_decode ($jpe);
After you run these lines, the $jpe variable has the value
IOengeOBr+OCrOODqeOCueOCkumjn+OBueOCieOCjOOBvuOBmeOAguOBneOCjOOBr+engeOCkuWCt+OBpOOBkeOBvuOBm+OCk+OAgg==
That stores just fine in an ASCII or Latin-1 column.
utf-8 saves the unicode data in table... but other way is to encode and save and then decode and display
update:
searched on web and found answer at How do you Encrypt and Decrypt a PHP String?
define("ENCRYPTION_KEY", "!##$%^&*");
$string = "This is the original data string!";
echo $encrypted = encrypt($string, ENCRYPTION_KEY);
echo "<br />";
echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
/**
* Returns an encrypted & utf8-encoded
*/
function encrypt($pure_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
return $encrypted_string;
}
/**
* Returns decrypted original string
*/
function decrypt($encrypted_string, $encryption_key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
return $decrypted_string;
}

Categories