Feedback gevraagd: basis php

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

Iris B

Iris B

28/08/2015 11:53:36
Quote Anchor link
Dag allen,

Ik zou heel graag feedback willen op mijn code. Tot nu toe heb ik op de procedural manier geoefend, maar wil nu overstappen op OOP.
Voordat ik dat doe, wil ik graag wat opbouwende kritiek ontvangen op wat ik tot nu toe gedaan heb :)

Komptie: linkje (verloopt over 2 weken)


NOTES:
- alleen de login/signup/settings pagina's werken.
- een db table genaamd 'clients' is nodig met de volgende velden: userID (unique,auto incr), email (unique), passw, firstname, lastname, address, city, zip, country, confirm, confirm_date, date_signup


Ben benieuwd! Be gentle ;)

Groetjes en fijn weekend, Iris
Gewijzigd op 28/08/2015 11:54:11 door Iris B
 
PHP hulp

PHP hulp

29/03/2024 07:57:49
 
- Ariën  -
Beheerder

- Ariën -

28/08/2015 12:03:38
Quote Anchor link
Kan je de relevante code niet in het topic plaatsen? Dat houdt het topic wat overzichtelijker.

De meeste mensen zijn ook niet zo happig om te downloaden, vrees ik.
Gewijzigd op 28/08/2015 12:04:59 door - Ariën -
 
Iris B

Iris B

28/08/2015 12:17:41
Quote Anchor link
Hoi Aar,

Dat kan ik doen, maar het zijn wel 4 verschillende paginas. Dus of het er overzichtelijker van wordt weet ik niet.
 
- Ariën  -
Beheerder

- Ariën -

28/08/2015 12:20:07
Quote Anchor link
Of op Pastebin plaasten, of uploaden als *.phps (source)
Gewijzigd op 28/08/2015 12:20:45 door - Ariën -
 
Iris B

Iris B

28/08/2015 12:23:17
Quote Anchor link
Signup

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100


<?php

require_once "includes/functions.php";

// store all errors in array
$errors = array();
$success = array();

// check if the form is submitted and all fields are filled in
if(isset($_POST['signup'])){

    // make sure error array is empty before we begin checking
    unset($errors);
    unset($success);

    $email = emailValidate(strip_tags($_POST['email']));
    $password = strip_tags($_POST['password']);

    // do we have any blank fields?
    if(!$email || !$password){

        $errors[] = "Please fill in all the form fields";

    }
else{

        // hash the password before storing it to the db
        // @TODO move this inside function

        $hash = password_hash($password, PASSWORD_DEFAULT);

        // check if email already exists
        $user = readUser($email);

        // no, we did not find a record!
        if($user == false) {

            // add the user to the db
            newUser($email, $hash);

            // send confirmation request
            // check how to enable sending email from your localhost!

            sendConfirm($email);


            // store email in session
            $_SESSION['email'] = $email;

            // Sign up successful, go to user's settings page
            header("location: settings.php ");

        }
else{

            // a record is returned, therefore the email already exists
            $errors[] = "This email address already exists";
        }
    }
}

include_once "includes/header.php";
include_once "includes/navigation.php";
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
        <h1>Sign up</h1>
            <?php
            if(!empty($errors)){
                echo "<div class=\"alert alert-danger\" role=\"alert\"><h2 class=\"h4\">Oops!</h2><ul class=\"unstyled\">";
                    foreach($errors as $error){
                        echo "<li>$error</li>";
                    }

                echo "</ul></div>";
            }

            if(!empty($success)){
                echo "<div class=\"alert alert-success\" role=\"alert\"><h2 class=\"h4\">Yipee!</h2><ul class=\"unstyled\">";
                foreach($success as $message){
                    echo "<li>$message</li>";
                }

                echo "</ul></div>";
            }
?>

            <form id="signup" role="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
             <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="Email address" />
                    <label>Password</label>
                    <input type="password" name="password" class="form-control" placeholder="Your password" />
                    <hr />
                    <input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />
                </div>
            </form>

            <p>Already have an account? <a href="login.php" target="_self" title="Login">Log in here</a></p>
        </div>
    </div>
</div>
<?php

include_once "includes/footer.php";

?>


Login

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90

<?php

require_once "includes/functions.php";

/*
* if form is submitted, check credentials in db
* if credentials match, go to dashboard page
* if not, show error
*/

