Google Answers Logo
View Question
 
Q: PHP ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: PHP
Category: Computers > Programming
Asked by: galgal1-ga
List Price: $20.00
Posted: 16 Jul 2003 20:43 PDT
Expires: 15 Aug 2003 20:43 PDT
Question ID: 231890
Hello,
I have 2 pretty simple questions.


The first one is that I want to edit the script below so that a
customer cannot put HTML codes into the text area but they can write
their resume with every simbol,number,and letter they want.
I want to protect my website so that anyone who writes html or any
other kind of code in my text area it would not effect anything.
Please give me any ideas or alternatives.


Here is the script I use to process the form:
<html>
<head><title>Empty fields</title></head>
<body>
<?php


$user="";
$host="";
$password="";
$database="";
$connection = mysql_connect($host,$user,$password)
or die ("Couldn't connect to server!");
$db = mysql_select_db($database,$connection)
or die ("Couldn't execute query!");




  /* set up array of field labels */
  $label_array = array ( "resume" => "Resume");
  foreach ($HTTP_POST_VARS as $key => $value)
  {
    /* check each field except middle name for blank fields */
    if ( $value == "" )
    {
       if ($key != "")
       {
          $blank_array[$key] = "blank";
       }
    }
    elseif ($key == "resume")
    {
        if (!ereg("^$",$HTTP_POST_VARS[$key]) )
        {
             $bad_format[$key] = "bad";
        }
    }
  }
  /* if any fields were not okay, display error message and form */
  if (@sizeof($blank_array) > 0 or @sizeof($bad_format) > 0)
  {
    if (@sizeof($blank_array) > 0)
    {
        /* display message for missing information */
        echo "<b>You didn't fill in one or more required fields. You
must enter:</b><br>";
        /* display list of missing information */
        foreach($blank_array as $key => $value)
        {
           echo "&nbsp;&nbsp;&nbsp;{$label_array[$key]}<br>";
        }
    }
    if (@sizeof($bad_format) > 0)
    {
        /* display message for bad information */
        echo "<b>One or more fields have information that appears to
be incorrect. Correct the format for:</b><br>";
        /* display list of bad information */
        foreach($bad_format as $key => $value)
        {
           echo "&nbsp;&nbsp;&nbsp;{$label_array[$key]}<br>";
        }
    }
    /* redisplay form */
    echo "<p><hr>
      <form action='CHECKRESUME.php' method='post'>
     <textarea rows=40 cols=70 name=resume maxlength=30 wrap=virtual
value=$resume></textarea>*<br><BR>
<input type='submit' value='Proceed'>\n

</form>";
   
 exit();
  }
  else
  {
  $query = "Insert Into Members (resume)
VALUES ('$resume')";
$result = mysql_query($query)
or die ("Couldn't execute query.");
}
?>
</body>
</html>
--------------------------------------------------------------------------


My next questions is I would like to have a form where the member can
upload a picture from their computer. Then I would like for the
picture to automaticlly appear onto the members area page where other
members can preview it. I am using MySQL,PHP,Apache, and my host is
webmasters.com if it is of any help. I always thought there was a nway
to have a form that sends the picture to my database and then I can
make it appear on my members area page but by what I have learned
while using MySQL I can't see any way to do that. Please inform me if
there is a way and exactly what I have to do.

Thank you for your help and have a great day!
Answer  
Subject: Re: PHP
Answered By: andyt-ga on 16 Jul 2003 21:18 PDT
Rated:5 out of 5 stars
 
Hello galgal1-ga,

Thanks for your question.

Stripping the html and php tags from an input form is a pretty
standard, and easy thing to do in php.  Fortunately, the php
developer's have a premade function which will enable you to do just
that.

Using the strip_tags() function, you can remove any and all html and
php tags from a given string.

