Jump to content

Recommended Posts

I've started writing some PHP.  Good news is that I am able to access mysql and the site itself is stable.

 

I've sort of run into the problem the prevented me from jumping into PHP in the first place.  I've got three text boxes and it is already overwhelming.  I'm usually breaking working code because it is in front of me.

 

Anyone have any object oriented program advice?









<html>
<body>


<?php
$emailErr = $loginErr = $passwordErr = "";
$email = $login = $password = "";
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

$email=$_POST['email'];
$login=$_POST['login'];
$password=$_POST['password'];

function checkinput ($login, $email, $password)
{
if (empty($_POST["login"]))
{$loginErr = "login is required";
return =1;
}
else
{
$login = test_input($_POST["login"]);
// check if login only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$login))
{
$loginErr = "Only letters and white space allowed";
return =1;
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";
return =1;
}
else
{
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
return =1;
}
}

if (empty($_POST["password"]))
{$password = "";
return =1;
}
else
{
$password = test_input($_POST["password"]);
if (!preg_match("/\b(??:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$password))
{
$passwordErr = "Password should contain numbers letters and symbols";
return =1;
}
return = 0;
}
return $passwordErr;
return $emailErr;
return $loginErr;
}


#if (checkinput () == 1)
#{
#$act = htmlspecialchars($_SERVER["PHP_SELF"]);
#}
}
if (!checkinput ($login, $email, $password))
{
$email=$_POST['email'];
$login=$_POST['login'];
$password=$_POST['password'];
echo $email;
echo $login;
echo $password;
echo $emailErr;
echo "shinola";
} else{
echo "shit";
echo $emailErr;
}

function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

?>


<h2>Website Registration</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr><th>Your e-mail Address</th> <th> <input type="text" name="email" value="<?php echo $email;?>"></th>
<th><span class="error">* <?php echo $emailErr;?></span><br></th> </tr>
<tr><th>Choose Your Login Name</th> <th> <input type="text" name="login" value="<?php echo $login;?>"></th>
<th><span class="error">* <?php echo $loginErr;?></span> <br></th> </tr>
<tr><th>Your Site Password</th> <th><input type="text" name="password" value="<?php echo $password;?>"></th>
<th><span class="error">* <?php echo $passwordErr;?></span><br></th> </tr>
<tr><th><input type="submit" name="submit" value="Submit"></th></tr>
</table>
</form>

</body>
</html>
Link to comment
https://forums.phpfreaks.com/topic/285891-three-text-boxes-foobar/
Share on other sites

#1 - It's not 

return = 1;

it should be

return 1;

#2 - You've added a function just above where you want to use the code... what's the point? You're misunderstanding the use of OOP (functions and classes). I recommend following some tutorials on PHP + OOP to understand the uses better.

 

#3 - Get used to indenting your code so it's easier to follow

 

#4 - What are you getting overwhelmed with when using inputs?

@adam I agree with points 1, 3 and 4. But point2 I do not see your comment about oop being relevant to the OP's code.

 

@Augury. You are defining a function within a condition. The checkinput() function will only be defined when a POST request is made. If no post request is made then your code will produce a fatal error as it is calling a function which is not defined.

 

Your logic here is reversed.  What you should be doing is defining the function first, but only call that function when a POST request is made

// define function
function checkinput($args...) {
   // function code
}

// call function on post request
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    checkinput($args...);
}

As adam mentioned you are using return incorrectly and using it without understanding its behaviour. If you use a variable with return, it does not mean it returns that variable and then allows you to use that variable outside of the function. What it will do is return the value of that variable. It'll also immediately terminate the execution of that function at the point it is used.

 

 

Also I dont think using a regex pattern for matching urls is a good idea for validating passwords. As soon as you get the users password you should be encrypting it.

OK I'm working on a new approach.  This takes advantage of class and class inheritance.

 

I've got a function MemberDataCheck.  It is a switch.  It will return the entry or leave a blank.

 

It needs some clean up still.



