PDA

View Full Version : || Some more PHP basics. ||



Dan Williamson
22-12-2005, 02:29 AM
Hey guys.

Again i'm writing another PHP tutorial, i'm becoming pretty good at PHP. So I thought why not share my knowledge, we are going too be going through lots of stuff today. Including making a basic membership system in which i'm going too use on my site.

First we will start off with the basic stuff.


<?php

?>

Well this does nothing exept open a PHP tag and the close that PHP tag.

Introducing the echo tag. this tag is one of the most basic tags ever.


<?php

echo ("Hello Habbox Forum lets learn PHP");

?>

Now i'll explain in detail what this does. Anything in the ("") bit after the echo will be echoed and then ; mean you don't have too write it all out again you can simply put another echo or print tag there.

See it's really simple i'll now show you the print tag. The print tag basically serves the same purpose as the Echo tag.

heres a combine tag with them both in using the ; too seperate them.


<?php

echo ("This is the echo command and underneath is the print");
print ("Hello dear Habboxilians");

?>

Now you don't want too get confused by adding this into your source page so you can include the file using PHP includes which is as easy as the echo and print tag.


<?php

include ("PageURL.php");

?>

Works just the same as echo and print the ("") you put the URL of the page in the middle and you can still seperate them with ;

Keeping it basic at the moment as I know how you Habboxilians can be confused easily :)

Now we get too something which some people can find confusing the world of variables. You often come across variables in Maths but you also use them in PHP :)

Variables hold values and can be recognized by the American dollar sign $ and then after the $ sign goes the variable name followed by =""; some of it is just like a HTML tag.

Here is a variable example which is used in a decent PHP form


$name = $_REQUEST['name'];

See how it has variable name only it's requested somethig before the '

Hope this isn't too confusing yet :)

Moving on from the basics of variables

Heres something more basic :)

Displaying time and dates


<?PHP
echo date("D M d, Y H:i:s");
?>

Very simple, i'm sure this is self explanatory. Yet again it uses the echo tool, so it shows you echo can be used for quite a bit :)

Now we are going too make a very basic PHP form so you can recieve emails from the viewers of your site :)

Well first we'll need the HTML part of the form, lets call it the visual part of this contact form


<html>

<head>

<title>Comments</title>

</head>

<body><form action="mail.php" method="post">

Your Name: <input type="text" name="name"><br>

E-mail: <input type="text" name = "email"><br><br>

Your Comments:<br>

<textarea name="comment"></textarea><br><br>

<input type="submit" value="Tell Us!">

</form>

</body>

</html>

Not hard, i'm guessing you know what all this means.

Heres the PHP bit too the form and i'll walk you through it, yet it's terribly easy too understand, we're back using variables.


<?

$name=$_POST['name'];

$email=$_POST['email'];

$comment=$_POST['comment'];

$to="Write you email address here, it will not be visible";

$message=" $name sent you a comment on your site.\n They said $story\n\n Their e-mail address was: $email";

if(mail($to,"Comments From Your Site",$message,"From: $email\n")) {

echo "Your form was succsessful, write what you want here";

} else {

echo "The form didn't send, you can write some kind of messege here when your form has failed.";

}

?>

The variables are self explanatory the echo is self explanatry the form is incredibly simple.

So now you know how too create a PHP form, so you think your a PHP master now well guess what your not. I think I know a lot of PHP but I don't know as much as many people.

Basic user stats.

We may use some MySQL here so hopefully you know how too run queries :)

Grabbing and saving a viewers IP address is first We're going too use some MySQL here.

firstly, create a page called connect.php and add the following code inserting the data as needed.


<?php
$host = 'host';
$user = 'username';
$pass = 'password';
$db = 'database';

$conn = mysql_connect($host, $user, $pass) or die("Could not connect to database: " . mysql_error());
$dbselect = mysql_select_db($db, $conn) or die("Could not select database '" . $db . "': " . mysql_error());
?>

Thats basically connecting too an already made MySQL Database, you insert your host, LocalHost

Your username, password, and Database name.

Now we have a difficult part for newbies, setting up tables.

Run the SQL query in Phpmyadmin.


