Removing single quotes in PHP - php

I got some issues trying to INSERT some data from a php document till i got 2 values which contains quotes inside like :
"Rempli d'étoiles"
i d like to remove the ' by a space or even nothing.
-> "Rempli d etoiles"
Here is my what i tried :
$posdeapostrophe = strpos($array, '\'');
if ($posdeapostrophe == false)
{
...
}
else
{
// it goes in this block when it detects a ', but seems like trim doesnt work as i would
$newchaine = trim($array, '\'');
$sql .= "INSERT INTO categorie (id_cat,name_cat) VALUES (" . $cpt . ",'" .$newchaine . "'); ";
thanks!

You can use str_replace().
$array = "Some string's";
$posdeapostrophe = strpos($array, "'");
$val = '';
if ($posdeapostrophe !== false)
{
$val = str_replace("'", "\'", $array);
}
echo $val;
Also can use instead of strpos() and replace() to escape single quotes.
mysqli_real_escape_string($con, $array ); //for mysqli
mysql_real_escape_string($array , $con); //for mysql

What you are currently doing is quite dangerous.
First of all, you should really use the current recommended method for executing queries which is by using PDO: http://php.net/manual/en/book.pdo.php
This will both solve the quotes problem and a massive security hole (SQLi vulnerability) you have currently introduced in your code.
If you still want to replace the single quotes in your text you can indeed do what #scrowler suggested which is:
$your_string = str_replace("'", "", $your_string);
But please use PDO when interacting with a database since this is really the only (safe and recommended) way of doing this.

Related

How to properly escape double quotes in a malformed json input before php json_encode

I have a large json file that I'm importing before treatment. I do not control the content of this file, and the json is improperly escaped, leading to some cases of double quotes inside double quotes enclosed strings.
for example :
/...../
"productdiploma" : [],
"productcursus" : ["Méthodes"],
"productpublishedonsite" : false,
"productpublishedonkne" : false,
"productypologyparentality" : [ {
"productmediaformat" : "01- Livre",
"producttechformat" : "50- Grand format - "Autre"",
"productparent" : ""
}],
"productparentwork" : [ {
"productparentworkid" : "1000248048",
"productparentworktitle" : "TRAVAILLER EN FRANCAIS "EN ENTREPRISE" 2007"
/...../
In my import, the file is treated as a very large string with file_get_contents(). I probably need a preg_replace() or a preg_filter() there, but I can't quite figure what patterns I'd need to find and escape those double quotes with a \". Any Help/ideas out there ?
(and see comment below in anwser to shibon to see why it's not a duplicate)
I'd suggest you need a different approach here. Loading the file as one large string means it's nearly impossible to know which double quotes are wanted and which ones are not. I'd go with an approach that allows you to read the fine line by line instead;
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
$line = fgets($file);
}
fclose($file);
?>
This will allow you to test just the right hand side of each :, like this;
$partToTest = explode($line, ':')[1];
Knowing that for items that have quotes at all (i.e, not the arrays), they should be the first and last character on each line. So you could do something along the lines of;
If the part has quotes, remove the first and last
if($partToTest.substr($line, 0, -1) === "\""))
$partToTest = substr($line, 0, -1); # removes the last quote
$partToTest = substr($line, 1, 0); # removes the first quote
Replace any remaining quotes with \"
$partToTest = str_replace("\"", "\\\""); # escape remaining quotes
Append and prepend new quotes to replace the ones we removed
$partToTest = "\"" . $partToTest . "\"";
Put the line back together.
$line = explode($line, ':')[0] + $partToTest;
}
Admittedly, my php skills aren't the best so there may be a much simpler way of doing this, but the principle should work.
I managed to work out this code, based on #lewis' idea :
$content = '';
while(! feof($infile) )
{
// reset line values at each iteration.
$final_line = '';
$test = array();
// get the next line
$line = trim(fgets($infile));
// test if the line is splitable, else, white as is ({, [ etc...])
if(strpos($line,'" : "')) {
// split the line at quote+space+':'.space+quote to avoid splitting strings containing just ' : ' (not fool proof as a string might still contain '" : "' and split, but works in my case)
$test = explode('" : "',$line) ;
// add the final quote that we just stripped in the splitting to the key
$key = $test[0].'"';
// test if the line ends with a comma or not to decide at which position to remove the last quote
if( strpos($test[1], '",') == (strlen($test[1])-2) ){
$val = substr($test[1],0,-2);
$comma = ','; // store a comma for latter use
} else {
$val = substr($test[1],0,-1);
$comma = '';
}
// no need to remove remove the fist quote it's been taken care of at splitting
// replace the double quotes inside the trimmed string
$val = str_replace('"','\"', trim($val));
// reassemble the corrected line
$final_line = $key . ' : "' . $val . '"'. $comma ."\n";
} else {
$final_line = $line ."\n";
}
//store the line for later treatment
$content .= utf8_encode($final_line);
}
That does the job, though it's significantly slower, and there is still room for errors in the splitting if the line contains the '" : "' string inside the part I want to test, but that's a fix anyway :)

