Welcome to Dream.In.Code
Getting PHP Help is Easy!

Join 136,479 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 1,632 people online right now. Registration is fast and FREE... Join Now!




Using objects/classes to create web pages

 
Reply to this topicStart new topic

Using objects/classes to create web pages, I don't fully understand the use of classes/objects...

livelonger87
2 Jul, 2008 - 11:58 AM
Post #1

New D.I.C Head
*

Joined: 27 May, 2008
Posts: 30


My Contributions
I'm trying to create web pages using this new method I've found. However, I can't seem to fully percieve the full use of them. I understand (Well sorta), how to use one...
CODE

class userlogin
{
var $username;
var $password;
function filtervariables()
  {
  $this -> username = stripslashes($_POST['username']);
  $this -> password = stripslashes($_POST['password']);
  }
function checkinput()
  {
  if(!$this -> username || !$this -> password)
  {
  print "Please enter your username and password before logging in. <br>";
  }
  else
  {
  $sql = "SELECT * FROM users";
  $sqlquery = mysql_query($sql);
  $count = 0;
  while ($count = 0; $count++);
  if($count == "1")
  {
  $_SESSION['user'] = $this -> username;
  setcookie("asfagag", "asfasf", time()+3600);
  }
else
$_SESSION['user'] = "0"
}
}
}

Anyway, could someone explain to me, the use of classes? I mean, the do's and dont's, the rules (I.e. the limits and stretches of a class), the requirements to call one, the implementation of user inputs into a class (See above attempt), mysql inputs (I.e. setting a tablename in another class; recalling it in another); basically how to use them properly...

Thanks!!:)
User is offlineProfile CardPM
+Quote Post

akozlik
RE: Using Objects/classes To Create Web Pages
2 Jul, 2008 - 12:11 PM
Post #2

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 611



Thanked: 24 times
Dream Kudos: 750
My Contributions
Hey livelonger,

Well classes are used in a method of programming known as Object Oriented Programming, or OOP. OOP is a relatively new (i.e. past few years) concept that has been emerging as a great way to program. The point of OOP is to basically modularize your entire site. It makes code reusability easier and allows you to protect data. C++, Java, and PHP 5 are examples of languages that utilize OOP.

Entire books have been written on OOP because it's such a broad topic. All the questions you have would really require a lot of explanation to get across. I can highly recommend a book on PHP OOP though that may get you on your way. It's called Object Oriented PHP and can be found at:

http://www.amazon.com/Object-Oriented-PHP-...YDFEPH1XW9Y56P3

Check your library for a copy.

You can also check out this website:

http://www.devarticles.com/c/a/PHP/Object-...ramming-in-PHP/

I hope that all points you in the right direction. Take care.
User is offlineProfile CardPM
+Quote Post

livelonger87
RE: Using Objects/classes To Create Web Pages
2 Jul, 2008 - 11:34 PM
Post #3

New D.I.C Head
*

Joined: 27 May, 2008
Posts: 30


My Contributions
QUOTE(akozlik @ 2 Jul, 2008 - 01:11 PM) *

Hey livelonger,

Well classes are used in a method of programming known as Object Oriented Programming, or OOP. OOP is a relatively new (i.e. past few years) concept that has been emerging as a great way to program. The point of OOP is to basically modularize your entire site. It makes code reusability easier and allows you to protect data. C++, Java, and PHP 5 are examples of languages that utilize OOP.

Entire books have been written on OOP because it's such a broad topic. All the questions you have would really require a lot of explanation to get across. I can highly recommend a book on PHP OOP though that may get you on your way. It's called Object Oriented PHP and can be found at:

http://www.amazon.com/Object-Oriented-PHP-...YDFEPH1XW9Y56P3

Check your library for a copy.

You can also check out this website:

http://www.devarticles.com/c/a/PHP/Object-...ramming-in-PHP/

I hope that all points you in the right direction. Take care.