From the php manual page on  strip_tags
(http://us4.php.net/strip_tags) the usage is as follows:
$stripped_string = strip_tags($input_string);

If you only wanted to remove certain tags (for example remove bold,
italic, or underline tags) you would set that as the optional
parameter, as follows:
$stripped_string = strip_tags($input_string, '<b><i><u>');


So for example, in your form to strip the tags from the $resume field,
you would write this line anytime before the MySQL insert.

$resume=strip_tags($resume);

For your next question, it looks like you want to be able to store
image (binary data) in a MySQL table.  You can insert binary image
data into a database, just like you can insert any other data.  A
great technical tutorial written by the O'Reilly Devcenter on how to
do it (with loads of examples) can be found at:
"Uploading, Saving, and Downloading Binary Data with MySQL"
http://www.onlamp.com/pub/a/php/2000/09/15/php_mysql.html

Search keywords used:

php+strip+tags

binary+data+in+mysql

A great timesaver is typing php.net/your_function here.  You can try
to guess the name of the function or type in anything instead of
'your_function, and if there's no exact match, then a search will be
done throughout the php.net manual.  It's a great resource.

If you require any additional help, please post a request for
clarification; and I'd be happy to assist you further.

Sincerely,
andyt-ga

Request for Answer Clarification by galgal1-ga on 17 Jul 2003 09:54 PDT
Hello Andy,
Thank you for all the help. I ran into a problem while using the
script on the website you told me. Here is what happend. I took his
example script and I edited it to my needs.

Here is the script:
<?php
$user="";
$host="";
$password="";
$database="";
$connection = mysql_connect($host,$user,$password)
or die ("Couldn't connect to server!");
$db = mysql_select_db($database,$connection)
or die ("Couldn't execute query!");

$sql = "SELECT * FROM Members ";
$sql .= "ORDER BY filename ASC";
$result = mysql_query($sql, $db);
$rows = mysql_num_rows($result);

echo "<table>\n";
echo " <tr>\n";
echo "  <td>Filename</td>\n";
echo "  <td>Type</td>\n";
echo "  <td>Size</td>\n";
echo "  <td>Description</td>\n";
echo "  <td> </td>\n";
echo " </tr>\n";

for ($i = 0; $i < $rows; $i++) {
  $data = mysql_fetch_object($result);
  // since our script is very small, i'm not going to escape out to
html mode here
  echo " <tr>\n";
  echo "  <td>$data->filename</td>\n";
  echo "  <td>$data->filetype</td>\n";
  echo "  <td>$data->filesize</td>\n";
  echo "  <td>" . stripslashes($data->description) . "</td>\n";
  echo "  <td>( <a href='download.php?id=$data->id_files'>Download</a>
)</td>\n";
  echo " </tr>\n";
}
mysql_free_result($result);
mysql_close($db);
?>

When I take this script to the internet this is what it shows:

Warning: mysql_query(): supplied argument is not a valid MySQL-Link
resource in /usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/viewpictures.php
on line 13

Warning: mysql_num_rows(): supplied argument is not a valid MySQL
result resource in /usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/viewpictures.php
on line 14
Filename Type Size Description  

Warning: mysql_free_result(): supplied argument is not a valid MySQL
result resource in /usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/viewpictures.php
on line 36

Warning: mysql_close(): supplied argument is not a valid MySQL-Link
resource in /usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/viewpictures.php
on line 37
 
Please tell me what is wrong with the script so I can get this done.

Another thing is I want my users only to upload gif and jpg files. How
can I edit this script (that I also got from that website) so that it
would only accept gif and jpg files?

Here is the script:

<?php

$user="";
$host="";
$password="";
$database="";
$connection = mysql_connect($host,$user,$password)
or die ("Couldn't connect to server!");
$db = mysql_select_db($database,$connection)
or die ("Couldn't execute query!");


