adding image attachement to php messages? - php

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

Related

PHP Gallery CMS - Cannot Update Row in PHPMyadmin (LONG)

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.

block offensive words, block links etc in mysql insert query?

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

Images not displaying from database and file

i Have set up a site that lets user upload images then those images get displayed back on the home screen. but i hit a wall just now so i got past to letting the user upload an image then that images gets saved to a folder and a database but how can i do it so the image gets displayed on the home screen.
<?php
// Connect to database
$errmsg = "";
if (! #mysql_connect("localhost","alfred1000351","*******")) {
$errmsg = "Cannot connect to database";
}
#mysql_select_db("drp_2cgih5o233");
$q = <<<CREATE
create table pix (
pid int primary key not null auto_increment,
title text,
imgdata longblob)
CREATE;
#mysql_query($q);
// Insert any new image into database
if ($_REQUEST[completed] == 1) {
// Need to add - check for large upload. Otherwise the code
// will just duplicate old file ;-)
// ALSO - note that latest.img must be public write and in a
// live appliaction should be in another (safe!) directory.
move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
$instr = fopen("latest.img","rb");
$image = addslashes(fread($instr,filesize("latest.img")));
if (strlen($instr) < 149000) {
mysql_query ("insert into pix (title, imgdata) values (\"".
$_REQUEST[whatsit].
"\", \"".
$image.
"\")");
} else {
$errmsg = "Too large!";
}
}
// Find out about latest image
$gotten = #mysql_query("select * from pix order by pid desc limit 1");
if ($row = #mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
// Put up a picture of our training centre
$instr = fopen("../wellimg/ctco.jpg","rb");
$bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}
// If this is the image request, send out the image
if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>
<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
</body>
</html>
Here is my toughts:
Do not suppress warnings what you get from DB. They are real, and needed. Remove all #-characters from the front of DB-calls. If you get any notices, warnings, errors do not suppress them, correct them.
If you are making new code, consider using PDO as DB API, not the old, deprecating PHP MySQL API. It's as easy as MySQL API to use.
You only want try to create table only once, remove it from code which is executed many times.
You should check if $_REQUEST parameters exists, and not compare them if they do not. Also you need to put the parameter names in quotes, otherwise PHP thinks you are using constants, which you are not. So line if ($_REQUEST[completed] == 1) { must be fixed to if(isset($_REQUEST['completed']) && $_REQUEST['completed'] == 1) {. Same appies to whatisit and gim -params.
The code if (strlen($instr) < 149000) { does not work as intented, you cannot get length of resource. You are probably looking for this functionality: if (strlen($_FILES['imagefile']['size']) < 149000) {.
Same (as in step 4) with $row s you need to put the literas in quotes, so fix those lines as: $title = htmlspecialchars($row['title']); $bytes = $row['imgdata'];
Othewise than that it should work. However, it contains DB-security hole, which can lead to compromize your website, so I recommend you NOT to put this to any real site. Just for your own/friends fun.

create a sql table with image

I want to use php to create one table in sql which has images set content of the image and then I want fetch this table in html.
someone knows how this work? or someone has see the example on line?
please help. thanks a lot.
Here' is an article that will tell you all you want to know regarding storing images and the likes of in blob columns http://www.phpriot.com/articles/images-in-mysql
Ok, I understand that you want to upload an image file into a table in db, through your web app, using php, and then again you want to display that same image from the table in your web app(html page).
I will show the example for MySQL, using simple PHP 5.3
Create a sample table, say "photo_table" :
CREATE TABLE photo_table (photo_name_col VARCHAR(30),photo_img_col LONGBLOB);
Now for uploading the image file through your php page use the following in your html code:
<form name="photoForm" method="post" ENCTYPE="multipart/form-data" action="../insertImage.php" >
<input type="text" name="uploadFileName">
<!--commenting as I was not able to publish this note<input type="file" name="uploadFile" />-->
<!--Some other input fields if you want-->
<input type="submit" value="Submit"/>
</form>
Now, once the form "photoForm" is submitted, the form values are passed to "insertImage.php", where we will have the following code to upload the photo and its name into a table in our MySQL db:
<?php
$con=mysql_connect("ipAddressOfDB","username","password");
if(!$con){
die('Could not connect:'.mysql_error());
}
mysql_select_db("db_name",$con);
$image = $_FILES['uploadfile']['tmp_name'];
$imageName = $_POST['uploadFileName'];
$fp = fopen($image, 'r');
$content = fread($fp, filesize($image));
$content = addslashes($content);
fclose($fp);
$sql="insert into photo_table values('$imageName','$content')";
mysql_query($sql,$con);
?>
For displaying the photo from table into your html page, I use the following approach.
Fetch the image from db and copy it to a temporary location in the server.
<?php
$con=mysql_connect("ipAddressOfDB","username","password");
mysql_select_db("db_name",$con);
$sql="select * from photo_table where photo_name_col ='$uploadFileName'";
$result=mysql_query($sql,$con);
if($row=mysql_fetch_array($result)){
$fileName="generated/".$uploadFileName;
file_put_contents($fileName, $row['photo']);
}
echo "<img src='" . $fileName . "' />"; <!--this will display the image-->
?>

PHP MYSQL Changing the photo on my database

I am very new to PHP;
ADD.PHP - I have a form that collects the following information 1. name 2. email 3. phone and picture
pictures are stored on a directory folder on my server and then the filename of that photo is stored on my sql table.
VIEW.PHP - all the data in mysql is being displayed in this page including the photo in tabular format including the id of every record. The id being display is a hyperlink in which when clicked you will be directed to a page wherein you can edit the record contents:
below is the code for my EDIT.PHP
<?php
// Connects to your Database
mysql_connect("localhost", "user1", "12345") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
// Check whether the value for jobnumber is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen jobnumber
$result = mysql_query("select id, name, email,
phone, picture from employees where id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysql_error() . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
echo $name. "\n";
echo $row['email'] . "\n";
echo $row['phone'] . "\n";
echo "<img width=500px height=500px src=pics/" . $row['picture'].">" . "\n";
// form tag
echo '<form action="add2.php" method="POST">';
//display name
echo 'Name: <input type="text" name="name" value="';
echo $row['name'];
echo '"><br>';
//display email
echo 'email: <input type="text" name="email" value="';
echo $row['email'];
echo '"><br>';
//display phone
echo 'Phone: <input type="text" name="phone" value="';
echo $row['phone'];
echo '"><br>';
//display photo
echo 'Photo: <input type="text" name="photo" value="';
echo $row['picture'];
echo '"><br>';
echo '<input type="submit" value="Add">';
echo '</form>';
}
} else {
die("No valid data specified!");
}
?>
using this code, the test fields went well but the input box for the photo is blank and when i click the button the photo field in my database will be blank unless i uploaded a new photo?
how can the user change the existing photo? or retain the old photo if not being changed?
Assuming your employees.picture column stores the path to the image.
To upload a new photo, you're going to need to change a couple of things...
Your form needs to use the correct encoding type, ie
<form action="add2.php" method="post" enctype="multipart/form-data">
You also need to provide a "file" input element to accept the new photo, eg
<input type="file" name="photo">
To see if a new photo has been supplied, simply check (after detecting a valid POST request)
if ($_FILES['photo']['error'] == UPLOAD_ERR_OK) {
// file uploaded
}
see this link :http://www.w3schools.com/PHP/php_file_upload.asp
As to changing the existing photo, u should also save the name of the photo name in your db fom within the page add2.php
when any users wants to upload the photo for the second time, then a check should be made in add2.php to find whether a photo was previously uploaded. Then U can take a decision from the user from 2 yes, no buttons. If yes then UPDATE( not insert) the corresponding column in db table.
U can use jquery to take the decision and work accordingly. Any help needed with jquery?
IF it is for the first time that the uploading is gonna take place, then u can bypass the check process.
Clear?

Categories