Hey! Thanks!!
I created this just recently....
CODE

//userobjects.php
<?php
class User {
    var $username;
    var $password;
    var $email;
    var $loginusername;
    var $loginpassword;
    function variables() {
        $this -> username = mysql_real_escape_string(strlen(stripslashes($_POST['username'])));
        $this -> password = mysql_real_escape_string(strlen(stripslashes($_POST['password'])));
        $this -> email = mysql_real_escape_string(strlen(stripslashes($_POST['email'])));
        $this -> loginusername = mysql_real_escape_string(stripslashes($_POST['usernamelogin']));
        $this -> loginpassword = mysql_real_escape_string(stripslashes($_POST['passwordlogin']));
    }
    function checkregistration ()  {
        if(!$this -> username || !$this -> password || !$this -> email)
        {
            print "You must fill in the required fields in order to sign up. <br><br>";
        }
        else if($this -> username > 8)
        {
            print "Your username must be less than 8 characters in length. <br><br>";
        }
        else if($this -> password < 6)
        {
            print "Your password must be at least over 6 characters long. <br><br>";
        }
        else
        {
            $this -> username = $_POST['username'];
            $this -> password = $_POST['password'];
            $this -> email = $_POST['email'];
            $sql1 = "INSERT INTO Registered_users (Username, Password, Email) VALUES ('". $this -> username. "', '". $this -> password. "', '". $this -> email. "')";
            $querysql1 = mysql_query($sql1);
            if(!$querysql1)
            {
                print "Error: Cannot query user into database";
            }
            else
            {
                print "Thank you <b>". $this -> username. "</b> for signing up.<br><br>";
            }
        }
    }
    function login()
    {
        if(!$this -> loginusername || !$this -> loginpassword)
        {
            print "You must enter your username and password in order to login. <br><br>";
        }
        else
        {
            $loginusername = $this -> loginusername;
            $loginpassword = $this -> loginpassword;
            $sql2 = "SELECT * FROM Registered_users WHERE Username='$loginusername' and Password='$loginpassword'";
            $querysql2 = mysql_query($sql2);
            if(!$querysql2)
            {
                print "Error: Cannot query <b>". $this -> loginusername. "</b> from database.<br><br>";
            }
            else
            {
                $count = 0;
                while($a = mysql_fetch_assoc($querysql2))
                {
                    $count++;
                }
                if($count == 1)
                {
                    $username1 = $this -> loginusername;
                    $_SESSION['loggedin'] == "$username1";
                    setcookie("asfasf", "asfasf", time()+200);
                    header("location: index.php");
                }
                else
                {
                    $_SESSION['loggedin'] == "false";
                    header("location: http://www.google.com/");
                }
            }
        }
    }
}
?>
//index.php
<?php
require("connect.php");
include("userobjects.php");
?>

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="header">

<?php
$new = new User;
$new -> variables();
$new -> login();
if($new -> login($_SESSION['loggedin'] == "false"))
{
?>
<div id="sub-header">
<?php
//
?>
<form action="index.php" name="login" id="login" method="post">
Username: <input type="text" name="usernamelogin" id="usernamelogin">
Password: <input type="text" name="passwordlogin" id="passwordlogin">
<input type="submit" name="loginuser" id="loginuser">
</form>
</div>
<?php
}
else
{
    print "Welcome user";
}
?>
</div>
<div id="content">
<?php
$newuser = new User;
$newuser -> variables();
$newuser -> login();
if($newuser -> login($_SESSION['loggedin'] == "false"))
{
?>
<div id="registration">
<?php
$newuser -> checkregistration();
?>
<form action="index.php" name="registration1" id="registration1" method="post">
You must signup in order to view the contents of this site.  <br><br>
Username: <input type="text" name="username" id="username">
Password: <input type="text" name="password" id="password">
Email: <input type="text" name="email" id="email">
<input type="submit" name="signup" id="signup">
</form>
</div>
<?php
}
else
{
    print "Welcome user";
}
?>
</div>
</body>
</html>