// store all errors in array

$errors = array();

if(isset($_POST['login'])){

    // make sure error array is empty before we begin checking
    unset($errors);

    $email = emailValidate(strip_tags($_POST['email']));
    $password = strip_tags($_POST['password']);

    // do we have any blank fields?
    if(!$email || !$password){

        $errors[] = "Please fill in all the form fields correctly";

    }
else{

        // check if email exists and password is correct
        $user = logIn($email, $password);

        if($user != false) {

           // Yes, user is found and credentials match

            $_SESSION["email"] = $email;
            header("location: dashboard.php");

        }
else {

            // credentials are incorrect
            $errors[] = "Wrong email or password, please try again";
        }

    }
}


// TODO add 'Remember me' functionality

include_once "includes/header.php";
include_once "includes/navigation.php";
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
        <h1>Login</h1>
            <?php
            if(!empty($errors)){
                echo "<div class=\"alert alert-danger\" role=\"alert\"><h2 class=\"h4\">Oops!</h2><ul class=\"unstyled\">";
                    foreach($errors as $error){
                        echo "<li>$error</li>";
                    }

                echo "</ul></div>";
            }
?>

            <form role="form" id="login" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="[email protected]" />
                    <label>Password</label>
                    <input type="password" name="password" class="form-control" placeholder="Your password" />
                    <hr />
                    <div class="checkbox">
                        <label>
                            <input name="remember" type="checkbox"> Remember me
                        </label>
                    </div>
                    <input type="submit" name="login" class="btn btn-primary" />
                </div>
            </form>

            <p>Need an account? <a href="signup.php" target="_self" title="Sign Up">Sign up here</a></p>
        </div>
    </div>
</div>
<?php

include_once "includes/footer.php";

?>

Toevoeging op 28/08/2015 12:25:33:

Settings

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207

<?php

session_start();
if(!isset($_SESSION['email'])){
    header("location: index.php");
}

require_once "includes/functions.php";
include_once "includes/header.php";
include_once "includes/navigation.php";

// lookup user details to populate forms with current user data
$user = readUser($_SESSION['email']);

// store all messages in arrays
$errors = array();
$success = array();

// update personal details
if(isset($_POST['personal'])){

    // clear both messages arrays
    unset ($errors);
    unset ($success);

    $_POST['firstname'] = strip_tags($_POST['firstname']);
    $_POST['lastname'] = strip_tags($_POST['lastname']);
    $_POST['address'] = strip_tags($_POST['address']);
    $_POST['city'] = strip_tags($_POST['city']);
    $_POST['zip'] = strip_tags($_POST['zip']);
    $_POST['country'] = strip_tags($_POST['country']);
    $_POST['userID'] = strip_tags($_POST['userID']);

    // do we have any blank fields? No blanks allowed!
    if(!$_POST['firstname'] || !$_POST['lastname'] || !$_POST['address'] || !$_POST['city'] || !$_POST['zip'] || !$_POST['country']){

        $errors[] = "Please fill in all the form fields correctly. All fields are required.";

    }
else{

        $update = updateUser($_POST);

        if ($update !== false){

            $user = $update;
            $success[] = "Your personal details are updated successfully";

        }
else{

            // update failed, user wasn't found
            $errors[] = "Sorry, your details weren't updated, please try again.";

        }

    }

}

// update email
if(isset($_POST['emailupdate'])){

    // clear both messages arrays
    unset ($errors);
    unset ($success);

    $_POST['email'] = emailValidate(strip_tags($_POST['email']));
    $_POST['userID'] = strip_tags($_POST['userID']);

    // Do we have any blank fields?
    if(!$_POST['email']){

        $errors[] = "You did not enter an email address.";

    }
else{

        // Let's update the email address.
        // If the update fails it means the email already exists and we throw an error


        $update = updateEmail($_POST['email'], $_POST['userID']);

        if($update !== false){

            $user = $update;
            $success[] = "Your email is updated successfully";

        }
else{

            // Bummer, email already in use, show an error
            $errors[] = "This email is already in use! Please choose another.";

        }

    }

}


