I have problems with treatment of Post. I received a string with the symbol '%' and two letters together, like 'Geci%de', but on PHP the var_dump I receive a different string, like 'Geci�', if try to use utf8_encode and utf8_decode, however the error continued, the strings resulted were 'GeciÞ' and'Geci?'. How is the better way to convert in the orignal string? I need to use in postgreSQL, it will be in select.
It is uses to treatment:
$data = strip_tags($data);
$data = trim($data);
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data;
$data = preg_replace("#(--|\|)#s", "", $data);
$data = urldecode($data); // especific to Ajax
return utf8_decode($data);
Related
I have Decimal data type in my database with value 0.00 but in JSON result is .00, How I can convert so i can still get 0.00 in result ?
I working in Jquery.. Thanks
This my code
<?php
include "../../../config/config.php";
$kd_entitas=$_POST['kd_entitas'];
$tglAwal = $_POST['tglAwal'];
$tglAkhir = $_POST['tglAkhir'];
$con = sqlsrv_connect(serverNameAST,$connectionInfoAST) or die('Unable to Connect');
if( $con === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
else{
//$sql = "SELECT SELECT #rownum := #rownum + 1 AS urutan, t.* FROM SYS_DEPT t, (SELECT #rownum := 0) r";
$sql="[Daily_report_r] '$kd_entitas','$kd_entitas','$tglAwal','$tglAkhir'";
$result = sqlsrv_query($con, $sql, array(), array( "Scrollable" => 'static' ));
$data = array();
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$data[] = $row;
}
$datax = array('data' => $data);
echo json_encode($datax);
}
?>
Result JSON in field oustand
Result from my database sql server
You have two problems here:
When you're getting the data from database all values will be strings. If you want a specific number to be a double then you have to explicitly cast it to a double.
If you want to preserve zero fraction in json you have to use JSON_PRESERVE_ZERO_FRACTION flag in json_encode. See http://php.net/manual/en/function.json-encode.php for details.
But this solution will preserve only one zero and will only work on numbers of type double. If you want to have more zeros after coma you have to leave the number in the string and handle yourself.
If the number from the database is returned without the fraction part then check your field type or field precision.
I have a very simple PHP array
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
PHP
If I dd($array); out I got
array:3 [▼
"a" => "1"
"b" => "2"
"c" => "3"
]
If I decode dd(json_encode($array));, I got this
"{"a":"1","b":"2","c":"3"}"
JS
I want to be able to access this variable in my Javascript, So I've tried
1
console.log($array);
I got
$array is not defined
2
I'm using Laravel. {{ }} == echo
console.log('{{$array}}');
I got
500 Internal Error
htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)
3
console.log('{{ json_encode($array)}}');
I got
The page to load, but the data is very bad looking
{"a":"1","b":"2","c":"3"}
4
console.log(JSON.parse('{{ json_encode($array)}}'));
I got
Uncaught SyntaxError: Unexpected token & in JSON at position 1
5
console.log(JSON.parse('{{ json_decode($array)}}'));
I got
json_decode() expects parameter 1 to be string, array given
6
console.log('{{ json_decode($array)}}');
I got
json_decode() expects parameter 1 to be string, array given
GOAL
I just want to be able to access my array as Javascript Array or JSON in the Javascript.
Can someone please fill me in on this ?
In Blade, {{ $variable }} will output an escaped version of the string, passed through htmlentities() to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!} for that:
console.log({!! json_encode($array) !!});
You don't need to add quotes around it, json_encode() outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.
In Laravel you can use {!! !!} to skip entity escaping
console.log({!! json_encode($array) !!});
Just echo it as json data and use it in javascript.
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = <?=json_encode($array);?>;
alert(jsArr);</script>
EDIT because of clarification that you're using blade. Then it should be:
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = {!! json_encode($array) !!};
alert(jsArr);</script>
{ ... } is an escaped version of your string. But you need the unescapt string. This can be achieved by using {!! ... !!}.
First, you have to understand that PHP run on server side and javascript on client side, as PHP make the response you should print a script like this:
echo "<script>
var sheison = JSON.parse(".dd(json_encode($array)).");
console.log(sheison);
</script>";
I didn't test the code, is just the idea.
I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).
According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);
You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);
I have a PHP file that encodes Json data and when i view the JSON output when its a single data block i get a valid json code syntax this is an example :
single data block
But when the JSON results in a multiple data block it generates an invalid JSON format like this: multiple data blocks
This is my PHP code:
<?php
header('Content-Type: application/json; charset=utf-8', true,200);
DEFINE('DATABASE_USER', 'xxxxx');
DEFINE('DATABASE_PASSWORD', 'xxxxxx');
DEFINE('DATABASE_HOST', 'xxxxxxxxxxx');
DEFINE('DATABASE_NAME', 'xxxxxxxx');
// Make the connection:
$dbc = #mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$dbc->set_charset("utf8");
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){//IF the url contains the parameter "keyword"
$keyword = trim($_GET['keyword']) ;//Remove any extra space
$keyword = mysqli_real_escape_string($dbc, $keyword);//Some validation
$query = "select name,franco,alpha,id,url,songkey,chord from song where name like '%$keyword%' or franco like '%$keyword%'";
//The SQL Query that will search for the word typed by the user .
$result = mysqli_query($dbc,$query);//Run the Query
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$data = array();
$data = $row;
echo $_GET[$callback]. ''.json_encode($data).'';
}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';//No Match found in the Database
}
}
}else {
echo 'Parameter Missing in the URL';//If URL is invalid
}
?>
It is because you are JSON-encoding a single line of the result set at at time. This is not a valid JSON structure if the calling client is expecting such.
Likely, you will want to put each row as an entry in an array, and then JSON-encode and echo the resulting array.
Like this:
if($result){//If query successfull
if(mysqli_affected_rows($dbc)!=0){//and if at least one record is found
$array = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ //Display the record
$array[] = $row;
}
echo json_encode($array);
}
}
This is the problem I get, for example, when an user inputs <script>top.location.href=’http://www.google.nl’;</script>
I want my application to echo it as plain text. Now, this actually works with
htmlspecialchars()
This example works for me:
$test = "<script>top.location.href=’http://www.google.nl’;</script>";
echo htmlspecialchars($test);
But, when the user submits the form, the data goes to my DB and then returns to a 'dashboard'.
The value is now ''.
Is there a way how I can save the data safe into my DB?
I add the values into the DB for my C# application in this way via SDK:
$onderwerp = htmlspecialchars(stripslashes(trim($_POST['onderwerp'])), ENT_QUOTES,'UTF-8',true);
$omschrijving = htmlspecialchars(stripslashes(trim($_POST['omschrijving'])), ENT_QUOTES,'UTF-8',true);
$im = array('description' => mysql_real_escape_string($onderwerp),
'message' => mysql_real_escape_string($omschrijving) ,
'relation' => $_SESSION['username'],
'messageType' => 70,
'documentName' => $_FILES["file"]["name"],
'documentData' => base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$imresponse = $wcfclient->CreateInboundMessage($im);
echo $imresponse->CreateInboundMessageResult;
And then call them at my dashboard in this way:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $calls){
echo $calls->Description;
}
can you please check mysql-real-escape-string
mysql_real_escape_string() :
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
Also CHeck SQL Inject :SQL Injection
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Ouput :
Escaped string: Zak\'s and Derick\'s Laptop
Yes, read about mysqli_real_escape_string.