<?php
$sql = ("
CREATE TABLE unique_hits (
id INT (4) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
ipaddress varchar (15),
)
");

mysql_query($sql) or die("Error in creating unique hits table: " . mysql_error());
?>

You can change the name of the table if you wish :)

Now. You've connected to a MySQL Database and set up a table too hold the data in. Wow you guys on Habbox are getting good :)

Know me need a few more PHP codes.



<?php
$ip = $_SERVER['REMOTE_ADDR'];
$sql = mysql_query("SELECT id FROM unique_hits WHERE ipaddress = '$ip'") or die("Error querying table: " . mysql_error());
$unique = mysql_num_rows($sql);

if ($unique == 0) {
mysql_query("INSERT INTO $unique_hits (ipaddress) VALUES ('$ip')") or die("Error inserting user IP: " . mysql_error());
}
?>


You've probably guessed what this code does, well that is if you looked at it properly, you'll see the variable $ip and then the grab an IP code.

So basically this grabs the views IP address.

You should have put the IP script in a completely different file than connect.php and you should call this one IP.php

Now we want too intergrate this into our site, so above all your HTML on the page write this code.


<?php
require('connect.php');
require('IP.php');
?>

Thats basic enough

Now we move onto users online. People usually find this one too be the hardest and I've alway found this one difficult, maybe because i've always used the same code :)

Now I take no credit for this next script but I'll hopefully be able too write one myself, just I never tried.


$remote = $_SERVER["REMOTE_ADDR"];

$file = "log.txt"
;
$timeoutsecs = 30;

$timestamp = time();

$timeout = ($timestamp-$timeoutsecs);

$fp = fopen("$file", "a+");

$write = $remote."||".$timestamp."n";
fwrite($fp, $write);
fclose($fp);

$online_array = array();
$file_array = file($file);

foreach($file_array as $newdata){
list($ip, $time) = explode("||", $newdata);
if($time >= $timeout){
array_push($online_array, $ip);
}
}

$online_array = array_unique($online_array);

$online = count($online_array);
if ($online == "1") {
echo "People Online: $online";

} else {

echo "People Online: $online";
}
?>


You should save this file onlinepeople.php Now you have to create a text file called log.txt and upload it to the same directory as onlinepeople.php on your server! CHMOD log.txt to 777

Now for the big one.

I've highly edited a membership script and used it on my site, i've basically revamped the whole script so it looks awesome :)

Only advanced users may understand this. Firstly we need to set up the tables, so go on PHPmyadmin and run the SQL query


CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(30) NOT NULL default '',
`password` varchar(255) NOT NULL default '',
`email` varchar(40) NOT NULL default '',
`msn` varchar(250) NOT NULL default 'Not Specified',
`interests` varchar(250) NOT NULL default 'Not Specified',
`occupation` varchar(36) NOT NULL default 'Not Specified',
PRIMARY KEY (`id`)
) TYPE=MyISAM;

Then we of course need too connect too the MySQL Databse.

We're going too use cookies because people like to remember passwords using cookies


<?
ob_start();
$conn = mysql_connect("localhost","DB Username"," Db Password");
mysql_select_db(DbName or die(mysql_error());

$logged = MYSQL_QUERY("SELECT * from users WHERE id='$_COOKIE[id]' AND password = '$_COOKIE[pass]'");
$logged = mysql_fetch_array($logged);

?>

See even thats basic enough, just a normal connection. So now you have connected too a Database with tables. Now of course save this file as config.php

Now we need register.php :)


<?php
ob_start();

include("config.php");