// update password
if(isset($_POST['password'])){

    // clear both messages arrays
    unset ($errors);
    unset ($success);

    // sanitize data input
    $old_pw = strip_tags($_POST['old_pw']);
    $new_pw = strip_tags($_POST['new_pw']);
    $check_pw = strip_tags($_POST['check_pw']);
    $userID = strip_tags($_POST['userID']);

    // no empty fields allowed
    if(!$old_pw || !$new_pw || !$check_pw){

        $errors[] = "Please fill in all the form fields correctly. All fields are required.";

    }
else{

        $update = updatePw($old_pw, $new_pw, $check_pw, $userID);

        if ($update !== false){

            $success[] = "Your password is now successfully updated.";

        }
else{

            $errors[] = "Sorry, your passwords didn't match. Please try again.";
        }

    }


}

?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <h1>Settings</h1>
            <?php
            if(!empty($errors)){
                echo "<div class=\"alert alert-danger\" role=\"alert\"><h2 class=\"h4\">Oops!</h2><ul class=\"unstyled\">";
                foreach($errors as $error){
                    echo "<li>$error</li>";
                }

                echo "</ul></div>";
            }

            if(!empty($success)){
                echo "<div class=\"alert alert-success\" role=\"alert\"><h2 class=\"h4\">Yippee!</h2><ul class=\"unstyled\">";
                foreach($success as $message){
                    echo "<li>$message</li>";
                }

                echo "</ul></div>";
            }


            ?>

        </div>
        <div class="col-md-4">
            <form role="form" name="personal" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                <h2>Personal details</h2>
                <div class="form-group">
                    <label>First Name</label>
                    <input type="firstname" name="firstname" class="form-control" value="<?php if (!empty($user->firstname)) echo $user->firstname; ?>" placeholder="First Name" />
                    <label>Last Name</label>
                    <input type="lastname" name="lastname" class="form-control" value="<?php if (!empty($user->lastname)) echo $user->lastname;  ?>" placeholder="Last Name" />
                    <label>Address</label>
                    <input type="address" name="address" class="form-control" value="<?php if (!empty($user->address)) echo $user->address;  ?>" placeholder="Address" />
                    <label>City</label>
                    <input type="city" name="city" class="form-control" value="<?php if (!empty($user->city)) echo $user->city;  ?>" placeholder="City" />
                    <label>Zip code</label>
                    <input type="zip" name="zip" class="form-control" value="<?php if (!empty($user->zip)) echo $user->zip;  ?>" placeholder="Zip" />
                    <label>Country</label>
                    <select type="country" name="country" class="form-control" >
                        <?php if (!empty($user->country)) echo "<option>$user->country</option>"; echo countryList();  ?>
                    </select>
                    <input type="hidden" name="userID" value="<?php echo $user->userID; ?>"/>
                </div>
                <input type="submit" name="personal" value="Update" class="btn btn-sm btn-primary" />
            </form>
            </div>
        <div class="col-md-4">
            <form role="form" name="email" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                <h2>Account details</h2>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?php if (!empty($user->email)) echo $user->email;  ?>" placeholder="Email" />
                    <input type="hidden" name="userID" value="<?php echo $user->userID; ?>"/>
                </div>
                <input type="submit" name="emailupdate" value="Update" class="btn btn-sm btn-primary" />
            </form>
            <hr/>
            <form role="form" name="password" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
                <div class="form-group">
                    <label>Update your password</label>
                    <input type="password" name="old_pw" class="form-control" placeholder="Current password" />
                    <label>Choose a new password</label>
                    <input type="password" name="new_pw" class="form-control" placeholder="New password" />
                    <label>Type it again</label>
                    <input type="password" name="check_pw" class="form-control" placeholder="New password" />
                    <input type="hidden" name="userID" value="<?php echo $user->userID; ?>"/>
                </div>
                <input type="submit" name="password" value="Reset" class="btn btn-sm btn-primary" />
            </form>
        </div>
    </div>
</div>
<?php

include_once "includes/footer.php";

?>

Toevoeging op 28/08/2015 12:26:40:

Alle functies

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

<?php

// start session
session_start();


function
dbConnect(){
    // connect to db. If connection fails, return false, otherwise return PDO object.

    // db settings

    $host = '';
    $dbname = '';
    $user = '';
    $pw = '';

    try{
        // connect to db and return pdo opject if connection succeeds
        $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pw);
        $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $result = $DBH;

    }
catch(PDOException $e){
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3,"../logs.txt");
    }


    return $result;

}