<?php
class Member {
    private $id = NULL;
    private $userType = NULL;
    private $username = NULL;
    private $email = NULL;
    private $pass = NULL;
    private $firstname = NULL;
    private $lastname = NULL;
    private $validation_code = NULL;
    private $address = NULL;
    private $city = NULL;
    private $state = NULL;
    private $zipCode = NULL;

    public function getid() {
        return $this->id;
    }			
    public function getusername() {
        return $this->username;
    }
    public function getfirstname() {
        return $this->firstname;
    }
    public function getlastname() {
        return $this->lastname;
    }
    public function getpass() {
        return $this->pass;
    }
    public function getusertype() {
        return $this->usertype;
    }
    public function clearPass() {
        $this->pass = NULL;
    }
    public function getemail() {
        return $this->email;
    }
    public function isAdmin() {
        return ($this->userType == 'admin');
    }
    public function isSysop() {
        return ($this->userType == 'sysop');
    }
    public function isNewUser() {
        return ($this->userType == 'public');
    }
    public function canEditPage(Page $page) {
        return (($this->isAdmin() && ($this->id == $page->getCreatorId())) || $this->isSysop());
    }
    public function canCreatePage() {
        return ($this->isAdmin() || $this->isSysop());
    }
}			//@%@close class Member~@~Store user info and functions to access/control the flow of data.  The member attributes containing required and optional information.  The attributes must correspond to the database table columns:

class NoobMember extends Member
{
    }
    public function setusername() {
        $username = MemberDataCheck($_POST['username'], $usernameErr);
    }
    public function setfirstname() {
        $firstname = MemberDataCheck($_POST['firstname'], $firstnameErr);
    }
    public function setlastname() {
       $lastname  = MemberDataCheck($_POST['lastname'], $lastnameErr);
    }
    public function setpass() {
        $pass = MemberDataCheck($_POST['pass'], $passErr);
    }
    public function setemail() {
       $email  = MemberDataCheck($_POST['email'], $emailErr);
    }
}			//@%@close class NoobMember

function MemberDataCheck ($dataentry)
{
	switch ($dataentry, &$entryErr)
	{
		case $dataentry = ($username || $firstname || $lastname):
			$dataentry = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
			$errocode = "may only contain letters, numbers, spaces and hyphen"
			break;
		case $dataentry = $email:
			$dataentry = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
			$errorcode = "not a vaild e-mail address"
			break;
		default:
			$dataentry = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
			$errorcode = "invalid entry"
			break;
	}
	if (!$dataentry)
		$entryErr -> $errorcode;
	else $entryErr -> NULL;
return $dataentry
}			//@%@close function MemberDataCheck~@~non-required fields that are left empty should not be passed through MemberDataCheck


    $query = 'SELECT id, userType, username, email, pass, firstname, lastname, address, city, state, zipcode FROM users WHERE username=:username';
    $stmt = $pdo->prepare($query);
    $stmt->execute(array(':username' => $_POST['username']));
    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Member');
    $stored_user_data = $stmt->fetch();
			//~@~Verify Stored Hashed Password against input
    if ($stored_user_data) {
        $result = password_verify($_POST['pass'], $stored_user_data->getpass());
			if (!$result) {ForgotPassword();}
			else {LogonMember ();}
    } else {
		NoobJoin();}

			//@%@ ForgotPassword() LogonMember () NoobJoin are not written yet
?>
Edited by Augury

The array management system is apparently a bitch.

 

I syntax error 78%, over loop 10%, 12% I am in a vector tweak situation with no good guyz on my side.

 

Last know good code:

<?php
class Member {
public $member = array('id'=>'', 'usertype'=>'', 'username'=>'', 'email'=>'', 'pass'=>'', 'firstname'=>'', 'lastname'=>'', 'validation_code'=>'', 'address'=>'', 'city'=>'', 'state'=>'', 'zipcode'=>'', 'flag'=>'');
reset($member);
//public $member = array_fill_keys($mymember, '')
$member[2] = 'entryErr';
$member[username][4] = $member[email][4] = $member[firstname][4] = $member[lastname][4] = 'required';  
}			//@%@close class Member~@~member[0] holds the very index to our feilds, member[][1] is that members row, member[][2] is the err commentary, member[][3] is reserved for the old entry should we need it, member[][4] is a pop-o-matic flag due respect

