I think I am going to start a compilation of scripts that I have created and believe are useful Smile. Here is the first one, it is an extremely simple guestbook using php and mysql.


Code:

//guestbook.php
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook with Php</h1>
<p>This is a simple guestbook application written with php.  Just fill out the form below and click submit.
And the php will take care of the rest.</p>
<br />
<?php
//User defined database information
$dbname = "";
$dbuser = "";
$dbpass = "";
$dbhost = "";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link) {
   die("Couldn't connect to MySQL");
}

mysql_select_db($dbname) or die("Couldn't open $database");

$result = mysql_query("SELECT * FROM entries");
while ($row = mysql_fetch_array($result)) {
   echo "<strong>" . $row['name'] . "</strong>" . "&nbsp;&nbsp&nbsp&nbsp&nbsp&nbsp;" . "<em>". $row['email'] . "</em>";
   echo "<br />";
   echo $row['comments'];
   echo "<br />";
}
mysql_close($link);
?>
<form action="gbsubmit.php" method="post">
Name:<input type="text" name="name" />
<br />
E-mail:<input type="text" name="email" />
<br />
Comment:<input type="text" name="comment" />
<input type="submit" value="Send" />
</form>
</body>
</html>



Code:

//gbsubmit.php
<?php
//User defined database information
$dbname = "";
$dbuser = "";
$dbpass = "";
$dbhost = "";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link) {
   die("Couldn't connect to MySQL");
}

mysql_select_db($dbname) or die("Couldn't open $database");


$query = "INSERT INTO entries(name, email, comments) values('$_POST[name]','$_POST[email]','$_POST[comment]')";
mysql_query($query, $link) or die ("INSERT error: ".mysql_error());

mysql_close($link);
print "Thank you your entry has been submitted";
?>


Edit: Also this one isn't very safe, i forgot to strip entities i will fix that later.
You're not escaping the data that's being used in the queries; what if Peter O'Hanrahanrahan made a post? Smile See mysql_real_escape_string.

(Of course, you could have magic_quotes_gpc enabled, which only really serves to lend you a false sense of security).
benryves wrote:
You're not escaping the data that's being used in the queries; what if Peter O'Hanrahanrahan made a post? Smile See mysql_real_escape_string.

(Of course, you could have magic_quotes_gpc enabled, which only really serves to lend you a false sense of security).


I agree on the escaping to prevent SQL injection, also even if he had magic_quotes_gpc enabled for a published script he shouldn't rely on the end user having it without a notice of that. Also, can we get the sql or a definition of the structure in terms of what field types you were suggesting?
This should create the table for you assuming it is in a database named test.
Code:

CREATE TABLE  `test`.`entries` (
`name` TEXT NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL ,
`comments` VARCHAR( 300 ) NOT NULL
) ENGINE = MYISAM ;


Also, i edited saying it wasn't safe from injection Smile.

Edit: to use mysql_escape_real_string do i just add this line

Code:

$result = mysql_real_escape_string($result);


right before the while loop in guestbook.php?
You use it to escape user-provided strings that you are using to build queries to prevent SQL injection problems.

That is,

Code:
$query = "
    INSERT INTO
        `entries`
    SET
        `name`='" . mysql_real_escape_string($_POST['name']) . "',
        `email`='" . mysql_real_escape_string($_POST['email']) . "',
        `comments`='" . mysql_real_escape_string($_POST['comment']) . "'
";
mysql_query($query, $link) or die ("INSERT error: ".mysql_error());

Myself, I use a database object I've written that handles this escaping for me in a rather nicer fashion:

Code:
$db->query(
    "INSERT INTO `entries` SET `name`='{0}', `email`='{1}', `comments`='{2}'",
    $_POST['name'], $_POST['email'], $_POST['comment']
);
Alright thanks for that information, now I just need to apply it to the new set of scripts that I have created. The following set allows users to register, login, view their status, and of course an admin can register them. The user edit is a bit barbaric but it works and I couldn't think of any other way to do it.

Code:

<!---registration.php--->
<html>
<head>
<title>User Registration Form</title>
</head>
<body>
<h1>User Registration Form</h1>
<p>This is a simple registration form using php</p>
<form method="post" action="uregsubmit.php">
Name:<input type="text" name="name" />
<br />
Username:<input type="text" name="username" />
<br />
Password:<input type="password" name="password" />
<br />
Email:<input type="text" name="email" />
<br />
<input type="submit" value="Register" />
</form>
</body>
</html>


Code:

<?php
//uregsubmit.php
$dbname = "scripts";
$dbuser = "root";
$dbpass = "";
$dbhost = "localhost";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link){
   die("Could not connect to the database");
}

mysql_select_db($dbname) or die("Couldn't select database");
$query = "SELECT * FROM users WHERE username='$_POST[username]'";
$results = mysql_query($query, $link);
$row = mysql_fetch_array($results);
if ($row['username'] == $_POST[username]){
   echo "Username in use please try another";
} else {
   $query = "INSERT INTO users(name, username, password, email, registered, status) values('$_POST[name]','$_POST[username]','$_POST[password]',
         '$_POST[email]','0','0')";
   mysql_query($query,$link);
   mysql_close($link);
   print "Thank you for registering please wait for an admin to activate your account.<br />";
   print "<a href='login.php'>Login Page</a>";
}
?>