if ($action == "upload") {
  // ok, let's get the uploaded data and insert it into the db now
  include "open_db.inc";

  if (isset($binFile) && $binFile != "none") {
    $data = addslashes(fread(fopen($binFile, "r"),
filesize($binFile)));
    $strDescription = addslashes(nl2br($txtDescription));
    $sql = "INSERT INTO Members";
    $sql .= "(description, bin_data, filename, filesize, filetype) ";
    $sql .= "VALUES ('$strDescription', '$data', ";
    $sql .= "'$binFile_name', '$binFile_size', '$binFile_type')";
    $result = mysql_query($sql, $db);
    mysql_free_result($result); // it's always nice to clean up!
    echo "Thank you. The new file was successfully added to our
database.<br><br>";
    echo "<a href='form.php'>Continue</a>";
  }
  mysql_close();

} else {
?>
<HTML>
<BODY>
<FORM METHOD="post" ACTION="form.php" ENCTYPE="multipart/form-data">
 <INPUT TYPE="hidden" NAME="MAX_FILE_SIZE" VALUE="1000000">
 <INPUT TYPE="hidden" NAME="action" VALUE="upload">
 <TABLE BORDER="1">
  <TR>
   <TD>Description: </TD>
   <TD><TEXTAREA NAME="txtDescription" ROWS="10"
COLS="50"></TEXTAREA></TD>
  </TR>
  <TR>
   <TD>File: </TD>
   <TD><INPUT TYPE="file" NAME="binFile"></TD>
  </TR>
  <TR>
   <TD COLSPAN="2"><INPUT TYPE="submit" VALUE="Upload"></TD>
  </TR>
 </TABLE>
</FORM>
</BODY>
</HTML>
<?php
}
?>


Thank you for everything and have a great day.

Clarification of Answer by andyt-ga on 18 Jul 2003 07:31 PDT
Hello galgal1-ga,
Without seeing your database schema it will be a little tough to debug
your code. (being as the warning are related to the SQL statement you
have constructed.)  The PHP looks ok to me, but the error could be in
the datatype of the database.

Let's break the problem down into smaller chunks. Can you connect to
the MySQL database to process your form without binary data?  Can you
use the prewritten code at O'Reilly without any warnings?

The code you posted looks like it's selecting image data from the
member's table, and the example code you are modifity is inserting
data; so I'm not really sure what your goal is.

In regards to limiting the filetype, you could use the following code
to check the mime file type.
If you have something like this in your form:

<INPUT TYPE="file" NAME="binFile"
  
You could test the mime type with this code:

//where binFile_type is a variable from php that holds the mime file
type
//check to see this variable is either image/gif or image/jpeg
 if(strtolower($HTTP_POST_VARS[binFile_type]) != "image/gif" |
strtolower($HTTP_POST_VARS[binFile_type])!="image/jpeg")
 { 
    echo "Only jpg or gif files are accepted."; 
    exit; 
 } 
  

-andyt-ga

Request for Answer Clarification by galgal1-ga on 18 Jul 2003 08:28 PDT
Hello,
Thank you for all of your help. My real goal is to make is so that
when a user puts in their picture it goes inot my database and then is
shown on an members list along with their other info that has been
stored in the database. I don't understand what you mean by binary
data, could you please explain it to me. Also when I try to run the
script from O'Reilly it tells me that my server cannot authorize the
script so I am looking for an alternative.

Thank you and have a great day!

Clarification of Answer by andyt-ga on 18 Jul 2003 09:17 PDT
galgal1-ga,

Binary data in this case simply means a picture.  Binary is made up of
the 1's and 0's that computer's use to keep track of data.  It could
consist of pictures, applications, text, but when we refer to text we
call it text data, and when we refer to pictures it's called binary
data.

There's many other alternatives to the article I linked you to, below
I've listed a couple for you to check out.  When you say that the
script you are trying to run isn't authorized I'm guessing this means
that you  must change the access permissions of the file for the
webserver to run it.  This is done with the chmod command.  You
usually access it by right clicking on the file in your ftp program,
and selecting 'chmod'.  You must give the script enough access
priviledges in order to upload files.  A good tutorial for chmod can
be found here: http://catcode.com/teachmod/  Alternatively, while
testing give full permission to the file by right clicking and
selecting all the boxes or typing 777 and then see if the code works.

Links to some alternative tutorials:
Upload image file to MySQL as BLOB:
http://www.weberdev.com/get_example.php3?count=3688
How to store images directly in the sql database:
http://www.phpbuilder.com/columns/florian19991014.php3

Hope this was at all helpful,
andyt-ga

Request for Answer Clarification by galgal1-ga on 18 Jul 2003 15:05 PDT
Hello,
Thank you for your time and effort. I went to another one of the links
(www.phpbuilder.com) and I got the script you had the link pointed to.
After I made a new table in my database just as the instructions tell
me to and I put in the connection information in the script, I tried
it and some errors came up.
Below you can see the script with all the information about my
database such as host name, user name, and password. I have put them
in even though I have them marked with * here. You can go to my
website and try the script yourself and you will see the error
messages that are below. Here is the website:
http://www.htauditions.com/headshotform.php