function
logIn($email, $password){

    try{

        $pdo = dbConnect();
        $stm = $pdo->prepare("SELECT email, passw
                                     FROM `clients`
                                     WHERE email = :email"
);
        $stm->bindParam(":email", $email);
        $stm->execute();

        // if rows are returned, the email exists and we can proceed
        if($stm->rowCount() > 0){

            // check if password matches the hash stored in the db

            $user = $stm->fetchObject();

            $hash = $user->passw;

            if (password_verify($password, $hash)) {

                // credentials are correct

                $result = $user;

            }
else{

                // password is incorrect

                $result = false;
            }

        }
else{

            // email doesn't exist

            $result = false;
        }

    }
catch(PDOException $e){
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3,"../logs.txt");
    }


    return $result;
}

function
newUser($email, $password){

    try{
        $pdo = dbConnect();
        $stm = $pdo->prepare("INSERT INTO `clients` (email, passw)
                                     VALUES (:email, :passw)"
);
        $stm->execute(
            array(
                ":email" => $email,
                ":passw" => $password
            )
        );


        $result = true;

    }
catch(PDOException $e){
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3,"../logs.txt");
    }


    return $result;
}


function
readUser($email){

    try{

        $pdo = dbConnect();
        $stm = $pdo->prepare("SELECT email,
                                            userID,
                                            firstname,
                                            lastname,
                                            address,
                                            city,
                                            zip,
                                            country
                                     FROM `clients`
                                     WHERE email = :email"
);

        $stm->bindParam(":email", $email);
        $stm->execute();

        // if rows are returned, the user exists and we can proceed
        if($stm->rowCount() > 0){

            $result = $stm->fetchObject();;

        }
else{

            $result = false;
        }

    }
catch(PDOException $e){
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3,"../logs.txt");
    }


    return $result;
}

function
updateUser($user){

    try{

        if (is_array($user)) {

            // update user details, check if form is submitted

                $pdo = dbConnect();
                $stm = $pdo->prepare("UPDATE `clients` SET
                                                              firstname = :firstname,
                                                              lastname = :lastname,
                                                              address = :address,
                                                              city = :city,
                                                              zip = :zip,
                                                              country = :country
                                                              WHERE userID = :userID"
);
                $stm->bindParam(":firstname", $user['firstname']);
                $stm->bindParam(":lastname", $user['lastname']);
                $stm->bindParam(":address", $user['address']);
                $stm->bindParam(":city", $user['city']);
                $stm->bindParam(":zip", $user['zip']);
                $stm->bindParam(":country", $user['country']);
                $stm->bindParam(":userID", $user['userID']);
                $stm->execute();


                // if update affected any rows, the new user data will be returned
                if ($stm->rowCount() > 0) {

                    // return new user data
                    $user = readUser($_SESSION['email']);
                    $result = $user;

                }
else {

                    // update failed
                    $result = false;

                }
            }

    }
catch(PDOException $e) {
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3, "../logs.txt");
    }


    return $result;
}

function
updateEmail($email, $userID){

    try{

        // check if the email exists in another account
        $pdo = dbConnect();
        $stm = $pdo->prepare("SELECT *
                              FROM `clients`
                              WHERE email = :email
                              AND userID <> :userID"
);
        $stm->bindParam(":email", $email);
        $stm->bindParam(":userID", $userID);
        $stm->execute();


        if($stm->rowCount() > 0){

            // if rows are returned, the email exists and we cannot proceed
           $result = false;

        }
else{

            // email is unknown, we can update the email address!

            $stm = $pdo->prepare("UPDATE `clients` SET
                                                   email = :email
                                                   WHERE userID = :userID"
);
            $stm->bindParam(":email", $email);
            $stm->bindParam(":userID", $userID);
            $stm->execute();

                // if update affected any rows, the new user data will be returned
                if ($stm->rowCount() > 0) {

                    // update the session variable with the new value
                    $_SESSION['email'] = $email;

                    // return the updated user details to populate the form accordingly
                    $user = readUser($email);

                    $result = $user;

                }
else {

                    $result = false;

                }
        }
    }
catch (PDOException $e) {
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3, "../logs.txt");
    }


    return $result;
}