class GetMember extends Member {
    public function getId() {
        return $this->$member[id];
    }			
    public function getusername() {
        return $this->$member[username];
    }
    public function getfirstname() {
        return $this->$member[firstname];
    }
    public function getlastname() {
        return $this->$member[lastname];
    }
    public function getpass() {
        return $this->$member[pass];
    }
    public function clearPass() {
        $this->pass[0] = NULL;
    }
    public function getusertype() {
        return $this->$member[usertype];
    }
    public function getemail() {
        return $this->$yourmember[email];
    }
    public function isAdmin() {
        return ($this->usertype[0] == 'admin');
    }
    public function isSysop() {
        return ($this->usertype[0] == 'sysop');
    }
    public function isNewUser() {
        return ($this->usertype[0] == 'public');
    }
    public function canEditPage(Page $page) {
        return (($this->isAdmin() && ($this->id == $page->getCreatorId())) || $this->isSysop());
    }
    public function canCreatePage() {
        return ($this->isAdmin() || $this->isSysop());
    }
}			//@%@close class Member~@~Store user info and functions to access/control the flow of data.  The member attributes containing required and optional information.  The attributes must correspond to the database table columns:

class NoobMember extends Member
{
  uses MemberDataCheck;
    public function setusername() {
        $member[username] = MemberDataCheck($_POST['username'], $member[username][entryErr]);
    }
    public function setfirstname() {
        $member[firstname] = MemberDataCheck($_POST['firstname'], $member[firstname][entryErr]);
    }
    public function setlastname() {
       $member[lastname] = MemberDataCheck($_POST['lastname'], $member[lastname][entryErr]);
    }
    public function setpass() {
        $member[pass] = MemberDataCheck($_POST['pass'], $member[pass][entryErr]);
    }
    public function setemail() {
       $member[emai]  = MemberDataCheck($_POST['email'], $member[email][entryErr]);
    }
}			//@%@close class NoobMember~@~the set arrays carry *the* value and error code. $array[2] may contain old values. $array[3] may contain flags.

trait MemberDataCheck {
function MemberDataCheck (&$dataentry, &$entryErr)
{
	switch (&$dataentry, &$entryErr)
	{
		case $dataentry = ($username || $firstname || $lastname):
			$dataentry = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
			$errocode = "may only contain letters, numbers, spaces and hyphen"
			break;
		case $dataentry = $email:
			$dataentry = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
			$errorcode = "not a vaild e-mail address"
			break;
		default:
			$dataentry = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
			$errorcode = "invalid entry"
			break;
	}
	if (!$dataentry)
		$entryErr -> $errorcode;
	else $entryErr -> NULL;
return $dataentry
}	}			//@%@close function MemberDataCheck, close trait MemberDataCheck~@~non-required fields that are left empty should not be passed through MemberDataCheck, do not alter the users expected input