if ($_POST[register]) {

$username = $_POST[username];
$password = $_POST[pass];
$cpassword = $_POST[cpass];
$email = $_POST[emai1];

if($username==NULL|$password==NULL|$cpassword==NUL L|$email==NULL) {

echo "A field was left blank.";
}else{

if($password != $cpassword) {

echo "Passwords do not match";
}else{

$password = md5($password);

$checkname = mysql_query("SELECT username FROM users WHERE username='$username'");
$checkname= mysql_num_rows($checkname);
$checkemail = mysql_query("SELECT email FROM users WHERE email='$email'");
$checkemail = mysql_num_rows($checkemail);
if ($checkemail>0|$checkname>0) {

echo "The username or email is already in use";
}else{

$username = htmlspecialchars($username);
$password = htmlspecialchars($password);
$email = htmlspecialchars($email);
information.

$query = mysql_query("INSERT INTO users (username, password, email) VALUES('$username','$password','$email')");

echo "You have successfully registered!";
}
}
}
}
else
{

echo ("
<center>
<form method=\"POST\">
Username: <input type=\"text\" size=\"15\" maxlength=\"25\" name=\"username\"><br />
Password: <input type=\"password\" size=\"15\" maxlength=\"25\" name=\"pass\"><br />
Confirm Password: <input type=\"password\" size=\"15\" maxlength=\"25\" name=\"cpass\"><br />
Email: <input type=\"text\" size=\"15\" maxlength=\"25\" name=\"emai1\"><br />
<input name=\"register\" type=\"submit\" value=\"Register\">
</form>
</center>
");
}
?>

This is basic enough. But we do a few things in this, we allow them too use cookies, we include config.php, we encrypt the passwords in MD5 Algorithym

We also do cool things such as check if the emails in use, see if the passwords match.

Moving on..

Heres the login;


<?
oB_start();

include("config.php");
if (!$logged[username])
{
if (!$_POST[login])
{
echo("
<center><form method=\"POST\">
<table>
<tr>
<td align=\"right\">
Username: <input type=\"text\" size=\"15\" maxlength=\"25\" name=\"username\">
</td>
</tr>
<tr>
<td align=\"right\">
Password: <input type=\"password\" size=\"15\" maxlength=\"25\" name=\"password\">
</td></tr><tr>
<td align=\"center\">
<input type=\"submit\" name=\"login\" value=\"Login\">
</td></tr><tr>
<td align=\"center\">
<a href=\"register.php\">Register Here</a>
</td></tr></table></form></center>");
}
if ($_POST[login]) {

$username=$_POST['username'];
$password = md5($_POST[password]);

$info = mysql_query("SELECT * FROM users WHERE username = '$username'") or die(mysql_error());
$data = mysql_fetch_array($info);
if($data[password] != $password) {

echo "Incorrect username or password!";
}else{

$query = mysql_query("SELECT * FROM users WHERE username = '$username'") or die(mysql_error());
$user = mysql_fetch_array($query);

setcookie("id", $user[id],time()+(60*60*24*5), "/", "");
setcookie("pass", $user[password],time()+(60*60*24*5), "/", "");
his/her password.
echo ("<meta http-equiv=\"Refresh\" content=\"0; URL=http://yoursite.com\"/>Thank You! You will be redirected");

}
}
}
else
{
// we now display the user controls.
echo ("<center>Welcome <b>$logged[username]</b><br /></center>
You can add all your HTML stuff here.
}
?>

We do some cool things here including logging someones username so it gives a friendly echo welcome.

Now don't forget too add this too the top of every page


<?
include("login.php");
?>

Now we can do all different things with this, install PM system, admin panel and editprofiles yet we're keeping too basics.

Need anymore help with all this tutorial feelfree too PM me :)

This tutorial is Copyright too Raremandan.

- Dan

ADAM:
22-12-2005, 02:34 AM
Great, that will help some people out

- Adam + rep if i can

Dan Williamson
22-12-2005, 02:43 AM
Thanks.

Took me over an hour too write, i'm knackered "/

- Dan

Rix
22-12-2005, 07:30 AM
good job dan

Luckyrare
22-12-2005, 08:44 AM
Good work mate, I am sure it will help people out ;)

nets
22-12-2005, 09:54 AM
Good tutorial, I only read the first few lines though.
Also if anyone is wondering what the difference between echo and print is. Echo is faster than print, but print is needed in more complicated situations.

timROGERS
22-12-2005, 10:06 AM
Dan, can you do a tutorial later with admin?

Dan Williamson
22-12-2005, 01:03 PM
Dan, can you do a tutorial later with admin?

Perhaps :)

- Dan

Want to hide these adverts? Register an account for free!