PHP Convert a string of comma separated values into another format without using a loop

In php, if I had a string of comma separated data like this which came from a database:
John,Paul,Ringo,George
how could I convert it to something like this, without using a for loop or any extra processing. Does php have a function that can do this?
$str = 'John','Paul','Ringo','George';
I currently split the string using explode and then reformat it. Anyway to achieve this without doing that?
The formatted string is sent to a SQL where it's used in a MySQL IN() function.
If you absolutely don't want to use explode() you could use
$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";
You can use preg_replace with $1 thing.
UPDATED:
See usage example:
echo preg_replace('((\\w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');
you can use explode like below
$db_data = 'John,Paul,Ringo,George';//from your db
$l = explode(',',$db_data);
echo "select * from table where column IN('".implode("','",$l)."')";
output:
select * from table where column IN('John','Paul','Ringo','George')
You can use the explode and implode functions in PHP.
$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);
I hope I got you right:
$str_1 = 'John,Paul,Ringo,George';
$str_2 = explode(',', $str_1);
$str_3 = implode('\',\'', $str_2);
$str_4 = '\''.$str_3.'\'';
echo $str_4;
Output: 'John','Paul','Ringo','George'
$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'

PHP error while inserting in MYSQL with arrays

I have a script which inserts all data in array to MYSQL. But when there is just a single word in the array, the script gives no error, while when there are multiple words, it gives a
Column count doesn't match value count at row 1
Here is my code
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
include("connect.php");
$counter = 0;
$counters = 0;
$string = mysql_real_escape_string($_POST['words']);
$arr = explode(" ", $string);
mysql_query("SET charset utf8");
$sql = mysql_query("SELECT `word` FROM unicode WHERE word IN ('".implode("', '", $arr) . "')") or die (mysql_error());
$dupes = array();
while($r = mysql_fetch_assoc($sql)) {
$dupes[] = $r['word'];
}
$newwords = array_diff($arr, $dupes);
if(count($newwords)) {
$word = implode("'),('", $newwords);
$md5 = md5($word);
$sqli = mysql_query("INSERT INTO unicode (word, word_hash) VALUES ('$word', '$md5')") or die (mysql_error());
}
}
?>
Please help....
As a rule, when I have problems with SQL I do the following things to track down the issue.
ECHO out the SQL query I am trying to run against the DB. This makes sure that I am passing the value of the variable and not the the text '$variable'.
Switch on and check the general.log table in the MySQL DB (assuming you are using MySQL). This will show you the last queries run against the DB and will prove one way or another if your script is even executing anything against the DB.
Lastly I am not as au fait with imploding etc as suggest above to comment, however I would also add the following. Looking at your query it looks as if you are doing I what I talked about in point 1.
$sqli = mysql_query("INSERT INTO unicode (word, word_hash) VALUES ('$word', '$md5')") or die (mysql_error());
The single quotes around $word and $md5 would mean literally pass $word and $md5 into the DB. When using variables within double quote " ... " you do not need to put anything around them just use them as is. Or if you would like to use single quote marks you can concatenate the query string.
$sqli = mysql_query('INSERT INTO unicode (word, word_hash) VALUES ( ' . $word . ', ' . $md5 . ')') or die...
Again echo out the query as you have it (without the mysqli_query function) to confirm.
Hope this helps.
S
You're imploding $newwords, so the resulting query would look something like:
...VALUES ('word1'),('word2'),('word3', 'md5 string')
Add $md5 to implode():
$md5 = 'md5 string';
$word = implode("', '$md5'),('", array('word1', 'word2', 'word3'));
Outputs:
...VALUES ('word1', 'md5 string'),('word2', 'md5 string'),('word3', 'md5 string')
The number of column parameters in your INSERT query is more than 2, but you've only provided 2 values.
$word = implode("'),('", $newwords);
This statement here is the culprit. When you implode the $newwords array, you'd probably get more than 2 values. When inserted into the MySQL query, it won't match with the number of VALUES you've provided. That's causing the error.

How to avoid having "whitespace" posts in a site?