Code:

<!---login.php--->
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Simple Login Script in action</h1>
<p>This script is an extension of the registration.php script.  You type in your credentials from registration.php into this form to log
in pending your account has been verified by an admin.  The only downfall is the user has to make themselves an admin using phpmyadmin</p>
<form method="post" action="logsubmit.php">
Username:<input type="text" name="username" />
<br />
Password:<input type="password" name="password" />
<br />
<input type="submit" value="Login" />
</form>
</body>
</html>


Code:

<?php
//logsubmit.php
$dbname = "scripts";
$dbuser = "root";
$dbpass = "";
$dbhost = "localhost";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link) {
   die("Couldn't connect to the database");
}
mysql_select_db($dbname) or die("Couldn't select database");

$query = "SELECT * FROM users WHERE username='$_POST[username]' AND password='$_POST[password]'";
$results = mysql_query($query, $link);
$row = mysql_fetch_array($results);

if ($row['registered'] == 0) {
   print "Sorry your account has not yet been activated";
} else {
   session_start();
   $_SESSION['username'] = $_POST[username];
   $_SESSION['status'] = $row['status'];
   print "Thank you for logging in ";
   print $_SESSION['username'];
   print "<br />Please click the following link to see your status";
   print "<br /><a href='userstatus.php'>Status</a>";
}
mysql_close($link);
print "<br /><a href='logout.php'>Logout</a>";
?>


Code:

<?php
//userstatus.php
session_start();
print "Hello again ";
print $_SESSION['username'];
print "<br />";
if ($_SESSION['status'] == 1) {
   print "You are a regular user.";
   print "Since you are a regular user all you can do is sit here.";
}
if ($_SESSION['status'] == 2) {
   print "You are an administrator";
   print "<br />Since you are an administrator you can edit other users here";
   print "<br /><a href='useredit.php'>Edit Users</a>";
}
print "<br /><a href='logout.php'>Logout</a>";
?>


Code:

<?php
//useredit.php
session_start();

if ($_SESSION['status'] == 1) {
   print "You do not belong on this page.";
}
if ($_SESSION['status'] == 2){
$dbname = "scripts";
$dbuser = "root";
$dbpass = "";
$dbhost = "localhost";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$link) {
   die("Couldn't connect to the database");
}
mysql_select_db($dbname, $link);
$query = "SELECT * FROM users WHERE registered='0'";
$results = mysql_query($query);
print "<p>Here are the users that have yet to be approved.</p>";
while ($row = mysql_fetch_array($results)) {
   print $row['name'] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $row['username'] . "&nbsp;&nbsp;&nbsp;&nbsp;" . $row['password'] . "&nbsp;&nbsp;&nbsp;&nbsp;"
      . $row['email'];
   print "&nbsp;&nbsp;&nbsp;&nbsp;<a href=" . "useredited.php?registered=yes&uname=" . $row['username'] . ">Register</a><br />";
}
mysql_close($link);
}
print "<br /><a href='logout.php'>Logout</a>";
?>   


Code:

<?php
//useredited.php
session_start();
$dbname = "scripts";
$dbuser = "root";
$dbpass = "";
$dbhost = "localhost";

$link = mysql_connect($dbhost, $dbuser, $dbpass);
if (!link) {
   die("Couldn't connect to database");
}

mysql_select_db($dbname);

$query = "UPDATE users SET registered='1' WHERE username='$_GET[uname]'";
mysql_query($query, $link);
mysql_close($link);
print $_GET[uname] . " has been registered and can now log in.";
print "<br />Return to the user editor page here. ";
print "<a href='useredit.php'>Edit users</a>";
print "<br />Or you may logout here. ";
print "<a href='logout.php'>Logout</a>";
?>


Code:

<?php
//logout.php
session_start();
session_destroy();
print "You have been successfully logged out.";
?>
As a general rule passwords should be unknown to all but the user (doesn't always apply but most of the time) so you might want to sha1() the password (or am I remembering the function name wrong). I would also suggest that for this to be really useful it should have a check.php to check if the user is logged in so it can be adapted for use in a larger system for authentication. Also the escaping needs to be done here.
Thanks for the suggestions. I will make them and then I am going to try a really simple forum.
That sounds interesting, a while ago when I was not nearly as familiar with php as I am now I thought about making a cms but my plans were far to grand and were for a specific application that no longer has any meaning for me so it will not happen, I have however resumed work on a similar size or larger project that will take a while but should help me learn a lot to do well but may take a year or two more to finish. It will be coded in 2 languages (one for client side and one for server side) and will be a large game. I hope to get it working before I get to many people involved and I am planning on making at least part closed source but I am thinking about opening up the system to users to make third party clients just not their own servers. I will most likely get some help with the some aspects of the game once I get a better handle on what help I will need.
I was browsing the pear archives and found a couple packages related to user login and topics similar to what i attempted above. If I can make heads or tails out of the documentation I may go ahead and try to use it and see how well it works.
I have been looking at the pear package MDB2 and it works pretty great, next I am going to try the Auth package. Here is the guestbook rewritten using MDB2 with escaping, simple form validation, and html tag stripping. The new guestbook uses the same table structure as above with of course another name.


Code:

//mdb2guest.php
<html>
<head>
<title>MDB2 Guestbook</title>
<script language="JavaScript" type="text/javascript">
function validate() {
   if (document.guestbookform.name.value.length < 1){
      alert("Please enter your name");
      return false;
   }
   if (document.guestbookform.email.value.length < 1){
      alert("Please enter your email address");
      return false;
   }
   if (document.guestbookform.comment.value.length < 1){
      alert("Please enter a comment");
      return false;
   }
   return true;
}
</script>
</head>
<body>
<form method="post" action="mdb2guestsub.php" name="guestbookform" onSubmit="return validate();">
Name:<input type="text" name="name" maxlength="25" /><br />
E-mail: <input type="text" name="email" maxlength="50" /><br />
Comment: <input type="text" name="comment" maxlength="300" /><br />
<input type="submit" value="Submit" />
</form>
<p>Here are the previous entries in the guest book.</p>
<br />
<?php
require_once("MDB2.php");
$url = "mysql://root:@localhost/scripts";
$options = array('persistent' => true);
$con = MDB2::factory($url, $options);
if(PEAR::isError($con)) {
   die($con->getMessage());
}
$res =& $con->query("SELECT * FROM mdb2guest");
if(PEAR::isError($res)) {
   die($res->getMessage());
}
echo "<table border='1' width='75%'>";
echo "<tr>";
echo "<td bgcolor='green'><strong>Name</strong></td>";
echo "<td bgcolor='green'><strong>Email</strong></td>";
echo "<td bgcolor='green'><strong>Comment</strong></td>";
echo "</tr>";
while(($one = $res->fetchRow())) {
   echo "<tr>";
   for($i=0;$i<3;$i++){
      echo "<td>" . $one[$i] . "</td>";
   }
   echo "</tr>";
}
echo "</table>";
echo "</body>";
echo "</html>";
$con->disconnect();
?>



Code:

//mdguestsub.php
<?php
require_once("MDB2.php");
$url = "mysql://root:@localhost/scripts";
$options = array('persistent' => true);
$con = MDB2::factory($url, $options);
$con->setFetchMode(MDB2_FETCHMODE_ASSOC);
if(PEAR::isError($con)) {
   die($con->getMessage());
}
$name = $con->escape($_POST[name]);
$email = $con->escape($_POST[email]);
$comment = $con->escape($_POST[comment]);
$name = strip_tags($name);
$email = strip_tags($email);
$comment = strip_tags($comment);
$sql = "INSERT INTO mdb2guest (name, email, comment)
   values('$name','$email','$comment')";

$res =& $con->exec($sql);
if(PEAR::isError($affected)) {
   die($affected->getMessage());
}
$con->disconnect();
?>
<html>
<head>
<title>Entry submitted</title>
</head>
<body>
<p>Thank you your entry has been submitted to view it click
<a href="mdb2guest.php">here</a>.</p>
</body>
</html>
I have only three suggestions, first: separate user defined details into a config.php when there is more than one file. Second: don't tell anyone you have a mysql server running somewhere without a root password as it is very dangerous if anyone finds out and actually knows where and who you are, they can often figure out where the server is located on the network and have fun with your data. Third: never run a mysql server with no root password.
I know, but I am running it on localhost so it doesn't really matter to me that much. I will probably never even make use of these anyway, they are just for fun.
lafferjm wrote:
I know, but I am running it on localhost so it doesn't really matter to me that much. I will probably never even make use of these anyway, they are just for fun.


I disagree unless they are firewalled off from all computers other than localhost. If you are on a LAN and I an on said LAN and you have it running without the proper firewalling I could connect to it which was my concern, I am having trouble but I am trying to .htaccess off my localhost server for security because it won't show up in my firewall and it for some reason does not like the .htaccess file. I do however have mysql firewalled.
Easy solution:

Code:
skip-networking

in your MySQL config file. Totally secure, until someone breaks into your machine through some other vector.
The Tari wrote:
Easy solution:

Code:
skip-networking

in your MySQL config file. Totally secure, until someone breaks into your machine through some other vector.


Who is that in response to? I have mysql firewalled just not apache which is what is giving me issues.
Dunno anymore. It's good advice for anyone, I guess.
The Tari wrote:
Dunno anymore. It's good advice for anyone, I guess.
Aye, always err on the side of overkill and paranoia when it comes to security and privacy
I've been playing around with PEAR::Auth, and so far I actually like the way that it works. Plus it takes a lot of the work from me.
I've recently been working with ajax so my next script may be a sax knock off although I highly doubt it. On a side note I was debugging one of the ajax scripts I have, and I was missing the s in getElementsByTagName and the entire thing stopped working Smile
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 2
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement