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 )
Related
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.
I want to suppress Searches on a database from users inputting (for example) P*.
http://www.aircrewremembered.com/DeutscheKreuzGoldDatabase/
I can't work out how to add this to the code I already have. I'm guessing using an array in the line $trimmed = str_replace("\"","'",trim($search)); is the answer, replacing the "\"" with the array, but I can't seem to find the correct way of doing this. I can get it to work if I just replace the \ with *, but then I lose the trimming of the "\" character: does this matter?
// Retrieve query variable and pass through regular expression.
// Test for unacceptable characters such as quotes, percent signs, etc.
// Trim out whitespace. If ereg expression not passed, produce warning.
$search = #$_GET['q'];
// check if wrapped in quotes
if ( preg_match( '/^(["\']).*\1$/m', $search ) === 1 ) {
$boolean = FALSE;
}
if ( escape_data($search) ) {
//trim whitespace and additional disallowed characters from the stored variable
$trimmed = str_replace("\"","'",trim($search));
$trimmed = stripslashes(str_ireplace("'","", $trimmed));
$prehighlight = stripslashes($trimmed);
$prehighlight = str_ireplace("\"", "", $prehighlight);
$append = stripslashes(urlencode($trimmed));
} else {
$trimmed = "";
$testquery = FALSE;
}
$display = stripslashes($trimmed);
You already said it yourself, just use arrays as parameters for str_repace:
http://php.net/manual/en/function.str-replace.php
$trimmed = str_replace( array("\"", "*"), array("'", ""), trim($search) );
Every element in the first array will be replaced with the cioresponding element from the second array.
For future validation and sanitation, you might want to read about this function too:
http://php.net/manual/en/function.filter-var.php
use $search=mysql_real_escape_string($search); it will remove all characters from $search which can affect your query.
I am having a problem trying to understand functions with variables. Here is my code. I am trying to create friendly urls for a site that reports scams. I created a DB full of bad words to remove from the url if it is preset. If the name in the url contains a link I would like it to look like this: example.com-scam.php or html (whichever is better). However, right now it strips the (.) and it looks like this examplecom. How can I fix this to leave the (.) and add a -scam.php or -scam.html to the end?
functions/seourls.php
/* takes the input, scrubs bad characters */
function generate_seo_link($link, $replace = '-', $remove_words = true, $words_array = array()) {
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($link))));
//remove words, if not helpful to seo
//i like my defaults list in remove_words(), so I wont pass that array
if($remove_words) { $return = remove_words($return, $replace, $words_array); }
//convert the spaces to whatever the user wants
//usually a dash or underscore..
//...then return the value.
return str_replace(' ', $replace, $return);
}
/* takes an input, scrubs unnecessary words */
function remove_words($link,$replace,$words_array = array(),$unique_words = true)
{
//separate all words based on spaces
$input_array = explode(' ',$link);
//create the return array
$return = array();
//loops through words, remove bad words, keep good ones
foreach($input_array as $word)
{
//if it's a word we should add...
if(!in_array($word,$words_array) && ($unique_words ? !in_array($word,$return) : true))
{
$return[] = $word;
}
}
//return good words separated by dashes
return implode($replace,$return);
}
This is my test.php file:
require_once "dbConnection.php";
$query = "select * from bad_words";
$result = mysql_query($query);
while ($record = mysql_fetch_assoc($result))
{
$words_array[] = $record['word'];
}
$sql = "SELECT * FROM reported_scams WHERE id=".$_GET['id'];
$rs_result = mysql_query($sql);
while ($row = mysql_fetch_array($rs_result)) {
$link = $row['business'];
}
require_once "functions/seourls.php";
echo generate_seo_link($link, '-', true, $words_array);
Any help understanding this would be greatly appreciated :) Also, why am I having to echo the function?
Your first real line of code has the comment:
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
Periods are punctuation, so they're being removed. Add . to the accepted character set if you want to make an exception.
Alter your regular expression (second line) to allow full stops:
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\.\s]/', '', strtolower($link))));
The reason your code needs to be echoed is because you are returning a variable in the function. You can change return in the function to echo/print if you want to print it out as soon as you call the function.
I try to pull out the number string from google and clean it up.
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = str_replace(' ','',$number[3]);
echo $result;
?>
however, the number i've got has a space.
I tried to replace it with needles " " or "  ;". Or utf8_encode, decode $content. None of them works.
As for the solution to your problem, the best answer is to replace anything that is not a number or punctuation using preg_replace(); Try this:
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = preg_replace("/[^\d.]/", '', $number[3]);
echo $result;
?>
But you may want to look into using google.com/ig/calculator. It should save a lot on bandwidth and save you having to pull a full Google Results page and replace on it: http://www.google.com/ig/calculator?hl=en&q=35%20meter%20in%20inch
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/ig/calculator?q=$query[0]+$query[1]+$query[2]+$query[3]";
$content = file_get_contents("$googleUrl");
preg_match("/rhs:\s\"(.*)\",error/", $content, $number);
$num = explode(" ", $number[1]);
$num = preg_replace("/[^\d.]/", '', $num[0]);
echo $num;
?>
Probably because it's not really a space, even though it looks like it. You could try replacing all \w with the regular expression.
hi the space before <?php tag it it there in your code too? then that might be giving the space check that!
This is not a space you are trying to remove, it is "à" that is not visible in browser. You can also check these things by using your php script by commandline. You can use html entities function and then replace according to that
I have tried many combinations and a few different PHP functions, but I still can't figure out why it doesn't work.
Here's the deal.. If someone uses the form and the (in this case) "Title" field ends with " (Part 1)", I want to delete that string, and if it doesn't contain " (Part 1)" I want to set a variable to the Title as it was submitted.
Here is my current script:
<?php
$partInStack = stristr($_POST['Title'], " (Part 1)");
if ($partInStack !== FALSE) {
$Title = str_replace($partInStack, "");
} else {
$Title = $_POST['Title'];
}
?>
You don't need to check stristr first, you can just do the str_replace right away:
$Title= str_replace(" (Part 1)","",$_POST['Title']);
UPDATE
You're original wasn't working because you messed up the parameter list for str_replace http://us.php.net/str_replace:
str_replace($search, $replace, $subject);
There's one parameter missing there in str_replace()
http://php.net/manual/en/function.str-replace.php