I'm not sure how to call the functions from within the class properly sad.gif Can you help me out here?
User is offlineProfile CardPM
+Quote Post

livelonger87
RE: Using Objects/classes To Create Web Pages
3 Jul, 2008 - 10:37 AM
Post #4

New D.I.C Head
*

Joined: 27 May, 2008
Posts: 30


My Contributions
Please help!!
User is offlineProfile CardPM
+Quote Post

akozlik
RE: Using Objects/classes To Create Web Pages
3 Jul, 2008 - 10:39 AM
Post #5

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 611



Thanked: 24 times
Dream Kudos: 750
My Contributions
Be patient. I'm writing your solution now
User is offlineProfile CardPM
+Quote Post

akozlik
RE: Using Objects/classes To Create Web Pages
3 Jul, 2008 - 11:01 AM
Post #6

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 611



Thanked: 24 times
Dream Kudos: 750
My Contributions
Wow, there are a lot of serious issues in that code. Rather than try to explain everything, check out this quick short class I wrote

php

class User {

function User($username, $password) {
$this->username = mysql_real_escape_string($username);
$this->password = mysql_real_escape_string($password);
}

function login() {
$sql = "select * from Registered_Users where username = '$this->username' and Password = '$this->password'";
$result = mysql_query($sql) or die ( mysql_error() );

if ( mysql_num_rows($result) == 1 ) {
$_SESSION['loggedIn'] == "true";
return 1;
} else {
return 0;
}
}
}


$user = new User($username, $password);

if ($user->login()) {
// Whatever you want the success code to be
} else {
// Whatever you want the fail code to be
}



Notice I have a function named User. This is called when the user is instantiated. You pass in the username and the password. This sets those variables to the class.

The following would go on your index page

php

$user = new User($_POST['username'], $_POST['password']);
if ($user->login()) {
// Whatever you want the success code to be
} else {
// Whatever you want the fail code to be
}


Typtcally you would sanitze your data before sending it through to the class, but I covered that in the class with the mysql_real_escape_string() function.

Really study my code and compare it to yours to see where the faults are. Key points to notice are that I pass values into the class. I'm only keeping track of hte username and password. I sanitize my data. I return a value from the function rather than doing all the success fail/code in there.

Also, when I instantiate, I use $user->login(username, password). Note there are no space between the variable and the function. I'm not sure if PHP picks up on that but it might.

Those are just a few notes. Keep studying OOP. You're getting close but you're not quite there. Take it easy.
User is offlineProfile CardPM
+Quote Post

livelonger87
RE: Using Objects/classes To Create Web Pages
3 Jul, 2008 - 12:49 PM
Post #7

New D.I.C Head
*

Joined: 27 May, 2008
Posts: 30


My Contributions
Hey thanks man!! I really appreciate all the help!! However, I'm still stuck sad.gif

How would I create a checklogin or registration function? I've tried to do so, but it doesn't seem to work...
CODE

