.
$row['NO'] = ''.$row['abc'].''
In the above statement, what is the meaning of escaping the values in that manner such as '\'. How can i learn this?
In the above statement i want to replace the php variable $row['TEST2'] with a static value 'OPEN', but i am getting a syntax error.
$row['NO'] = ''.$row['abc'].'';
Because the escaping is very confusing it might be better to use HEREDOC:
$row['NO'] =<<<EOC;
$row[abc]
EOC;
More about strings in the manual (including escaping and heredoc).
PS: Do not use $_REQUEST. Instead use $_GET or $_POST (the one that is appropriate here.)
In the above statement what is the
meaning of escaping the values in that
manner suchas '\'.How can we learn
this
Have a look at this tutorial :)
PHP and Escaping
For the error, make sure that you escape the strings correctly.
This is what I would suggest that you do instead of escaping + concatenating strings :
$html = "%s";
$row['NO'] = sprintf($html,
$row['bcd'],
$row['gfh'],
$row['test2'],
$_REQUEST['test1'],
$row['abc']
);
And then replace whatever you need to replace... Read the manual about sprintf for more details.
Also, if any argument after $html contain ' chars, you must call addslashes on those arguments.
** UPDATE **
About $_REQUEST, read here why it is not recommended to use it.
Related
i use this code to export data from table ,but if its have url in db its give wrong format
ex {"site_url":"tiger","site_name":"hassan:\/\/tiger-sat.net\/nn.mp4"}
should be hassan://tiger-sat.net/nn.mp4
any know how to fix please ,,,
<?php
//PDO is a extension which defines a lightweight, consistent interface for accessing databases in PHP.
$db=new PDO('mysql:dbname=db;host=localhost;','root','pass');
//here prepare the query for analyzing, prepared statements use less resources and thus run faster
$row=$db->prepare('select * from channel');
$row->execute();
$json_data=array();
foreach($row as $rec)
{
$json_array ['site_url']=$rec ['site_url'];
$json_array['site_name']=$rec['site_name'];
//here pushing the values in to an array
array_push($json_data,$json_array);
}
//built in PHP function to encode the data in to JSON format
echo json_encode($json_data);
?>
It's not wrong . json_encode function is just escape the data and it's 100% valid and should not create any difference and it's even better to have escaped data. but in case you don't want to escape the data and have php > 5.4 or more you can use
echo json_encode($json_data, JSON_UNESCAPED_SLASHES);
instead.
But in case you have a php < 5.4 you can use the following code instead :
$encoded = json_encode($json_data);
$unescaped = preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
}, $encoded);
echo $unescaped;
Another alternative is to use :
echo str_replace('\\/', '/', json_encode($json_data));
I would recommend to update your stack and get on a newer PHP version.
If your just needing to remove the extra slashes from the URL itself, then try stripslashes()
$example = 'hassan:\/\/tiger-sat.net\/nn.mp4';
echo stripslashes($example);
Result:
hassan://tiger-sat.net/nn.mp4
Another Option
$example = 'hassan:\/\/tiger-sat.net\/nn.mp4';
echo str_replace ( '\\' , '' , $example );
Result:
hassan://tiger-sat.net/nn.mp4
However, stripslashes does this exact same thing and would be the better option, it is what the function was made for, stripping backslashes..
If your needing to remove slashes throughout the whole JSON, then I would update PHP and use JSON_UNESCAPED_SLASHES.
You need to be careful if you aren't going to escape the slashes, they are there for a reason. If you are taking data from the JSON and using it in an SQL query, you could open yourself up to an SQL injection. So you would (and should) be using sanitized queries by using MySQLi or PDO, and prepared statements.
Depending on the use and need, I would not use JSON_UNESCAPED_SLASHES and strip the slashes when/where needed.
Last Note: preg_replace, and other forms of regular expressions, should be a last resort... Usually, they are for things way more trivial than simply removing a \ from strings. If you just need to remove a character (ie: ) then there are better ways than regular expressions.
Trying to save serialized string to SQL, but then i am having problems with unserializing it because of quotes.
Example, string is "te'st", after serialize we have
s:5:"te'st";
But to save it to SQL we need to add slashes, and i am doing
serialize(addslashes($string))
after this, in our MySQL db we have
s:6:"te'st";
And this is the problem. s:6 means we have 6 symbols string, but our "te'st" is only 5, so when we trying to unserialize it, we getting error.
How to solve it? Tried htmlspecialchars and mysql_real_escape_string
Update:
How i use mysql_real_escape_string
mysql_query("INSERT INTO `table`(`string`) VALUES ('" . serialize(array('iId' =>$aSqlResult['typeID'], 'sName' => mysql_real_escape_string($sScanResultLine))) . "')");
You should pass the data through the escape function after the serialization, not before - which is what you are doing now.
$serialized = mysql_real_escape_string(serialize($data));
Use a parameterised query with PDO or MySQLi and you can forget about the escaping altogether.
You're making a mistake I've seen many making. A bit of a fundamental misunderstanding of how escaping functions and should be used.
You cannot simply chain escape functions and end up with something that's perfect for any context. Your mistake is simple..
You're doing two things:
Serializing an object ( a string in this case )
Saving that into the database.
So before you save it to the database, you must make sure that your value is properly escaped. DO THIS WITH MYSQLI! The mysql_ functions are dead.
The equivalent is mysqli::real_escape_string.
But most importantly.. (sorry for dragging this on)..
serialize modifies the output, it can return a whole bunch of things.. quotes, 0x00's and this is not allowed in mysql queries.
So real_escape_string must obviously be the last step! First serialize, and the escape the output of that function. You did the exact opposite.
In your case the mysql_real_escape_string() is the way to go. It have to work, unless you did it somehow wrong (note: you need to be connected to DB before calling that function). And in fact you should use mysqli_ or PDO, not a mysql_ extension which is now deprecated. Using htmlspecialchars() is simply using wrong tool for the task.
Code should be like this:
mysql_real_escape_string( serialize( $string ) );
I'm using mysqli extension in php for connection to database. I've such a simple question. Is it better to use mysqli instead of mysql and why is it necessary to use mysqli_real_escape_string ? what is this function doing exactly ? Thanks ...
I'll put a little example not using SQL. Imagine you have this PHP code:
<?php
echo 'Hello, world!';
Now you want to replace world with O'Hara:
<?php
echo 'Hello, O'Hara!'; // Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'
Yeah, of course, that is not valid PHP. You need to escape the single quote since it's interpreted as a literal quote rather than the string delimiter:
<?php
echo 'Hello, O\'Hara!';
You have exactly the same problem when composing SQL queries. If you inject random input into your code, sooner or later it'll break. You need to encode input so it's handled as literal input rather than broken code.
How can you do that? Well, MySQL accepts \' just like PHP (though it's only a coincidence: other database engines use other escape methods). So the dumbest solution is to add back slashes here and here:
SELECT id FROM user WHERE name='O\'Hara';
Of course, it's a lot of work to hard-code all the possible characters that need escaping (and you'll probably forget some of them) so you can use a function that does the job for you: either mysql_real_escape_string() or mysqli_real_escape_string().
The question is: is this good enough? Well, it kind of works, but it leads to annoying code that's difficult to maintain:
$sql = "UPDATE user SET name='" . mysql_real_escape_string($name) . "' WHERE id='" . mysql_real_escape_string($id) . "'";
... and you still need to take care of surrounding the complete value with single quotes... which are not always mandatory (think of numbers)... What a mess. Can't someone invent something better? Good news is: they did! It's called prepared statements:
// Just an example, I invented the syntax
$sql = 'UPDATE user SET name=:name WHERE id=:id';
$params = array(
'name' => "O'Brian",
'id' => 31416,
);
$MyDbConnection->execute($sql, $params);
In real life:
MySQLi has the prepare() method to accomplish this. Find some examples there.
Legacy MySQL extension... has nothing: it does not support prepared statements at all! If you use this extension, you are stuck with the annoying add-quotes-yourself and string concatenation methods.
I hope this explains the whole question.
Mysql is slightly faster than Mysqli, but it would have no effect in 99% of web development. The real advantage is that Mysqli is more focused around classes and methods.
Mysqli_real_escape_string is a precautionary function to escape any illegal/malicious characters in a string that you are going to use in a Mysql query. There is also a standard mysql_real_escape_string function aswell. If in doubt it is better to use it than not use it, but beware too many may cause speed issues with your scripts/queries.
To cut it short, if you're writing procedural PHP use standard Mysql, but if you're writing object orientated code then use Mysqli and maximise it's potential. You must always make your queries safe, mysql_real_escape_string is just one way.
Hope this helps!
I have a standard text input field. It get it's value from $_POST and I use it to build an SQL query (ODBC, not just MySQL, if that makes a difference (or instance, I can't use mysql_escape_string() ) ) .
The query which I am building has single quotes on the PHP and double quotes on the SQL. E.g.:
$sql = 'SELECT * FROM ' . $table . ' WHERE field="' . $_POST['some_field'] . '"";
If the user includes a double quote in his input e.g 6" wrench the I get an SQL error on the unbalanced string (a single quote, as in O'reilly gives no problem).
What's the correct way to handle this? Again, I am using the ODBC interface, not MySQL.
Is it just a matter of addslashes()? Or magic quotes?
Update: the PHP manual says of magic quotes ...
This feature has been DEPRECIATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
(not that they suggests an alternative; in fact, it also says that magic quotes will be dropped in PHP 6)
Should the answer be to use prepared statements?
Use PDO prepared statements. It supports ODBC
Use odbc_prepare and odbc_execute like PDO
Even easier... why not just use htmlspecialchars?
http://us3.php.net/manual/en/function.htmlspecialchars.php
I mean, it's faster, and I'm assuming that the reason why your giving users a data field that allows them to use quotes is because your going to print that data back out at some point. Which is still doable, and you don't have to change around where you store your data.
I have a mysql query which requires that parameters be enclosed in either "" or '',
if I have an array passed to this function:
function orderbyfield($column, array $selection)
{
// will it be alright (secure) to do this?
foreach ($selection as $s)
{
$s = '"' . $s . '"';
}
$string = implode(',', $selection)
return array($column, $string);
}
and pass it to
function generate_sql()
{
$fields = $this->orderbyfield(); // assuming the code is in a class
$sql = 'SELECT FIELDS FROM TABLE ORDER BY FIELD (' . $fields[0] . ',' . mysql_real_escape_string($fields[1]));
}
will there be any security issues with this approach?
EDIT
assume that code is in a class, made necessary addition of $this->
EDIT
typo on the foreach
As others have said you should be using mysql_real_escape_string at the point where you create the query string. Also, although the database may be able to cast between types, not all the variables need to be quoted in queries:
function enclose($val, $dbh)
{
if (($val==='') || (is_null($val))) {
return 'NULL';
}
// is it a number?
if (preg_match('/^[\+-]*\d+\.?\d*$/', $val)) {
return($val);
}
// its a string
return("'" . mysql_real_escape_string($val, $dbh) . "'");
}
The null handling might need to be tweaked. (the above is cut down from a generic interface I use which also reads the structure of the table using DESCRIBE to get hints on when to quote/use nulls etc)
C.
Because you are using the mysql_real_escape_string function, it is pretty safe as far as strings are concerned. See dealing with sql injection for more info.
You should add quotes arround your string, but there quotes inside your strings themselves should also be escaped -- this can be done using mysql_real_escape_string, mysqli_real_escape_string, or PDO::quote, depending on the kind of functions/methods you are using to connect to your database.
Doing this (As you are already doing -- which is nice) should prevent SQL injections (at least for string : you should also check that numerics are indeed corresponding to numerical data, for instance)
Another solution, maybe a bit easier once you get it, would be to use Prepared statements.
See :
PDO::prepare
or mysqli_prepare
(Those can't be used with the old mysql_* functions)
If you're using PDO's prepared statements, you do not have to worry about the escaping yourself. No quotes, no backslashes, no nothing.