function
updatePw($old, $new, $check, $userID){

    try{
        // 1) check current password with userID

        $pdo = dbConnect();
        $stm = $pdo->prepare("SELECT passw
                              FROM `clients`
                              WHERE userID = :userID"
);
        $stm->bindParam(":userID", $userID);
        $stm->execute();

        if($stm->rowCount() > 0){

            // we found the record, let's check the current password
            $user = $stm->fetchObject();
            $hash = $user->passw;

            if(password_verify($old, $hash)){

                // they match, we can proceed
                // 2) check if both new passwords are equal


                if($new === $check){

                    // 3) hash new password
                    $newHash = password_hash($new, PASSWORD_DEFAULT);

                    // 4) store new password in db
                    $stm = $pdo->prepare("UPDATE `clients` SET
                                                           passw = :pwHash
                                                           WHERE userID = :userID"
);
                    $stm->bindParam(":pwHash", $newHash);
                    $stm->bindParam(":userID", $userID);
                    $stm->execute();

                    if($stm->rowCount() > 0){

                        // we did it!

                        $result = true;

                    }
else{

                        // failed!

                        $result = false;
                    }


                }
else{

                    // oops, values don't match
                    $result = false;
                }

            }
else{

                // wrong password!
                $result = false;
            }


        }
else{

            // user not found
            $result = false;
        }


    }
catch (PDOException $e) {
        $message = $e->getMessage();
        // log error in log file
        error_log($message, 3, "../logs.txt");
    }


    return $result;
}


//@TODO test on remote server
function sendConfirm($email){
    $to = $email;
    $subject = "Please confirm your email address";
    $message = "This is a test";
    $headers = "From: [email protected]" . '\r\n';
    $headers .= "Reply-to: [email protected]" . '\r\n';
    $headers .= "Content-type: text/html; charset=iso-8859-1" . '\r\n';
    $headers .= "Date:" . Date(D, M, Y) . '\r\n';

    $send = mail ($to, $subject, $message, $headers);

    return $send;
}


// email validation
function emailValidate($email){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        $result = $email;
    }
else{
        // email is invalid, return a blank value
        $result = '';
    }


    return $result;
}

function
countryList(){
    $list = array("","Afghanistan", "Albania", "ingekort");
        foreach($list as $country){
            $html .= "<option>$country</option>";
        }

    return $html;
}
[
/code]
[
size=xsmall][i]Toevoeging op 28/08/2015 12:27:51:[/i][/size]
Gewijzigd op 28/08/2015 12:40:38 door Iris B
 
- Ariën  -
Beheerder

- Ariën -

28/08/2015 12:30:20
Quote Anchor link
Met code-tags maakt het wat makkelijker.
 
Iris B

Iris B

28/08/2015 12:31:14
Quote Anchor link
Waar vind ik die dan? Ik zie alleen bold, underline en link etc

EDIT: Sorry, ik zie het al. Reageerde te snel en had niet op je linkje geklikt.
Ik ga het even aanpassen!
Gewijzigd op 28/08/2015 12:32:34 door Iris B
 
Johan K

Johan K

28/08/2015 12:48:28
Quote Anchor link
Valt weinig op aan te merken, je gebruikt netjes PDO, er zit alleen wel een lekje na je gebruik van header().
Die functie verzoekt de client naar die pagina te gaan, alleen hoeft de client hier niet naar te luisteren. Dus je zal het script moeten stoppen, met die of exit.
Gewijzigd op 28/08/2015 14:02:25 door Johan K
 
Iris B

Iris B

28/08/2015 12:52:43
Quote Anchor link
Johan K op 28/08/2015 12:48:28:
Valt weinig op aan te merken, je gebruikt netjes PDO, er zit alleen wel een lekje na je gebruik van header().
Die functie verzoekt jouw de browser van de client naar die pagina, alleen hoeft de client hier niet naar te luisteren. Dus je zal het script moeten stoppen, met die of exit.



Bedankt Johan. Dat is leuk om te horen.

Dus de wijze waarop ik steeds connect met de db is ook goed? vai de dbConnect functie?

Ik zal de header() aanpassen en er wat over lezen om goed te begrijpen wat je zegt.
 

28/08/2015 13:25:11
Quote Anchor link
Oke, ik ben gentle en probeer het zo goed mogelijk te brengen.
Je code is nog steeds procedureel op het verbinden met PDO na.