Here is the script that I got and I just put in my database
information(nothing else has been changed):

<?php

// store.php3 - by Florian Dittmer <dittmer@gmx.net>
// Example php script to demonstrate the storing of binary files into
// an sql database. More information can be found at
http://www.phpbuilder.com/
?>

<HTML>
<HEAD><TITLE>Store binary data into SQL Database</TITLE></HEAD>
<BODY>

<?php
// code that will be executed if the form has been submitted:

if ($submit) {

// connect to the database
// (you may have to adjust the hostname,username or password)

MYSQL_CONNECT("*********","*******","************");
mysql_select_db("*********");

$data = addslashes(fread(fopen($form_data, "r"),
filesize($form_data)));

$result=MYSQL_QUERY("INSERT INTO binary_data
(description,bin_data,filename,filesize,filetype) ".
"VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");

$id= mysql_insert_id();
print "<p>This file has the following Database ID: <b>$id</b>";

MYSQL_CLOSE();

} else {

// else show the form to submit new data:
?>

<form method="post" action="<?php echo $PHP_SELF; ?>"
enctype="multipart/form-data">
File Description:<br>
<input type="text" name="form_description" size="40">
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>File to upload/store in database:<br>
<input type="file" name="form_data" size="40">
<p><input type="submit" name="submit" value="submit">
</form>

<?php

}

?>

</BODY>
</HTML> 





Here are the errors you see if you press Submit:

Warning: fopen("", "r") - Success in
/usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/headshotform.php
on line 24

Warning: Unable to access in
/usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/headshotform.php
on line 24

Warning: fread(): supplied argument is not a valid File-Handle
resource in /usr/local/4admin/apache/vhosts/htauditions.com/httpdocs/headshotform.php
on line 24

This file has the following Database ID: 0 





Thank you for you time!

Request for Answer Clarification by galgal1-ga on 19 Jul 2003 09:48 PDT
Hi,
yesterday I got a message from google that there was activity in my
account at 9:00 pm. Then I tried to got to the google account and I
did not see an answer. If you sent me an answer please resend it.

Thank you and have a great day!

Clarification of Answer by andyt-ga on 19 Jul 2003 18:58 PDT
Apoligies for the extended response time.  It seems that script was
written when PHP's default was to have global variables on.  Now, with
PHP 4, global variables are usually turned off.  It looks like that's
where the error comes in.
Basically it means that to access variables from forms in PHP3, you
could just use $variable, but in PHP 4 when globals are turned off,
you must use $_REQUEST['variable'] (they did this for security
purposes)
The script that should work is below.  I'll test it out soon, and
provide confirmation.

<?php 
// store.php3 - by Florian Dittmer <dittmer@gmx.net> 
// Example php script to demonstrate the storing of binary files into
// an sql database. More information can be found at
http://www.phpbuilder.com/

?> 
<HTML> 
<HEAD><TITLE>Store binary data into SQL Database</TITLE></HEAD> 
<BODY> 
<?php 

//the following couple of lines were the only ones changed
$submit=$_REQUEST['submit'];
$form_data=$_REQUEST['form_data'];
$form_description=$_REQUEST['form_description'];
$form_data_name=$_REQUEST['form_data_name'];
$form_data_size=$_REQUEST['form_data_size'];
$form_data_type=$_REQUEST['form_data_type'];

// code that will be executed if the form has been submitted: 
 
if ($submit) { 
 
// connect to the database 
// (you may have to adjust the hostname,username or password) 
 
MYSQL_CONNECT("*********","*******","************"); 
mysql_select_db("*********"); 
 
$data = addslashes(fread(fopen($form_data, "r"),
filesize($form_data)));
 
$result=MYSQL_QUERY("INSERT INTO binary_data
(description,bin_data,filename,filesize,filetype) ".
"VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");
 
$id= mysql_insert_id(); 
print "<p>This file has the following Database ID: <b>$id</b>"; 
 
MYSQL_CLOSE(); 
 
} else { 
 
// else show the form to submit new data: 
?> 
 
<form method="post" action="<?php echo $PHP_SELF; ?>"
enctype="multipart/form-data">
File Description:<br> 
<input type="text" name="form_description" size="40"> 
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000"> 
<br>File to upload/store in database:<br> 
<input type="file" name="form_data" size="40"> 
<p><input type="submit" name="submit" value="submit"> 
</form> 
 
<?php 
 
} 
 