trait FindMember {
	function FindMember
	{
	
function BiancaData ($mymember, $member) {
	$mymember_keys = array_keys($mymember);0
	$member_values = array_values($member);
		for ($i = 0; $i <= count($mymember) - 1; $i++) {
	    	$themember[$mymember_keys[$i]] = $member[$mymember_keys[$i]];
    		if (!$themember[$mymember_keys[$i]])
				{$themember[$mymember_keys[$i]] = $mymember[$mymember_keys[$i]];}
return $themember; 
}




    $query = 'SELECT id, usertype, username, email, pass, firstname, lastname, address, city, state, zipcode FROM users WHERE username=:username';
    $stmt = $pdo->prepare($query);
    $stmt->execute(array(':username' => $_POST['username']));
    $stmt->setFetchMode(PDO::FETCH_CLASS, 'Member');
    $stored_user_data = $stmt->fetch();
			//~@~Verify Stored Hashed Password against input
    if ($stored_user_data) {
        $result = password_verify($_POST['pass'], $stored_user_data->getPass());
			if (!$result) {ForgotPassword();}
			else {LogonMember ();}
    } else {
		NoobJoin();}

			//@%@ ForgotPassword() LogonMember () NoobJoin are not written yet
?>

The array armageddon did not prevent BiancaData () -- we should OoP have the consistency.  Is it bad karma to go for DataFag ()?  Did I offend XoR?

OK, I'm trying to go ground up and build a skeleton.  

 

The error code is like this :

 

array(4) { ["email"]=> string(0) "" ["login"]=> string(0) "" ["password"]=> string(0) "" ["submit"]=> string(6) "Submit" }
Fatal error: Call to undefined function DataCheck() in /var/www/CampKojak.com/skel.php on line 60

 

Thusly the data found its way into an array inside my class...it is to be dealt with by a function, as functions are -- and from anywhere firstly.

 

Am I supposed to draw up a header of some sort for this language?  I have not read of anything like this but I cannot even drop the fucker below the damn set.

 

http://CampKojak.com/skelpost.php



<html>
<body>


<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$passwordErr = $emailErr = $loginErr = 0;
$entryErr = $dataentry = 0;
class Member {
  use MemberDataCheck;
        public function __construct()
        {
                $member = array('id'=>'', 'usertype'=>'', 'username'=>'', 'email'=>'', 'pass'=>'', 'firstname'=>'', 'lastname'=>'', 'validation_code'=>'', 'address'=>'', 'city'=>'', 'state'=>'', 'zipcode'=>'', 'flag'=>'');
                //public $member = array_fill_keys($mymember, '')
                $member[2] = 'entryErr';
                $member['username'][4] = $member['email'][4] = $member['firstname'][4] = $member['lastname'][4] = 'required';  
        }
}


trait MemberDataCheck {
function DataCheck($keydata, &$valuedata)
{
        switch($keydata)
        {
                case $keydata == ($username || $firstname || $lastname):
                        $valuedata = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
                        //$errocode = "may only contain letters, numbers, spaces and hyphen";
                        break;
                case $keydata == $email:
                        $valuedata = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
                        //$errorcode = "not a vaild e-mail address";
                        break;
                default:
                        $valuedata = (filter_var($string, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/[- A-Za-z0-9]*/"))));
                        //$errorcode = "invalid entry";
                        break;
        }
        if (!$dataentry)
                $entryErr -> $errorcode;
        else $entryErr -> NULL;
//return $dataentry;
}       }




class NoobMember extends Member {
  use MemberDataCheck;

        function setdata()
        {
        $member = $_POST;
        var_dump($member);

        $member_keys = array_keys($member);
        $member_values = array_values($member);
        for ($i = 0; $i <= count($member) - 1; $i++) {
                //$member[$member_keys[$i]]  
                $member[$member_keys[$i]] = DataCheck($member_keys[$i], $member_values[$i]);    
        }

        var_dump($member);
        }

/*
    public function setusername() {
        $member[username] = MemberDataCheck($_POST['username'], $member[username][entryErr]);
    }
    public function setfirstname() {
        $member[firstname] = MemberDataCheck($_POST['firstname'], $member[firstname][entryErr]);
    }
    public function setlastname() {
       $member[lastname] = MemberDataCheck($_POST['lastname'], $member[lastname][entryErr]);
    }
    public function setpass() {
        $member[pass] = MemberDataCheck($_POST['pass'], $member[pass][entryErr]);
    }
    public function setemail() {
       $member[emai]  = MemberDataCheck($_POST['email'], $member[email][entryErr]);
    }
*/
}                       //@%@close class NoobMember~@~the set arrays carry *the* value and error code. $array[2] may contain old values. $array[3] may contain flags.


$noob = new NoobMember;
$noob->setdata();
//var_dump(each($_POST)); 
//var_dump($_POST);
//print_r($_POST);
?>



<h2>Website Registration</h2>
<p><span class="error">* required field.</span></p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <table>
        <tr><th>Your e-mail Address</th> <th> <input type="text" name="email"></th> 
        <tr><th>Choose Your Login Name</th> <th> <input type="text" name="login"></th> 
        <tr><th>Your Site Password</th> <th><input type="text" name="password"></th> 
        <tr><th><input type="submit" name="submit" value="Submit"></th></tr>
      </table>
    </form>

  </body>
</html>

Edited by Augury
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.