Je code bevat een aantal fucnties die je aanroept, dit is helaas geen OOP :(

Je code is verder wel netjes maar het kan mooier.
Probeer ook geen if in een else en else in if if else else, je snapt me, te gebruiken.

Wat ook mooi is is werken met een template engine, hierdoor scheidt je je code met je view files en word het al wat gestructureerder.
Daarnaast kan je classes maken en aanroepen die bepaalde dingen moeten doen.

Je bent op een goede weg met een nog betere instelling maar hier is niet super veel OOP te bekennen.

Liefs, <== kijk netjes en lief gebracht toch
Rickert
 
- Ariën  -
Beheerder

- Ariën -

28/08/2015 14:04:55
Quote Anchor link
Als je wilt controleren of een formulier verstuurd is, gebruik liever dit:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
// afhandeling
} else {
// niet ge-POST.
?>
Gewijzigd op 28/08/2015 14:05:06 door - Ariën -
 
Johan K

Johan K

28/08/2015 14:08:43
Quote Anchor link
Zoals Rickert zei, je database functie kan beter. Als je toch al over gaat op OOP, mooie tijd om te zien hoe statics werken :)


Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
function dbConnect(){
    static $dbh;
    // connect to db. If connection fails, return false, otherwise return PDO object.
    if(!empty($dbh)){
      return $dbh;
    }


    // db settings
    $host = '';
    $dbname = '';
    $user = '';
    $pw = '';

    try{
        // connect to db and return pdo opject if connection succeeds
        $dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pw);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e){
        $dbh = false;
        error_log( $e->getMessage(), 3,"../logs.txt");
    }


    return $dbh;

}
?>
Gewijzigd op 28/08/2015 16:49:06 door Johan K
 
Frank Nietbelangrijk

Frank Nietbelangrijk

28/08/2015 15:30:53
Quote Anchor link
@Johan: De db Settings horen natuurlijk netjes thuis in een configuratie bestand.

Als het mag dan wil ik graag nog een praktische tip geven:

In de function updatePw:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
function updatePw()
{

    if(a) {
            if(b) {
                    if(c) {
                            if(d) {
                                    // doe iets
                                    return TRUE;
                            }
else {
                                    return FALSE;
                            }
                    }
else {
                            return FALSE;
                    }
            }
else {
                    return FALSE;
            }
    }
else {
            return FALSE;
    }
}

?>


Kun je vereenvoudigen tot:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
function updatePw()
{

    if(!a) {
        return FALSE;
    }

    
    if(!b) {
        return FALSE;
    }

    
    if(!c) {
        return FALSE;
    }

    
    if(!d) {
        return FALSE;
    }

    
    // doe iets
    return TRUE;
}

?>


Of:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
function updatePw()
{

    if(a) {
        if(b) {
            if(c) {
                if(d) {
                    // doe iets
                    return TRUE;
                }
            }
        }
    }

    
    return FALSE;
}

?>
 
Thomas van den Heuvel

Thomas van den Heuvel

28/08/2015 16:08:20
Quote Anchor link
Of
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
<?php
function updatePw() {
    if (a && b && c && d) {
        // doe iets
        return true;
    }

    return false;
}

?>


Verder zou ik niet strip_tags() over je input strooien, dat is niet echt ergens voor nodig en is toch een beetje schijnveiligheid.

Dan weet ik niet hoe header.php en footer.php er uit zien maar is het toch wel belangrijk dat je overal consistent dezelfde character encoding gebruikt. Ook bij het maken van een verbinding met je database zit in je DSN (je connectie-string) geen charset-aanduiding. Ook je escaping-functionaliteit ( functies zoals htmlspecialchars()) werkt mogelijk niet goed als je niet de juiste character encoding instelt.

En dan nog twee samenhangende issues:
Enerzijds zijn je acties niet heel erg gescheiden, zo combineer je bijvoorbeeld enerzijds het tonen van een signup-formulier, en anderzijds het afhandelen van het verwerken hiervan. Deze acties ("toon inschrijfformulier", "verwerk inschrijfformulier") zou je verder uit elkaar moeten trekken zodat je de code voor elk van deze acties in afzondering kunt behandelen.

Anderzijds introduceer je voor allerhande zaken allerlei functies die je vervolgens maar 1x gebruikt. Dat is niet echt het idee van een functie. In een functie bundel je code die je meerdere keren kunt (her)gebruiken. Zo is de functie "sendConfirm()" veel te specifiek, maar als je daar een soort van wrappertje van maakt om de mail() functie om een standaard zwik headers mee te sturen, en deze voorziet van wat meer parameters (titel, bodytext etc.), dan wordt deze functie al meteen een stuk breder inzetbaar.

