Sorry for the long title.  I am kind of paranoid, so I sanitized $_POST that was treated with JSON.stringify(order) via javascript with  $order = mysqli_real_escape_string($db_upload, htmlspecialchars( strip_tags($_POST['order'])));   before inserting into mysql through mysqli prepared statement.  But when I try to json_decode by  foreach(json_decode($row['order'], true) as $id =&gt;$value){     $sumArray[]= array("item" =&gt; $id, "value" =&gt; $value); }   I get "Invalid argument supplied for foreach() ..."  I know json_decode works when inserted value is   {"Hot water":"1"}   but not when inserted value is  {&amp;quot;Hot water&amp;quot;:&amp;quot;1&amp;quot;}   In this case, how can I json_decode?  Thanks.  edit: I was poor at explaining what I really wanted. As I have mentioned earlier, I already used mysqli prepared statement for inserting the data. I am less worried about sql injection but to advanced xss attacks.  What i really wanted was just how to json_decode  {&amp;quot;Hot water&amp;quot;:&amp;quot;1&amp;quot;}   I decided to go easier method: dropping htmlspecialchars. What I did was   $order = mysqli_real_escape_string($db_upload, strip_tags($_POST['order']));   then,   foreach(json_decode(stripslashes($row['order']), true) as $id =&gt;$value){ $sumArray[]= array("item" =&gt; $id, "value" =&gt; $value);   }  This worked nicely
73
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to , like in the following example:  $unsafe_variable = $_POST['user_input'];   mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");   That's because the user can input something like value'); DROP TABLE table;--, and the query becomes:  INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')   What can be done to prevent this from happening?
10256
How do I use the json_encode() function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
53910
I have a form where the user can input datetime and then I want to store it in the database. Here's my schema :     'start' => array(           'type' => 'varchar', 'mysql_type' => 'datetime',           'not null' => FALSE,         ),   The form :     $form['add']['start'] = array(         '#type' => 'datetime',   '#default_value' => $date,       );   When I hit submit button, it shows me :     db_insert failed. Message = SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:...   What I got out of it was that the DateTime in Drupal is incompatible with MySQL's. Any suggestions or how should I process the value from the form so I can insert it into the db?  Alternatively, any way to convert DrupalDatetime into string?  (For what it's worth I also tried 'timestamp' as the MySQL type but it throws me the same error).
114158
I've found several similar question but none of them explains why the below is giving me nothing with ASC order. It works with DESC.  Basically it's a query that should list posts where the custom field values are equal or greater to the current date, then arrange it in reversed order, so the first post should be a post that's custom field are the closest the the current date.  &lt;?php query_posts($query_string . '&amp;showposts=4&amp;order=ASC&amp;post_type=custompost&amp;meta_key=mydate&amp;orderby=meta_value'); ?&gt;     &lt;?php if (have_posts()) : ?&gt;     &lt;?php while (have_posts()) : the_post(); ?&gt;          &lt;?php $todays_date = date("Y/m/j"); ?&gt;         &lt;?php $today = strtotime($todays_date); ?&gt;         &lt;?php $exp_date = get_post_meta('mydate'); ?&gt;         &lt;?php $expiration_date = strtotime($exp_date); ?&gt;         &lt;?php if ($expiration_date &gt;= $today) { ?&gt;              &lt;a href="&lt;?php the_permalink(); ?&gt;" rel="bookmark" title="&lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;      &lt;?php } else { ?&gt;     &lt;?php };?&gt;  &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;?php endif; ?&gt;    Also, I've tried many different queries but none of them worked, the above script is the latest I have.
118249
I have a basic understanding of  (I come across it often when I'm migrating WordPress installs) and I just discovered .  Given that serialize causes so much trouble with replacing strings in the database (eg. editing an optinos field directly), why does WordPress prefer serialize to (the seemingly similar) json_encode, which doesn't insert the string length into the stored value.  My first thought was that it may provide some security or error-checking benefits - WordPress will ignore the option if the string lengths are incorrect.. but I'm interested in a qualified explanation :)
99906
One of the responses to  suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?
44862
I have a problem binding booleans using mysqli_stmt::bind_param in PHP5. The SQL query is the following: insert into `nvp_notes` (subject,messageid,receivedate,read) values (?,?,?,?)  Where 'read' is a tinyint, either 0 or 1, as I've had issues with bit using mysqli. So the types that I list in bind_param are: $stmt-&gt;bind_param('sdsd', ...);  I've also tried 'sdsb' and 'sdss' but nothing seems to work, and I always get the message:  Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement  When I remove the read field in the statement everything works fine. I've run out of ideas with this one. Surely bind_param works with booleans?
52467
I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:  var data = '{"count" : 1, "stack" : "sometext\n\n"}'; var dataObj = eval('('+data+')');   This gives me an error:   unterminated string literal   With JSON.parse(data), I see similar error messages: "Unexpected token ↵" in Chrome, and "unterminated string literal" in Firefox and IE.  When I take out the \n after sometext the error goes away in both cases. I can't seem to figure out why the \n makes eval and JSON.parse fail.
91117
I'm looking for a good approach to manipulate some JS code from within a module call. (Using Drupal 6.)  I have a set of JavaScript functions I need to add to a page. (Regular JavaScript, no jQuery.) Unfortunately they rely on some variables from the page they are shown on. So my current approach is to generate all the JavaScript from within PHP code which results in a whole lot of escaped strings like $output .= '  var url = "'. $url . '";' . "\n";, which is not so nice after 20-30 lines of code.  So I would like to move all the JavaScript code into it's own .js file, and find a way to inject my variables. So far, the only solution I could come up with is putting it in a temporary file, read that, modify and save it to the /files directory. But is there another, more preferred way?
73925
Earlier today a question was asked regarding .  The top answer, at time of writing, suggests in PHP just using htmlspecialchars and mysql_real_escape_string.   My question is: Is this always enough? Is there more we should know? Where do these functions break down?
94609
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.  1) How can I return the JSON encoded string to the javascript? 2) How will the javascript loop through the rows and access their fields?
47815
What is a strong way to protect against sql injection for a classic asp app?  FYI I am using it with an access DB.  (I didnt write the app)
16453
Friends, sometimes I had to create a self-contained PHP script. That means the PHP script could have any files within it due to some encoding/decoding algorithm, like Base64. For example,  is a Base64 encoding of this tiny image:   Of course, in this particular case, PHP can handle that huge encoded string because it has a bundled  function.  I was wondering if this idea is possible to achieve somehow in TeX/LaTeX. I need to point out that I'm just curious on this subject, not that I want to embed whatever in code. Besides, as you noted, the encoded string is huge, so that'd surely make people cry blood.  One possible solution I see is if somebody implement an encoding/decoding algorithm in TeX/LaTeX, like \base64_decode, so it would be possible to use something like this: \includegraphics{\base64_decode{\myhugeunreadablestring}}. Sorry for the acid trip ticket, but I'm really curious on how this insane code would work. =)
115517
I wanted to suggest an edit for  given to , but it was denied because "Edits must be at least 6 characters."  However, given the edit I was suggesting is very important to the syntax of the solution, I think it is relevant even though it contains only 3 characters. See the answer posted by knittl and notice the variable $value is used as both function input and in the foreach loop. I simply suggested changing the function parameter's name to $values in the 3 locations it is used, but was denied, leaving the post incorrect.  Note: I do realize I could have suggested an entirely different variable name thus allowing the edit, but similar situations have arisen in the past where a simple fix of just a few characters make a significant difference. After all, Stack Overflow is a coding website and syntax is very important.
326
I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1.  Where exactly do I need to set the encoding/charsets? I'm aware that I need to configure Apache, MySQL, and PHP to do this — is there some standard checklist I can follow, or perhaps troubleshoot where the mismatches occur?  This is for a new Linux server, running MySQL 5, PHP, 5 and Apache 2.
19369
points out the following security problem with MySQL:  USERS id | email            | password_reset_token 1  | one@example.com  | QTlXww)uV!Hdg3U6aGwKV2FPvAqzVgPx 2  | two@example.com  | CZor5t7WbX#LTeqiG3v@6f3@z#)BfK*n   Here we have nice, random tokens that a user must prove they have in order to reset their account. But the user manages to submit a reset token of 0, so we run this query:  SELECT * FROM `users` WHERE `email` = 'one@example.com' AND `password_reset_token` = 0   MySQL converts the token VARCHAR to an INT in order to make the comparison. It considers a VARCHAR that does not start with a number to equal 0. Therefore, an attacker can match any non-numeric string and take over the account.  Even if the reset token starts some numbers, the situation is not much better. MySQL ignores all characters but the initial numbers when making this comparison, so it considers 12blahblah3blah4 to be equal to 12, which makes guessing exponentially easier.  Can I configure MySQL not to do this kind of typecasting? If, for example, it cast INT to VARCHAR instead of vice versa, this attack would not work.  Note  If the query is run with '0' instead of 0, this doesn't work. The article discusses this vulnerability in terms of Ruby on Rails' acceptance of XML, where a type=integer property convinced Rails to send an actual integer in the query.  That bug has been patched in Rails; it now converts all request parameters to strings, so it would never build a query with an integer. But I still think MySQL should be configurable to prevent this.
95793
Important note: I'm using Cygwin    I retrieve JSON from a file that I alter before sending it to a server using curl. By now everything is ok except one thing, when the server receive the JSON, every special characters (with accents, etc) aren't well encoded. I suppose this was due to the fact that my JSON wasn't encoded in UTF-8 before being sent but I don't manage to convert it.  Here is the code:  sed -i 's/\r//g' $file fileContent=`cat $file`  result=$(jq -c -j ".docs[$docIndex] + { \"_rev\": \"$rev\" }"&lt;&lt;&lt;"$fileContent")            result="{\"docs\":[$result]}"  result=$result | sed 's/\r//g' result=$result | iconv -t "UTF-8" s=$(curl -H "Content-Type: application/json; charset=UTF-8" -H "Cache-Control: no-cache" -d "$result" $2/$3/_bulk_docs --silent)   My bash script and my JSON files are both encoded in UTF-8. My LANG variable seems to be UTF-8. I checked with this: [[ $LANG =~ UTF-8$ ]] &amp;&amp; echo "Uses UTF-8 encoding.."  Any idea?    Update  Here is the full script:  #!/bin/bash  # $1 = directory containing JSON files # $2 = server url (+ port) # $3 = database name  #Loop on every file of the given directory for file in "$1"/*; do      #Try to insert every document of a specific JSON file and retrieve their status (200 = OK; 409 = conflict)     allStatus=$(curl -H "Content-Type: application/json" -H "Cache-Control: no-cache" --data-binary "@$file" $2/$3/_bulk_docs --silent | jq '.[] |.status' | tr -d '\r')     docIndex=0      #Loop on every status (one status = one document)     while IFS=' ' read -ra statusArray; do       for status in "${statusArray[@]}"; do          #Remove unwanted windows characters of the file         sed -i 's/\r//g' $file         fileContent=`cat $file`          #Retrieve the id of the current document         id=`jq -r -j ".docs[$docIndex]._id"&lt;&lt;&lt;"$fileContent" | tr -d '\r'`          if [ "$status" = "409" ]         then              #Retrieve the revision of the current document and add it to the document              rev=$(curl -X GET --header 'Accept: application/json' $2/$3/$id?revs=true --silent | jq -r -j '._rev' | tr -d '\r')             result=$(jq -c -j ".docs[$docIndex] + { \"_rev\": \"$rev\" }"&lt;&lt;&lt;"$fileContent")              #Wrap the document inside {"docs":[]}             result="{\"docs\":[$result]}"              #Remove unwanted windows characters before sending the document (again)             result=$result | sed 's/\r//g'             result=$result | iconv -t "UTF-8"             s=$(curl -H "Content-Type: application/json; charset=UTF-8" -H "Cache-Control: no-cache" -d "$result" $2/$3/_bulk_docs --silent)              #Echo result             echo $s         else           #Status should be 200.           echo 'status: '$status ' - ' $id         fi          docIndex=$((docIndex+1))        done     done &lt;&lt;&lt; "$allStatus" done   This script aims to upsert documents inside a NoSQL database. If first try to insert and if if fails it retrieves a property (the revision) of the document, append to it and then retry once.  I know this script could be improved but this is my first bash script and it won't be used in production (only for testing, etc.).