PHP - Json Encode And Escaping
This should be really simple but I can't get my head round it.
Please see the PHP/HTML below. <?php $a = array( 'test' => "'data'" ); $json = json_encode($a); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Unknown Page</title> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.min.js"></script> <script type="text/javascript"> var j = jQuery.parseJSON('<?php echo $json; ?>'); </script> </head> <body> </body> </html> You will notice that data is stored by " then ' I have tried how it is and also with add slashes $a = array( 'test' => addslashes("'data'") ); It either outputs without slashes (which is clearly wrong) Code: [Select] var j = jQuery.parseJSON('{"test":"'data'"}');Or which I cant work out why dosent work Code: [Select] var j = jQuery.parseJSON('{"test":"\\'data\\'"}'); Now firebog throws the following error Code: [Select] missing ) after argument list How should I be escaping this variable? Similar TutorialsHello - I am connecting to MySql and running a query. If I use a foreach loop, I can iterate over the results and have them print to screen. However, when I try the below everything is null!
How can I add the results of my MySql query to a php array?
<?php $con=mysqli_connect("site", "user", "psasswr=ord", "db"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT * FROM test LIMIT 10"; $result = mysqli_query($con,$sql); echo json_encode($result); mysqli_free_result($result); mysqli_close($con); ?>
but what this prints is: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} base64_encode is a perfect standard php encoding, but this produces = most of times. Is there an alternative making the encode by alphanumeric only? i know of Bace64 rot_13 is thare more than just this? (for urls) Hi, I am working on a project, and my customer is demanding some sort of "non-standard" hashing to encode field values on a database. This customer wants something exclusive, difficult to be decoded, and would accept no argument proving that the existing hash algorithms are good enough for the job. What makes it even more challenging for me is that I don't have much experience in PHP. The output should be something similar to a hex triplet (web color), so... this basically means I cannot use MD5, SHA, etc. This also means that PHP hash() function is useless in this case, unless there is a hash algorithm I don't know about, and that gives me the output I need. What I need is something like: Code: [Select] $output = functionthatdoesntexist("string to be encoded"); The "$output" var should contain something like: 19f7b4 (this is just a random value I am using to illustrate the format required for the output.) Now here are my questions: 1) Is there a PHP function that encodes a string/number, and gives me back a "hex triplet"? 2) If such function doesn't exist, is there a way to create one from scratch? How should I start? I just can't figure out how to solve this problem, so any help is appreciated. Thanks in advance, AP This topic has been moved to Other. http://www.phpfreaks.com/forums/index.php?topic=357168.0 Hi there. I was wondering if it were possible to convert text to numbers or some sort of URL friendly link. For example, "Hello there" would be converted to '435342553' or whatever. I want to do this because for example when someone goes to this URL, example.com/435343434, the number/uri string would be decoded and whatever the text was it would be displayed on the site. I can write all this code no bother I just need some advice/ideas on the the encoding/decoding of the text. I was looking at some options for doing this..... hexdec - removes spaces md5 - cannot be decoded? None of them seem to be working, the problem is decoding them. md5 creates a perfect uri string but as I said it cannot be decoded. I would appreciate any ideas of suggestions. Thanks a million. Code: [Select] echo '<img src="data:image/jpg/png/jpeg;base64,' . base64_encode( $row['image'] ) . '" height="150" />'; This is showing up images great in firefox, safari and chrome, but in internet explorer it shows a nice red cross, and I assume it is because of the encoding? Does anyone know how to get working in internet explorer as well? Pretty urgent job! Much appreciated for your help! This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=315503.0 I have a table with two columns A and B. I'm submitting a form where the user selects different checkboxes. Column A contains the values of all the checkboxes. I want to, after the form is submitted, using the array of values of randomly checked checkboxes, search the table for the corresponding values in column B. Then display the values of selected checkboxes and their cosesponding values from column B. First I did an implode() on the array of submitted checkbox values, Code: [Select] $list = "'".implode("','", $_POST['Ref'])."'"; then did a mysql_real_escape_string on that. Code: [Select] for($i=0;$i<$count;$i++) { $list = mysql_real_escape_string($list[$i]); } I got a Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'SYSTEM'@'localhost' (using password: NO) Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established for each row of $list. What am I doing wrong? I've got this code and it works fine. All I want to do is, when people click on the x to delete something they submitted erroneously, I want a confirmation...really want to delete this? (sometimes that x is too tempting you know) But I *think* I'm having trouble escaping the line (near bottom): onsubmit='".return confirm('Really Delete');."' I'm not sure if it will work anyhow...but right now it doesn't. Thanks for any suggestions. <code> <?php include '../php/config_conn.php'; $querysum = "SELECT SUM(total_time) FROM `coop_hours` where user = '".$_SESSION['user_name']."'"; $resultsum = mysql_query($querysum); $arr = mysql_fetch_row($resultsum); $resulthours = $arr[0]; $querytime = "SELECT * FROM `coop_hours` WHERE user = '".$_SESSION['user_name']."' ORDER BY `date_completed`"; $result = mysql_query($querytime); $num = mysql_num_rows($result); mysql_close(); echo "<table width='1000' cellpadding='0' cellspacing='0' border='0'><tr> <td width='200'><strong>Coop Job</strong></td> <td align=center width='200'><strong>Date Completed</strong></td> <td align=center width='120'><strong>Total Time</strong></td> <td width='380'><strong>Comments</strong></td> <td width='100'>Delete Entry</td></tr>"; $i=0; while ($i < $num) { $hours_id = mysql_result($result, $i, "hours_id"); $user = mysql_result($result, $i, "user"); $coop_job = mysql_result($result, $i, "coop_job"); $date_completed = mysql_result($result, $i, "date_completed"); $start_time = mysql_result($result, $i, "start_time"); $end_time = mysql_result($result, $i, "end_time"); $total_time = mysql_result($result, $i, "total_time"); $comments = mysql_result($result, $i, "comments"); echo "<tr><td>$coop_job</td> <td align=center>$date_completed</td> <td align=center>$total_time</td> <td>$comments</td> <td align=center valign='middle'> <form action='".php/del.php."' method='".post."' onsubmit='".return confirm('Really Delete');."'> <input type='".hidden."' name='".hours_id."' value='".$hours_id."'> <input TYPE='image' SRC='images/del.png' width='11' height='11' border='0' alt='Delete'> </form> </td> </tr>"; $i++; } echo "<tr><td colspan=5><hr></td></tr>"; echo "<tr><td></td><td align=right>Total hours:</td><td align=center>$resulthours</td><td></td></tr>"; echo "<table>"; ?> </code> Hi, newbie here. Could someone show me how to properly escape the quotes in this code so it works properly? I'm having major problems with it, thanks. echo "<td style="background-color:#fff" onMouseover="this.style.backgroundColor='#ff9900';" onMouseout="this.style.backgroundColor='#fff';">" Hi, I have set up a simple function so that when a user enters a title in a php form, php gives the first letter of each word a capital letter. As follows: function caps($text){ $search_text=$text; $search_text=ucwords(strtolower($search_text)); $look_for = "(a"; $change_to = "(A"; $changed_text = str_replace($look_for, $change_to, $search_text); $search_text=$changed_text; $look_for = "(b"; $change_to = "(B"; $changed_text = str_replace($look_for, $change_to, $search_text); $search_text=$changed_text; $look_for = "(c"; $change_to = "(C"; //...etc...etc.. up to $look_for = "(z"; $change_to = "(Z"; $changed_text = str_replace($look_for, $change_to, $search_text); $search_text=$changed_text; return $search_text; } The trouble is, if I were to enter the following "The secret of DNA", my function would return "The Secret Of Dna" (removes the caps). Any ideas how to get around this would be most useful. Thanks in advance. Russ Im getting a syntax error caused by the first line. How do I properly escape the code? echo "<tr class="'.$colors[$i++ % 2].'"> <td align=center nowrap>($phone1) XXX-$phone2</td> <td align=center nowrap>$overall</td> <td align=center nowrap>$hygiene</td> <td align=center nowrap>$attitude</td> <td align=center nowrap>$ethnicity</td> <td align=center nowrap>$body</td> <td align=center nowrap>$city</td> <td align=center nowrap>$user</td> <td align=center nowrap>$date</td> <td align=center nowrap>$comment</td> </tr>"; Hi guys I am encoding JSON in PHP but want to know how to escape ' and " thats in the content? Thanks Quote from: Mike Solstice on April 14, 2011, 12:24:45 AM Ok, that works if I run it CLI or though phpMyAdmin, but won't if I try it in php Code: [Select] $remcomma = "UPDATE top_train SET deaths = replace( replace(field_name, ',', ''), '"', '' )"; mysql_query($remcomma); I assume because of the quotes used in the regex. I tried escaping the " Code: [Select] $remcomma = "UPDATE top_train SET deaths = replace( replace(field_name, ',', ''), '\"', '' )"; mysql_query($remcomma); Which broke it altogether. Anyone have any ideas? Thanks! Moved here since that thread was marked as solved & it's more of a PHP issue at this point anyway. Any & all help is greatly appreciated! Hello! I'm very new to PHP, and I'm sure this is a noob question - still, its got me stuck! How would I best escape this properly? $resizeObj = new resize('C:\xampp\htdocs\images_test\$file'); so that $file is parsed? the whole script is as follows: Code: [Select] <?php // *** Include Nathan's class include("resize-class.php"); // Define the full path to your folder from root $path = 'C:\xampp\htdocs\images_test'; // Open the folder $dir_handle = @opendir($path) or die("Unable to open $path"); // Loop through the files while ($file = readdir($dir_handle)) { if($file == "." || $file == ".." || $file == "index.php" ) continue; // *** 1) Initialise / load image $resizeObj = new resize('C:\xampp\htdocs\images_test\$file'); // *** 2) Resize image $resizeObj -> resizeImage(100, 100, 'auto'); // *** 3) Save image $resizeObj -> saveImage('C:\xampp\htdocs\images_test\$file', 90); echo "<a href=\"$file\">$file</a><br />"; echo $path; } // Close closedir($dir_handle); ?> Do I need to escape variables passed via link? Is it possible that someone does an SQL Injection via unescaped $_GET variable? (Yes I am using it in an SQL query, not inserting it into a DB tho) Hi Php Freaks I am trying to escape variable but I am lost. I am sure that it is easy. can anyone help ta Code: [Select] $y="\\$GLOBALARRAY = array( \n"; echo $y; I've got a file with some strings that have both types of quotes in them. And I seem to have managed to get the data, display it in my html, store it in a js array (using a json_encode in php and then simply inserting it into my js) but I cannot seem to pass the string as a parameter form an onclick function call to js.
For most strings the addslashes makes it work in the function call. But for those with both sets of quotes it won't work. My console tells me there are "unterminated string constants..". I've experimented with many silly changes but none make it work.
Ex. of the strings:
What do you mean "It's crooked"?
Of course I could remove the contraction and that would probably work, but that would be a hack, would not it?
|