Ik denk dat je een hoop functies gewoon "inline" kunt zetten in de eerdergenoemde "acties".
Gewijzigd op 28/08/2015 16:10:41 door Thomas van den Heuvel
 
Iris B

Iris B

28/08/2015 17:36:50
Quote Anchor link
Rickert Bombaklats op 28/08/2015 13:25:11:
Je code bevat een aantal fucnties die je aanroept, dit is helaas geen OOP :(


Hi Rickert :)

Nee, dat klopt ook! Ik zeg ook in mijn eerste post dat ik het nu nog procedural is, en dat ik VOORDAT ik overga op OO, eerst wat feedback wil ;)

Bedankt voor je tips. Ik vraag me alleen af hoe je bepaalde 'flow' zonder geneste if/else kunt doen, wat mijn code betreft?

En hoe zou ik het netter kunnen maken? Of heeft dat vooral met de procedural opzet te maken?
Template frameworks e.d. heb ik mij nog niet in verdiept. Ik wilde nu mijn basiskennis die ik tot nu toe heb vergaard, oefenen.

Groetjes, Iris
 
Johan K

Johan K

28/08/2015 22:11:18
Quote Anchor link
Je zou ook even kunnen kijken naar "ternary" operators. Hiermee kan je veel code in jouw script 1-linen.
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
  echo 1 > 0 ? 'true' : 'false'; // dit echo'd true want 1 is groter dan 0.

  // of in jouw script (functies lijn 128->135)
  return $stm->rowCount() > 0 ? $stm->fetchObject() : false;
  // en verander lijn 143 naar
  return false;

Als er dan een exception op treet in $stm->fetchObject() dan word die catch block uitgevoerd inplaats van try block, dus er word niets gereturned. Aangezien de functie standaard van false returned behaal je hetzelfde, met minder code. Dit kan overal in jouw gehele code ook gedaan worden.
Gewijzigd op 28/08/2015 22:24:53 door Johan K
 
Iris B

Iris B

29/08/2015 07:39:35
Quote Anchor link
- Aar - op 28/08/2015 14:04:55:
Als je wilt controleren of een formulier verstuurd is, gebruik liever dit:

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
// afhandeling
} else {
// niet ge-POST.
?>


Hi Aar,

Bedankt voor de tip.
Kun je toelichten waarom dit beter is?

Groetjes, Iris

Toevoeging op 29/08/2015 07:52:06:

Beste Johan, Frank en Thomas,

Echt top, jullie feedback! Hier heb ik heel veel aan!!

Ik ga ermee aan de slag en als ik nog vragen heb, dan post ik ze.

Fijn weekend.
 
Frank Nietbelangrijk

Frank Nietbelangrijk

29/08/2015 10:20:50
Quote Anchor link
>> Kun je toelichten waarom dit beter is?

Er zijn vier verschillende manieren waarop je een verzoek aan een webserver kunt sturen:

HTTP GET: Voor het opvragen van informatie
HTTP POST: Voor het verwerken van nieuwe gegevens
HTTP PUT: Voor het updaten van gegevens
HTTP DELETE: Voor het verwijderen van gegevens

Met het uitlezen van de superglobal $_SERVER['REQUEST_METHOD'] kom je er achter welke 'METHOD' er door de client gebruikt is en als dat de POST methode is dan mag je dus ook min of meer verwachten dat er data ($_POST variabelen) meegestuurd wordt door de client.
Gewijzigd op 29/08/2015 10:54:26 door Frank Nietbelangrijk
 

31/08/2015 12:15:31
Quote Anchor link
Er zijn meer request methods dan alleen POST, GET, PUT en DELETE.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Het zijn wel de meest gebruikelijke. Vooral met de REST standaard krijg je hier veel mee te maken.

@johan, ik zou het gebruik van tenary operators zoveel mogelijk afraden, soms ontkom je er niet aan maar het maakt je code onduidelijk voor de andere developers.

Wat Frank zegt is super belangrijk, snel returnen.
Hierin maak je een method of functionaliteit waarbij je elke keer als er een conditie zich voordoet je dit meteen kan tergug geven.

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
<?php
function defineNameIsIris($name) {
if ('Iris' == $name) {
 return true;
}


return false;
}

?>
 



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.