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.
Related
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 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);
I need to update a database using AJAX so don't have my page be reloaded. I can't find what's wrong and unexpectedly I get a success message back but a database doesn't get updated.
JS:
$('.start-time-class').submit(function() {
var startTime = "11:30";
var projectID = 17;
var userID = 2;
$.ajax({
url:'functions/starttime.php',
data:{startTime:startTime,projectID:projectID,userID:userID}, // pass data
dataType:'json',
success:function(){
// something
}
});
});
PHP:
$con = mysqli_connect('localhost','smt','smt','smt');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$startTime = $_GET['startTime'];
$projectID = $_GET['projectID'];
$userID = $_GET['userID'];
mysqli_select_db($con,"ajax_demo");
$sql = "INSERT INTO 'uc_project_time'('userID', 'projectID', 'startTime') VALUES (". $userID .", ". $projectID .", ". $startTime .")";
$result = mysqli_query($con,$sql);
mysqli_close($con);
Don't use quotes for table or column names
Use:
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('$userID', '$projectID', '$startTime')";
or
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('".$userID."', '".$projectID."', '".$startTime."')";
And do sanitize your code:
How can I prevent SQL injection in PHP?
You don't use quotes(single or double) in SQL for table or column names. You could use backticks(`), though not necessary(in your circumstance), it can be required in some situations.
When to use backticks(`)?
Firstly, you'd only use them in MySQL, as SQL Server and T-SQL use square brackets [] to denote identifiers.
If you were using spaces or keywords in your column or table names, you would need backticks. This would instruct the parser to parse the column or table name as a literal string.
To illustrate, if you had a table called 'badly named table'.
This wouldn't work
SELECT FROM badly named table...
This would work
SELECT FROM `badly named table`...
To conclude, backticks are useful if you have a bad table or column naming convention.
SQL Injections
Also, as #Fred -ii- said you're currently vulnerable to SQL Injections. If you're using PHP with PDO enabeled, you could use the following code (with prepared statements) protect against SQL injections and ensure that malicious actions can't be carried out on your database.
$con = new PDO('mysql:host=localhost; dbname= name_of_db', 'name_of_user', 'password_of_user');
$sql = $con->
prepare("
INSERT INTO uc_project_time userID, projectID, startTime VALUES (:userID, :projectID, :startTime)
");
$sql->bindParam(':userID', $userID,':projectID', $projectID,':startTime', $startTime, PDO::PARAM_STR);
$sql->execute();
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
Or, If you want to continue using MySQLi, you could use their version of prepared statements. That said, I recommend PDO for the reasons illustrated here.
ChkNewRspLive.php
<?php
$query3 = "SELECT msgid, id FROM rspnotificationlive WHERE username='{$username1}' ORDER BY id LIMIT 99";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
$numrspmsg = mysql_num_rows($result3);
echo $numrspmsg . "|";
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
echo $rspmsgid . ", ";
}
?>
index.html
<script type="text/javascript">
$.get("ChkNewRspLive.php?username=" + username, function(newrspmsg){
var mySplitResult = newrspmsg.split("|");
var rspMsgCount = parseFloat(mySplitResult[0]);
var rspMsgids =(mySplitResult[1]);
var Msgids = ??//how to get this result from ChkNewRspLive.php ?
});
</script>
As you can see, I used "|" to separate $rspmsgid and $numrspmsg. I also use "," to separate multiple $rspmsgid. How if I want to separate another data $msgid? How to do that?
If I use | to separate $rspmsgid and $msgid, there will be many sign of | because they both are in the while loop.
JSON encode your content.
In your php, change your code to something like:
$json = array();
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
$json[] = array($rspmsgid,$msgid);
}
echo json_encode($json);
and then use $.getJson in your javascript.
You won't have to define the number of mysql_rows either, as you can just get that in javascript by using .length on the json data.
edit and escape your string before using it in your SQL!
You are already using the .split() method to seperate the other string. Apply it to the other part and let it split by ", " or just use another | instead of the , and you will have it split into three parts instead of two.
However I suggest you have a look at JSON. This should be the better solution if it gets more complicated.