class login {
function ($username, $password)
  {
  $this -> username = mysql_real_escape_string(stripslashes($username));
$this -> password = mysql_real_escape_string(stripslashes($password));
//how would I check if the user has submitted it? I mean, if empty, return a message, else login the user.  Same for a registration technique; return message if username is x amount of characters in length, else, register user.

On the index page,
$user = new User($_POST['Username'], $_POST['Password']);
//Lemme go back to something....

Back to the objects page,
var $username;
var $password;

function filter_var($username, $password) {
$this -> username = mysql_real_escape_string($username);
$this -> password = mysql_real_escape_string($password);
}
function check_var($username, $password) {
if(!$this -> username || !$this -> password)
  {
  print "You must enter a username and password in order to login. <br>";
}
//else??
}

Anyway, back to index.php...
We've already defined the username and password globals...
So..
$user -> filter_var($_POST['Username'], $_POST['Password']);
$user -> check_var($_POST['Username'], $_POST['Password']);
//kinda lost now :(


I want to be able to return a value if the user enters a wrong value or just simply hits the submit button. However, if the post is fine, submit the details or login the user and gather the content.

I would prefer to use globals if they were to pass through each function consistently (I.e. if the first function were to filter them, the other functions view them as filtered variables?)


User is offlineProfile CardPM
+Quote Post

akozlik
RE: Using Objects/classes To Create Web Pages
3 Jul, 2008 - 12:54 PM
Post #8

D.I.C Addict
Group Icon

Joined: 25 Feb, 2008
Posts: 611



Thanked: 24 times
Dream Kudos: 750
My Contributions
Take a look at the strlen() and isset() functions on php.net

http://us2.php.net/strlen
http://us2.php.net/isset

That should get you on your way to figuring it out. Also, your first few lines of code will not work

Make sure you plan out your class before you start typing away. Know precisely what you're trying to do, write it out on paper, then start coding it. Planning is the most important thing.

User is offlineProfile CardPM
+Quote Post

livelonger87
RE: Using Objects/classes To Create Web Pages
6 Jul, 2008 - 08:36 AM
Post #9

New D.I.C Head
*

Joined: 27 May, 2008
Posts: 30


My Contributions
*sigh*... Thanks for the help, but I'm trying to percieve the use of classes. Here's a short example of what I'm attempting to committ...

CODE

//userobjects.php

<?php
Class checkinput {
       //set a global variable, accessible through each function, saving me from recreating the variable everytime I create a function.
    var $username;
    function variables($var) {
               //variable will be altered to $_POST['username'] on the next page.  The argument $var will tell the function to give the global a value of whatever is contained within $var.
        $this -> username = $var;
    }
    function filter_var($this -> username) {
//I'm a little lost here... I'm trying to sanatize the variable.  Since $var has altered the global, perhaps I could sanatize the global through the argument? Some help here please...
        mysql_real_escape_string(striptags(stripslashes($var)));
    }
    function check_var($this -> username) {
                //same here... :(
        if(!$var)
        {
            print "Please enter a username. <br>";
        }
        else
        {
            print "Thank you <b>". $var. "</b> for submitting. <br>.";
        }
    }
}
?>


Here's the index.php file...

CODE

<html>
<body>
<?php
//if user hits the submit button...
if($_POST['submit'])
{
        //initiate a new instance of the class checkinput...
    $user = new checkinput();
        //the global will then be valued $_POST['username'] through the function variables
    $user -> variables($_POST['username']);
    $user -> filter_var($var);
       //uhh... filter variable?
    $user -> check_var($var);
      //same
}
?>
<form action="index.php" name="forma" id="forma" method="post">
Username: <input type="text" name="username" id="username">
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>

Hopefully you get that idea of what I'm trying to understand.
User is offlineProfile CardPM
+Quote Post

joeyadms
RE: Using Objects/classes To Create Web Pages
6 Jul, 2008 - 10:58 AM
Post #10

D.I.C Head
Group Icon

Joined: 4 May, 2008
Posts: 145



Thanked: 7 times
Dream Kudos: 600
Expert In: PHP, Web Security

My Contributions
Here is how you would use variables inside of a class.

CODE

<?php

class testClass {
    public $name = 'John'; // A public var
    
    public function getVar($var){
        if(isset($this->$var)){
            return $this->$var;
        } else {
            return "No Var Available";
        }
    }
    
    public function setName($name){
        $this->name = $val;
    }
}

$test = new testClass();

echo $test->getVar('name'); // prints John
$test->setName('Joey');
echo $test->getVar('name'); // prints Joey



Variables are not global in scope to the methods(functions) inside the class, to access class variables use $this->variablename
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 06:19PM

Live PHP Help!

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month