I have this site : http://aasiskos.webpages.auth.gr/1905_YPA/Rating.php . I log in ( user = mpa#mpa.com and pass = 123a ) and then I can add a comment by pushing the green image. I am trying to put a restriction to the "post comment" thing. I want to avoid having comments posted with whitespace (no text). But it doesn't work. The posts that are not whitespace , are not shown either. The problem is under the last "else" thing in the code below. How can i change that ?
$link=mysql_connect('localhost', 'student1905','123456');
mysql_select_db('student1905');
$title= $_POST["title"];
$text= $_POST["text"];
if (!$link) {
die('Could not connect: ' . mysql_error());
}
else {
header("Location:Rating.php");
}
if ( ($_POST[title]=" ") || ($_POST[text]=" ") ) {
header("Location:Rating.php");
}
else
{
$sql = "INSERT INTO kritikes (Auxon, Date, Title, Text) VALUE ('',CURDATE(),'$_POST[title]', '$_POST[text]')";
mysql_query($sql);
}
?>
You can use PHP's trim() function to remove white space from the beginning and end of a string. This would easily allow you to evaluate the content.
However, there are several other problems with your code. Firstly, you are redirecting to Rating.php if your database connection exists. This will prevent any future code in the PHP from running.
You're also using a deprecated family of functions. mysql_* bring serious security implications to the table. You should really consider using MySQLi or PDO. Along with this, your code is open to SQL injections, so you should certainly make sure that you sanitize your inputs.
That having been said, the following code should work for you, but you'll need to make the changes based on my recommendations above regarding mysql_* and SQL injection:
$link = mysql_connect('localhost', 'student1905','123456');
mysql_select_db('student1905');
$title= trim($_POST["title"]);
$text = trim($_POST["text"]);
if(!$link)
{
die('Could not connect: ' . mysql_error());
}
else {
if(strlen($title) == 0 || strlen($text) == 0)
{
header("Location:Rating.php");
}
else
{
$sql = "INSERT INTO kritikes (Auxon, Date, Title, Text) VALUE ('',CURDATE(),'$title', '$text')";
mysql_query($sql);
}
}
you can use trim() to take out any leading and trailing white space. examples:
trim(' h i '); //is equal to "h i"
trim('hello world'); //is equal to "hello world"
it does not remove the middle whitespace.
You can use empty to check if the string is empty regardless how many whitespace it contains. Examples:
empty(""); //returns true
empty(" "); //returns true
empty(" a"); //returns false
Use trim to remove any leading or trailing whitespace. Then check if the message is empty (ie. strlen($message) === 0).
You can do like this-
if(trim($_POST[title])=="") {
// your code
}
For just spaces, use str_replace: For ex, $string = str_replace(' ',
'', $string);
For all whitespace, use preg_replace:
$string = preg_replace('/\s+/', '', $string);
If you just are dealing with excess whitespace on the beginning or
end of the string you can use trim(), ltrim() orrtrim() to remove
that.
Read in your post variables into actual variables, trimming while doing so. Then, do a check to make sure neither of them is an empty string. If neither is empty, then proceed to do your sql query. See example below.
$title = trim($_POST['title']);
$text = trim($_POST['text']);
if($title != '' && $text != '') {
$sql = "INSERT INTO kritikes (Auxon, Date, Title, Text) VALUE ('',CURDATE(),'$title', '$text')";
mysql_query($sql);
}
try updating this line :
if ( ($_POST[title]=" ") || ($_POST[text]=" ") )
to :
if ( strlen(trim($_POST[title]))== 0 || strlen(trim($_POST[text]))== 0 )

Add quotes to values in a string separated by a comma php

I have a search box that can contain multiple values using a comma, eg Pasta, tuna, eggs
Im using FULLTEXT mysql search but I need to use some kind of preg_replace to turn Pasta, tuna, eggs into 'Pasta','tuna','eggs'
If I enter this 'Pasta','tuna','eggs' into the search box the results are correct.
Don't use regular expressions for problems that can be solved otherwise. What you want is a simple string replacement:
$string = "'" . str_replace(",", "','", $string) . "'";
You should escape quotes inside the string first, though (don't know what your escape character is, assuming it's backslash):
$string = "'" . str_replace(array("'", ","), array("\\'", "','"), $string) . "'";
Are you building an SQL query with the list? If so, you should take some time to make sure the resulting SQL is properly escaped as well.
$myList = "pasta, tuna, eggs";
$items = preg_split("/[,\\s]+/", $myList);
$sqlItems = array();
foreach ($items as $item) {
$sqlItems[] = "'" . mysql_real_escape_string($item) . "'";
}
// Add new list to SQL
$sql .= implode(",", $sqlItems);
Do you have any comma in values?
If not you could use something like:
preg_replace('/[^,]+/g', '\'\1\'', preg_replace('/\'/g', '\\\'', $text))
implode your string, then foreach resulting array and add needed symbols
Guys sorry for the trouble but I've solved my own question! Ive looked at this and it was all wrong to begin with.
I had to replace each , with a space and a plus sign so ", tuna" = " +tuna"
Thanks anyway

Categories