?> 
 
</BODY> 
</HTML>  


This is the first coding type question I've answered on GA, it's not
really optimized for this type of debugging stuff, sorry if things
aren't going very smoothly.

andyt-ga

Clarification of Answer by andyt-ga on 19 Jul 2003 20:44 PDT
Ok, found one (from one of the comments on the phpbuilder site that
works with php4.  if the above code doesn't work, give this one a
shot.



<HTML> 
<HEAD><TITLE>Store binary data into SQL Database</TITLE></HEAD> 
<BODY> 
<?php 
if (isset($HTTP_POST_VARS['form_description'])) { 
MYSQL_CONNECT("localhost","***","***"); 
mysql_select_db("ga"); 
$form_description = $HTTP_POST_VARS['form_description']; 
$form_data_type = $_FILES['userfile']['type']; 
$form_data_name = $_FILES['userfile']['name']; 
$form_data_size = $_FILES['userfile']['size']; 
$data = addslashes(fread(fopen($_FILES['userfile']['tmp_name'], "r"),
filesize($_FILES['userfile']['tmp_name'])));
$result=MYSQL_QUERY("INSERT INTO binary_data
(description,bin_data,filename,filesize,filetype) ".
"VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");
$id= mysql_insert_id(); 
print "<p>This file has the following Database ID: <b>$id</b>"; 
MYSQL_CLOSE(); 
} else { 
?> 
<form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>"
method="post" enctype="multipart/form-data" name="picup"
target="_self" id="picup">
File Description:<br> 
<input type="text" name="form_description"  size="40"> 
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="1000000"> 
<br>File to upload/store in database:<br> 
<input type="file" name="userfile"  size="40"> 
<p><input type="submit" name="submit" value="submit"> 
</form> 
<?php 
}
?> 
</BODY> 
</HTML> 

You would then retrieve the image with this script


<?php

// getdata.php3 - by Florian Dittmer <dittmer@gmx.net>
// Example php script to demonstrate the direct passing of binary data
// to the user. More infos at http://www.phpbuilder.com
// Syntax: getdata.php3?id=<id>
$id=$_REQUEST['id'];
if($id) {

    // you may have to modify login information for your database
server:
    @MYSQL_CONNECT("localhost","root","password");

    @mysql_select_db("binary_data");

    $query = "select bin_data,filetype from binary_data where id=$id";
    $result = @MYSQL_QUERY($query);

    $data = @MYSQL_RESULT($result,0,"bin_data");
    $type = @MYSQL_RESULT($result,0,"filetype");

    Header( "Content-type: $type");
    echo $data;

};
?>  


cheers,
andyt-ga

Clarification of Answer by andyt-ga on 20 Jul 2003 14:57 PDT
Hello again,

I uploaded the upload script, as well as the getdata script to your
webpage.
I SUGGEST YOU CHANGE YOUR PASSWORD ASAP.  This is a public forum, and
you never know what somebody might do to your private data.

the upload script is called uploadga.php, and the getdata script is
called getdata.php.  it is called with getdata.php?id=(number) where
the number is the data id of the stored file.

cheers,
andyt-ga

Request for Answer Clarification by galgal1-ga on 21 Jul 2003 15:52 PDT
Thank you for your help and I think you were one of the best
professionals. I will have another question up today and I will love
it if you would answer it. Bow I will close this question and go to
the next one. Again, thank you so much and have a great day!

Clarification of Answer by andyt-ga on 21 Jul 2003 16:45 PDT
Glad to be of service.  I'll take a look at the next question, and see
if I can answer it.

cheers,
andyt-ga
galgal1-ga rated this answer:5 out of 5 stars and gave an additional tip of: $20.00
He gave me more help than I expected. Execelent answer!

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy