hi im running a mysql insert query, the idea is users can submit reviews to users profiles, but i wanted to know if there was a way i could block offensive words, links and prevent a way of people spamming it with blog links etc.
would i use a php if statement that says ignore these keywords; "f*ck" etc, i feel the only problem with something like this is i would have to have every word covered in the ignore statement,
or would i include something in my mysql, either way i want to block all links being inserted into the form,
can somone give me some guidance and show me how i woudld do this please thanks
html:
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<textarea name="review_recipient" id="review_recipient" maxlength="180" cols="33" rows="5" style=""></textarea><label style="">Who is the Review from?</label>
<br/>
<textarea name="review_content" id="review_content" maxlength="180" cols="33" rows="5" style=""></textarea>
<label style="">Say Something...</label>
<input name="add_review" type="image" src="http://www.playtimeboys.com/assets/img/icons/save-edit.png" BORDER="0" ALT="SUBMIT!"class="review_submit4" /></form>
php/mysql:
<?php ob_start(); ?>
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
{
$sql = "INSERT INTO ptb_reviews (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Thank You</strong> - Your review has been sent and is awaiting approval.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} } } } ?>
$blocked_words="test1,test2,test3,test4";//list of offensive word
$review_from_user ="Your reviews test2 is following hello test1"; //review from user
$blocked_words_expo = explode(",", $blocked_words);
foreach($blocked_words_expo as $rmv)
{
if(strpos($review_from_user,$rmv)==true)
{
$review_from_user = str_replace($rmv,'',$review_from_user);
}
}
echo $review_from_user;
//and then insert $review_from_user
You can try to get the values from the bad words table .something like below
$blocked_words=array();
$q="select words from block";
$rs=mysql_query($q);
while($rd=mysql_fetch_object($rs))
{
$blocked_words[]=$rd->words;
}
$string_words=explode(" ", $_POST['review_content']);
$result = array_intersect($blocked_words, $string_words);
By the above code you will get all words from table 'block' into $blocked_words.You might need to change with respect to your needs
Related
I am pretty new to PHP and MySQL. Anyway, I currently try to write an application for Karaoke events.
The visitors of the event should be able to search online in a database for a specific song they would like to sing and then should be able to add this song to a kind of queue. The queue can then be display on a screen so the visitors can see how many people are singing before them and what they are singing etc.
My msql database is pretty simple. The table is called "songs" and I have 4 columns
id, title, artist, language
So first thing I need is a search form in which the people can type in any kind of searchterm and they get back the matching songs. It should not matter weather they search for artist or song, so they could type in "Love" as well es "Beatles" ot get the matching results.
So if the searchterm is "love" for example, the visitor gets back a table of maybe 100 lines of songs with the term "love" in the title.
I finally made this work, here is my code so far
<form action="searchform.php" method="get" >
<input type="text" name="searchquery" dir="ltr">
<input type="submit" value="start search">
</form>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'inc/db.php';
$daten = array();
if(isset($_GET ['searchquery']) && $_GET['searchquery'] !== ' ')
{
$searchquery= trim($_GET['searchquery']);
echo "<p>Your search was: <b>". $searchquery ."</b></p>";
$search_for = "%$searchquery%";
$songsearch=$db->prepare("SELECT title,artist FROM songs WHERE artist LIKE ? OR title LIKE ?");
$songsearch->bind_param('ss', $search_for, $search_for);
$songsearch->execute();
$songsearch->bind_result($showtitle, $showartist);
echo "<table><tr><th>Title</th><th>Artist</th></tr>";
while ($songsearch->fetch()) {
echo "<tr><td>$showtitle</td>";
echo "<td>$showartist</td></tr>";
}
echo "</table>";
}
?>
inc/db.php
<?php
error_reporting(E_ALL);
$db = new mysqli('localhost', 'root', 'root', 'songlist');
$db->set_charset('utf8');
?>
Now I want the visitor to be able to click on one songtitle of the returned list (table) and with this click I want the song to be added to a queue. My idea was to just add another table to the database called "queue" with the columns id,title,artist and to add the choosen song to this table using the "INSERT" command.
Something like this...
$addtoqueue= $db->prepare("INSERT INTO queue (title, artist) VALUES (?, ?)");
After adding a song to the queue, it should forward to a "queue.php" which displays the data from the queue-table and refreshes every 30 seconds or so.
So I would probably need some kind of "action" around the
echo "<tr><td>$showtitle</td>";
line...like
<tr><td>$showtitle</td>
But I have no idea how to "select" the specific dataset on which the visitor has clicked so that all columns of this dataset are inserted to the "queue" table.
p.s. I now tried the following, however I get errors on this and not the expected result of course
$queuedata = array();
if (isset($_GET['action']) and $_GET['action']=='queue') {
if ( isset($_GET['id']) ) {
$id_fetch = (INT) $_GET['id'];
if ($id_fetch > 0)
{
$dsfetch=$db->prepare("SELECT id, title, artist FROM songs WHERE id = ?");
$dsfetch->bind_param('iss', $id, $title, $artist);
$queuedata[] = $dsfetch;
}
}
$addqueue = $queuedata->prepare("INSERT INTO queue (id, title, artist) VALUES ('$id, $title, $artist')");
$addqueue->bind_param('sss', $id, $title, $artist);
if ($addqueue->execute()) {
header('Location: queue.php?action=feedback');
die();
}
}
if (isset($_POST['action']) and $_POST['action']=='feedback') {
echo '<p class="feedbacksuccess">Song successfully added to queue</p>';
}
and for the output
echo "<tr><td><a href=\"?action=queue&id=$queuedata->id;\">$showtitle</td>";
I get this error:
Error: Notice: Trying to get property of non-object in C:\xampp\htdocs\karaoke-files\suchtest2.php on line 55
I am also new to programming, but I will try to help out.
If I understand you need to make a selection and then send info to a php script.
Problem is that php is server side language, as far as I understand.
You need something to do the work on the front-end of things. So look up some javascrpt.
You can include bundle.js into your index file, and you it's functions for selecting items.
I will give some small examples of code that you can easily find online.
For example. Use javascript to select needed things.
And you function to make to do the work on the front-end.
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>`
Using javascript you can also call php script.
Read this post Call php function from javascript
Or you can simply use html form. You can fill it up with php using echo. In action you can specify what php to send data to.
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
And php script you are calling in this case action_page.php
can receive your input like so $firstName = $_REQUEST['firstname'];
And if you want for example to populate you form's drop down box and fill it with data you can read this post Populate a Drop down box from a mySQL table in PHP
It is a bit long answer, hope it will help you.
I finally found a solution
if (isset($_GET['action']) and $_GET['action']=='queue') {
if ( isset($_GET['id']) ) {
$id_fetch = (INT) $_GET['id'];
if ($id_fetch > 0)
{
$dsfetch=$db->prepare("SELECT id, title, artist FROM songs WHERE id = ?");
$dsfetch->bind_param('i', $id_fetch);
$dsfetch->execute();
$dsfetch->bind_result($id, $title, $artist);
while ($dsfetch->fetch()) {
echo $id . ' / '. $title .' '. $artist;
}
$addqueue = $db->prepare("INSERT INTO queue (id, title, artist, user) VALUES (?, ?, ?, ?)");
$addqueue->bind_param('isss', $id, $title, $artist, $name);
if ($addqueue->execute()) {
header('Location: index.php?aktion=feedback');
die();
}
}
}
}
if (isset($_GET['aktion']) and $_GET['aktion']=='feedback') {
echo '<p class="feedbacksuccess">Song has been added to queue</p>';
}
and later in the output
echo "<tr><td>$showtitle</td>";
Not sure wether or not this is "good code", but it works :-)
Thanks for all the hints
Project: Create a simple CMS for a photography website. My first project in php. :)
Problem: I am 90% finished with the CMS, but have ran into an issue of not being able to UPDATE row data after being READ from database.
The Goal: What I am trying to achieve seems simple. I have an admin page that reads image data from a database (id, image) and I am using a while loop to display this. It works great, and so does the delete button.
<?php
$query = "SELECT * FROM photos";
$select_all_photos_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_all_photos_query)) {
$photos_id = $row['photos_id'];
$photos_image = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_alt = $row['photos_alt'];
echo "<tr>
<td><input type='checkbox' name='photo' value='photo'></td>
<td><img src='../images/$photos_image' width='70'></td>
<td><a class='edit' href='edit_photo.php?&p_id={$photos_id}'>Edit</a></td>
<td><a onClick=\"javascript: return confirm('Are you sure?') \"class='delete' href='admin.php?delete={$photos_id}'>Delete</a></td>
</tr>";
}
?>
The problem I am having is the Edit Button in my while loop. I am using a get method in my href to get the edit_photo.php page with a parameter named "p_id" that is = to $photos_id.
Once I click the Edit button it sends me to the edit_photo.php page and I see all of the CORRECT information which tells me it is reading it correctly. I do get a error at the bottom ( Notice: Undefined variable: photos_file) See code below.
<?php
if (isset($_GET['p_id'])) {
$photo_id = $_GET['p_id'];
// Send query to photos table in database. //
$query = "SELECT * FROM photos WHERE photos_id = $photo_id";
$result = mysqli_query($connection, $query);
// Grab unique row from photos table in database. //
while($row = mysqli_fetch_assoc($result)) {
$photo_file = $row['photos_image'];
$photos_title = $row['photos_title'];
$photos_desc = $row['photos_alt'];
}
}
?>
Now. Here comes the big problem. When I try to update this information, the program busts. I even checked to see if my sql is correct, and if the queries are connecting to database. See code below.
<?php
if (isset($_POST['image'])) {
// After "Save" is pressed, the values white space is trimmed and assigned to a variable. //
$photos_title = trim($_POST['photos-title']);
$photos_desc = trim($_POST['photos-description']);
$photos_file = $_FILES['image']['name'];
$photos_file_temp = $_FILES['image']['name_tmp'];
// The new variables are sanitized. //
$photos_title = mysqli_real_escape_string($connection, $photos_title);
$photos_desc = mysqli_real_escape_string($connection, $photos_desc);
}
// Send the Update query to the database. //
$update_query = " UPDATE photos SET
photos_image = '$photos_file', photos_title = '$photos_title', photos_alt = '$photos_desc'
WHERE photos_id = '$photo_id' ";
// Test the SQL syntax. //
if(!$update_query) {
echo "Wrong." . " " . mysqli_error($connection);
}
else { echo "The SQL appears right..." . "<br>";
}
// Test the Update query. //
$update_result = mysqli_query($connection, $update_query);
if(!$update_result) {
echo "Didnt Connect." . " " . mysqli_error($connection);
} else {
echo "Sent query to to database.";
}
?>
<form action="edit_photo.php" class="settings-form" method="post" enctype="multipart/form-data">
<div class="form-group edit-preview">
<label for="image">Photo</label>
<img src= <?php echo "../images/$photo_file"?> >
<input type="file" name="file_upload">
</div>
<div class="form-group">
<label for="photos-title">Title</label>
<input type="text" name="photos-title" value= <?php echo "$photos_title" ?> class="form-control">
</div>
<div class="form-group">
<label for="photos-description">Description</label>
<textarea type="text" rows="4" name="photos-description" class="form-control" ><?php echo "$photos_desc" ?> </textarea>
</div>
<div class="form-group">
<input type="submit" name="image" class="btn btn-primary" value="Save Photo">
</div>
</form>
I have spent four days trying to figure this out with no luck.
For one thing, it's failing because of this ['name_tmp'].
The syntax is ['tmp_name'] - you had those inversed
Ref: http://php.net/manual/en/features.file-upload.php so your temp file never gets processed.
Then as per your edit and seeing your HTML form:
You're using name="file_upload" and then using the $_FILES['image'] array; those names need to match.
Error reporting would have helped you here.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional note.
If you are attempting to set the given (file) column as binary data instead of the path to the given file(s) as text, then you MUST escape it.
Otherwise, MySQL will throw you an error.
If that is the case, you will need to do the same as the others:
$photos_file = $_FILES['file_upload']['name']; // notice I changed it to what it should be
$photos_file = mysqli_real_escape_string($connection, $photos_file);
as per <input type="file" name="file_upload">
Check for errors against all your queries; you're not doing that in your $query = "SELECT * FROM photos WHERE photos_id = $photo_id"; query.
Add or die(mysqli_error($connection)) to all mysqli_query() should there be an error somewhere.
HTML stickler.
<textarea type="text" - <textarea> does not have a "text" type; remove it.
Footnotes.
If you want to check if your UPDATE truly was successful, use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Instead of else { echo "The SQL appears right..." . "<br>"; }
As outlined in comments, your code is open an SQL injection.
If $photo_id is an integer, change
$photo_id = $_GET['p_id'];
to
$photo_id = (int)$_GET['p_id'];
However, if that is a string, then you will need to quote it and escape it in your query.
<?php
$sent = $_GET['sent'];
if($sent == "yes") {
require('database_connection.php');
$name = $_GET['name'];
$desc = $_GET['desc'];
$email = $_SESSION['Memberid'];
date_default_timezone_set('Europe/London');
$date = date("d.m.y");
$sql = 'INSERT INTO `'.$email.'` (`id`, `Note`, `Share Url`, `Name`, `Description`, `Date`, `Type`) VALUES (\'\', \'Enter Note Here.\', \'\', \''.$name.'\', \''.$desc.'\', \''.$date.'\', \'Text\')';
$i = mysqli_query($dbc, $sql);
if($i) {
echo '<h2>Created note.</h2>';
header( 'Location: https://daccaa.com/edits' ) ;
} else {
echo '<h2>Failed to create a note for you.</h2>';
echo $name.'<br />';
echo $desc.'<br />';
echo $email.'<br />';
echo $date.'<br />';
echo $sql.'<br />';
echo $i.'<br />';
echo '<h1 style="visibility: hidden;">_</h1>';
echo 'Let us Know.';
}
} else {
echo '<div class="holder">
<h1>Lets create a new note:</h1>
<h3 style="visibility: hidden;">_</h3>
<form method="GET" action="#">
<input type="text" name="name" class="myBox" placeholder="Enter Name Here" />
<input type="text" name="desc" class="myBox" placeholder="Enter Description Here" /> <br />
<input type="hidden" value="yes" name="sent" />
<input type="submit" value="Generate" class="select" /><br />
Go Back
</form>
</div>
</div>';
}
?>
The code above is from my website, the idea behind the code is that it will create a new row in the database with the information upon its execution.
This is what the testing upon failure will echo:
new_test_name
new_test_desc
49
02.07.14
INSERT INTO `49` (`id`, `Note`, `Share Url`, `Name`, `Description`, `Date`, `Type`) VALUES ('', 'Enter Note Here.', '', 'new_test_name', 'new_test_desc', '02.07.14', 'Text')
But I still cannot seem to get the value to enter, This similar method works fine on another page, I can pretty much eliminate the fact that it could be in the database file as it works fine on another page in the same directory.
The structure of the MYSQL database is:
id | Note | Share Url | Name | Description | Date | Type
Please note I will be going over this later to add more ways to prevent SQL injection, I just want to get the basic code sorted out first.
From your error message: Duplicate entry '0' for key 'PRIMARY'
I'm assuming id is your primary key. Make sure you have auto increment setup on this column and then just exclude the id field completely in the query.
Right now your inserting a blank ID. Without strict enforcement, MySQL will convert an empty value to a 0 for an integer field. So you are trying to insert into ID 0 every time rather than creating a new row.
Dangers of your query
You are using unsanitized user input in your query (GET). GET, POST, REQUEST, and COOKIE variables should always be used with prepared queries.
Right now I could load your url with something like ?name="'; DELETE FROM 49 WHERE 1;" and wipe out your entire table. Research SQL injections and how to use MySQLi to make prepared queries.
I have a php message system on my site. With it users can send and receive messages to each other, but recently I have been trying to look for a way to include image attachments, so a user could send a photo with their message.
Messages are stored in ptb_messages, and the message part (subject and body) works fine but I've created a column in my table called 'image' which is a BLOB type and a 'name' column to store the image name. But I'm new to php and mysql and no matter what I try, I can't seem to get the image to store in the database.
Can anyone help me and let me know where I'm going wrong?
<?php ob_start(); ?>
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php"); ?>
<?php
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
$image = $POST ['image'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
$image = stripslashes($image);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content, image) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."', '".$image."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<div class="subject">
<input name="subject" type="text" id="subject" placeholder="Subject">
<input type="file" name="image" id="image">
<textarea name="message_content" id="message_content" cols="50" placeholder="Message" rows="8" style="resize:none; height: 100px;"></textarea>
<input type="image" src="assets/img/icons/loginarrow1.png" name="send_button" id="send_button" value="Send">
</form>
<?php } ?>
<?php ob_end_flush() ?>
My advice would be to store the URL of the image in the data base, not the image file itself. Store the images in the server file system. The reasoning goes to the notion of backup and performance, where moving a huge blob column is not a good thing to repeat many times. Plus if someone ever writes SELECT * without a LIMIT clause, you're going to get a table scan that transfers all of the images.
That said, if you insist on storing an image in a data base table, you might want to use base64_encode() to make the image file safe for binary transfer. There is a corresponding decode function that you would call before sending the image to the browser.
http://php.net/manual/en/function.base64-encode.php
HTH, ~Ray
Brief:
Based on a query, I have multiple checkboxes generated dynamically. The value of each checkbox is a string from one of the query's rows;
upon form submission, another script is ran (del.php). This script gets the array of checkboxes that were checked and loops through them so it can ran another two queries, which is the delete and update queries.
They don't work! if I try the INSERT query, it works fine. But the DELETE AND UPDATE don't.
Here is my code:
index.php:
<?php
$gettips = mysql_query('SELECT body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[0] ?></span></a><br />
<? $i++;
}
?>
and del.php :
foreach($_POST['checkboxes'] as $check) {
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
mysql_error() doesn't throw any errors. Database connection works in both files. The values of the checkboxes are strings. I'm able to delete the record by adding the string itself rather than the POST $variable to the query.
(I have also noticed that I'm not able to delete older records, only the newly added ones).
UPDATE:
I realized that trying to delete records where row='string' wasn't the best practice, at least in my case. So, instead of passing strings as values to the checkboxes in the form, I decided to give the id value of the table.
here is the new code:
<?php
$gettips = mysql_query('SELECT id,body FROM tips WHERE body!="" and approved!="yes" and approved!="no"')or die(mysql_error());
$i=0;
while($tips = mysql_fetch_array($gettips))
{ ?>
<input type="checkbox" name="checkboxes[]" value="<?php print $tips[0] ?>" />
<input type="checkbox" name="checkboxesno[]" value="<?php print $tips[0] ?>" />
<a class="names"> - <span><?php print $tips[1] ?></span></a><br />
<? $i++;
}
?>
and the delete queries:
foreach($_POST['checkboxes'] as $check) {
// echo "INSERT INTO approved (body) VALUES ('$check') <br>";
// echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
// echo "DELETE FROM tips WHERE id=$key <br>";
mysql_query("UPDATE tips SET approved='no' WHERE id=$key");
mysql_query("DELETE FROM tips WHERE id=$key ")or die(mysql_error());
}
I still don't know why the other way wasn't working, so if someone out there has a chance to explain, it would be awesome!
If you add some echo statements to your forloops and comment out the queries, you'll be able to see what exactly is being sent to mysql, and then you'll be better able to solve your problem.
foreach($_POST['checkboxes'] as $check) {
echo "INSERT INTO approved (body) VALUES ('$check') <br>";
echo "UPDATE tips SET approved='yes' WHERE body='$check'<br>";
//mysql_query("INSERT INTO approved (body) VALUES ('$check') ");
//mysql_query("UPDATE tips SET approved='yes' WHERE body='$check'");
}
foreach($_POST['checkboxesno'] as $key) {
echo "DELETE FROM tips WHERE body='$key' <br>";
//mysql_query("DELETE FROM tips WHERE body='$key' ")or die(mysql_error());
}
Try and protect yourself from SQL Injections: http://php.net/manual/en/security.database.sql-injection.php, can you please output the exact generated SQL query, it may be because of the SQL string not escaped.
Try escaping it with mysql_real_escape_string();