Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
Edward

My Project Diary

Recommended Posts

Hi my name is Edward, i have decided to document a e-commerce project i will be working on, i have been learning HTML, CSS, PHP, Javascript and MySql for 1 year and 2 months.

 

Books read and experience:

 

Learning PHP, MySQL, and Javascript (O'Reilly) Robin Nixon (Finished)

CSS the missing manual (O'Reilly) David Sawyer McFarland(Read parts)

Adobe Dreamweaver CS5 Classroom in a Book(Finished)

Adobe Fireworks CS5 Classroom in a Book(Finished)

Adobe Photoshop CS5 Classroom in a Book(Finished)

Beginning PHP and MySQL E-Commerce (Apress) Christian Darie and Emilian Balanescu (Finished 1/3)

PHP 5 e-commerce Development (Packt) Michael Peacock (Read a little)

Object-Orientated Programming with PHP5 (Packt) Hasin Hayder (Finished 1/3)

PHP Object-Orientated Solutions (Friendsof) David Powers (Finished 1/3)

Effortless E-Commerce with PHP and MySQL (New Riders) Larry Ullman (Finished 1/2)

Agile Web Application Development with Yii1.1 and PHP5 ( Packt) Jeffrey Winesett) (Finished 2/3)

Yii 1.1 Application Development Cookbook (Packt) Alexander Makarov (Read parts)

PHP and MySQL for Dynamic Web Sites (Peachpit Press) Larry Ullman (Finished)

PHP Solutions Dynamic Web Design Made Easy (Friendsof) David Powers (Read Parts)

 

Online:

Larry's Forum (Yes here)

W3Schools.com

Youtube.com

 

I actually have 39 books in total others on javascript, css, jquery, html, mysql etc and more of Larry Ullman's books but these were the ones i gained most of my experience from so far. When i done my first PHP book by Robin Nixon i tried to make a website but i found i was struggling and had to keep looking a lot of stuff up online. I later tried some e-commerce books but i found the first two too complex for me as they were based on Object Orientated frameworks and my OOP code was not such that good and neither i had the experience. I later found a book which i could understand Larry Ullman's Effortless E-commerce so i decided to try that out but someone called Jonathon on this forum recommended that i get more experience before i done this book and give Larry's other book PHP and MySQL for Dynamic Web Sites a read which i did. It took me about 3 months to finish the book with a few breaks in the middle but now i am finally ready to get some practice in and start building.

 

For my first project/coding i will be using a normal way of coding, which means rather than using MVC and having data, logic and views in separate files i will have all my code on the same page. I will be using object-orientated code/classes where i can fit it in because i am working myself towards using the Yii framework or possibly building my own framework which in some ways i think would be better especially for a customized web site like the one i am building.

 

Well that's all i have to say for now, i hope you will enjoy to follow my project.

 

Thank You, Edward

  • Upvote 2

Share this post


Link to post
Share on other sites

This week i have worked on my registration process.

 

1. You fill out your personal details

2. Then you get an email which gives you a unique code to valid your account, so the activation field in the user's table will be set to NULL so you can log in.

3. But once you click the link in your email you then will be directed to a page where you need to pick your username and password. I decided to do it this way because i didn't want people just taking usernames and possibly not clicking the email links and ruining the chance for others that possibly wanting that user name. After the username and password are selected the account will be active and the user can log in.

  • Upvote 1

Share this post


Link to post
Share on other sites

Registration page consisting of:

 

7 Input's (Name, Address, Password etc)

4 Select Drop down's (State, Country, Birthday Month, Birthday Day)

 

States and countries i put into their own database table to pull out and display in drop down rather than hard coding it.

 

I have implemented a google API into this page called reCaptcha, it works with some basic object orientated code and installing a library, it is used to stop spam computers manually processing the forms and prove we are a human by having us type two words which are unreadable by computer recognition.

 

reCaptcha

 

https://developers.google.com/recaptcha/docs/php

 

Client Side (How to make the CAPTCHA image show up)

 

If you want to use the PHP library to display the reCAPTCHA widget, you'll need to insert this snippet of code inside the <form> element where the reCAPTCHA widget will be placed:

 

 require_once('recaptchalib.php');
 $publickey = "your_public_key"; // you got this from the signup page
 echo recaptcha_get_html($publickey);

 

With the code, your form might look something like this:

 

<html>
   <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
  <!-- your HTML content -->
  <form method="post" action="verify.php">
    <?php
	  require_once('recaptchalib.php');
	  $publickey = "your_public_key"; // you got this from the signup page
	  echo recaptcha_get_html($publickey);
    ?>
    <input type="submit" />
  </form>
  <!-- more of your HTML content -->
   </body>
 </html>

 

Don't forget to set $publickey by replacing your_public_key with your API public key.

Note that the value of the "action" attribute is "verify.php". Now, verify.php is the destination file in which the values of this form are submitted to. So you will need a file verify.php in the same location as the client html.

The require_once function in the example above expects recaptchalib.php to be in the same directory as your form file. If it is in another directory, you must link it appropriately. For example if your recaptchalib.php is in the directory called "captcha" that is on the same level as your form file, the function will look like this: require_once('captcha/recaptchalib.php').

 

 <?php
 require_once('recaptchalib.php');
 $privatekey = "your_private_key";
 $resp = recaptcha_check_answer ($privatekey,
						    $_SERVER["REMOTE_ADDR"],
						    $_POST["recaptcha_challenge_field"],
						    $_POST["recaptcha_response_field"]);
 if (!$resp->is_valid) {
   // What happens when the CAPTCHA was entered incorrectly
   die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
	 "(reCAPTCHA said: " . $resp->error . ")");
 } else {
   // Your code here to handle a successful verification
 }
 ?>

 

Using reCAPTCHA with PHP

 

The reCAPTCHA PHP Library provides a simple way to place a CAPTCHA on your PHP website, helping you stop bots from abusing it. The library wraps the reCAPTCHA API.

To use reCAPTCHA with PHP, you can download reCAPTCHA PHP library. You will only need one file from there (recaptchalib.php). The other files are examples, readme and legal stuff -- they don't affect functionality.

Quick Start

 

After you've signed up for your API keys, below are basic instructions for installing reCAPTCHA on your site. A full reference guide to the PHP plugin can be found below.

Client Side (How to make the CAPTCHA image show up)

 

If you want to use the PHP library to display the reCAPTCHA widget, you'll need to insert this snippet of code inside the <form> element where the reCAPTCHA widget will be placed:

require_once('recaptchalib.php');

$publickey = "your_public_key"; // you got this from the signup page

echo recaptcha_get_html($publickey);

With the code, your form might look something like this:

<html>

<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->

<!-- your HTML content -->

 

<form method="post" action="verify.php">

<?php

require_once('recaptchalib.php');

$publickey = "your_public_key"; // you got this from the signup page

echo recaptcha_get_html($publickey);

?>

<input type="submit" />

</form>

 

<!-- more of your HTML content -->

</body>

</html>

Don't forget to set $publickey by replacing your_public_key with your API public key.

Note that the value of the "action" attribute is "verify.php". Now, verify.php is the destination file in which the values of this form are submitted to. So you will need a file verify.php in the same location as the client html.

The require_once function in the example above expects recaptchalib.php to be in the same directory as your form file. If it is in another directory, you must link it appropriately. For example if your recaptchalib.php is in the directory called "captcha" that is on the same level as your form file, the function will look like this: require_once('captcha/recaptchalib.php').

Server Side (How to test if the user entered the right answer)

 

The following code should be placed at the top of the verify.php file:

<?php

require_once('recaptchalib.php');

$privatekey = "your_private_key";

$resp = recaptcha_check_answer ($privatekey,

$_SERVER["REMOTE_ADDR"],

$_POST["recaptcha_challenge_field"],

$_POST["recaptcha_response_field"]);

 

if (!$resp->is_valid) {

// What happens when the CAPTCHA was entered incorrectly

die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .

"(reCAPTCHA said: " . $resp->error . ")");

} else {

// Your code here to handle a successful verification

}

?>

In the code above:

  • recaptcha_check_answer returns an object that represents whether the user successfully completed the challenge.
  • If $resp->is_valid is true then the captcha challenge was correctly completed and you should continue with form processing.
  • If $resp->is_valid is false then the user failed to provide the correct captcha text and you should redisplay the form to allow them another attempt. In this case $resp->error will be an error code that can be provided to recaptcha_get_html. Passing the error code makes the reCAPTCHA control display a message explaining that the user entered the text incorrectly and should try again.

Notice that this code is asking for the private key, which should not be confused with the public key. You get that from the same page as the public key.

Also make sure your form is set to get the form variables using $_POST, instead of $_REQUEST, and that the form itself is using the POST method.

That's it! reCAPTCHA should now be working on your site.</p>

  • Upvote 1

Share this post


Link to post
Share on other sites

Regarding the CSS of the project i have used the blueprints.org CSS framework, which Yii Framework also incorporates. Blueprints it is an awesome framework, it has its own ie hacks in it and it also works as a grid where you can have a maximum column width of span-24 which is 950px. You could increase that if you wished to, anyhow if you wish to have a two column, three or possibly five column page this framework makes it easy.

 

It consists of 5 files, one added to override written by the yii developers

 

form.css

ie.css

main.css (Yii override css and custom form and error styles)

print.css

screen.css

 

I had a little trouble, spent quite a few hours to be precise trying to work out what yii had done and what they were doing but now i seem to be on some smooth concrete.

  • Upvote 2

Share this post


Link to post
Share on other sites

I have added an error summary above my Registration form which prints out all the errors held in the errors array. I also have added css error classes into all of the forum inputs which were not filled in. Rather than using functions i decided to make a Form_Functions Class with static methods to use. Here is my class.

 

<?php
/**
* Class to define commonly used form functions
*
*/

class Form_Functions
{
/**
* This method generates and form row error class.
* It takes two arguments:
* - The name to be given to the element.
* - The arrary of errors.
*/
public static function createErrorClass($name, $errors) {
if (array_key_exists($name, $errors)) echo 'error';
}
/**
* This function generates a form INPUT or TEXTAREA tag.
* It takes three arguments:
* - The name to be given to the element.
* - The type of element (text, password).
* - An array of errors.
*/
public static function createFormInput($name, $type, $attributes=array()) {

// Assume no value already exists:
$value = false;
// Check for a value in POST:
if (isset($_POST[$name])) $value = $_POST[$name];

// Strip slashes if Magic Quotes is enabled:
if ($value && get_magic_quotes_gpc()) $value = stripslashes($value);

// Start creating the input:
echo '<input type="' . $type . '" name="' . $name . '" id="' . $name . '"';

// Add the value to the input use htmlspecialchars to encode html characters before outputting:
if ($value) echo ' value="' . htmlspecialchars($value) . '"';

// Add attributes
if(isset($attributes)) {
foreach($attributes as $key => $value) {
echo ' ' . $key . '="' . $value . '"';
}
}

echo ' />';
} // End of the create_form_input() function.
}
// Omit the closing PHP tag to avoid 'headers already sent' errors!

 

I decided to do some modifications to Larry's helper function and also add an attribute array where i can add all the attributes of a html tag. I apologize if this is bad code, if you know better then please enlighten me because its the first time i write anything now. So far my validation all works on the page, so the next step is to take the values and get them added to the database. I will be using the object-orientated method of accessing MySql and i am thinking of adding some kind of classes in here with a Singleton Pattern.

  • Upvote 1

Share this post


Link to post
Share on other sites

Here are some of my form fields just to show how they look with the new functions, these cut the code down substantially:

 

<div class="row <?php Form_Functions::createErrorClass('email', $reg_errors); ?>">
 <label for="email">Email Address:</label>
 <?php Form_Functions::createFormInput('email','email', array('size'=>20, 'maxlengh'=>50)); ?>
</div>
<div class="row inline <?php Form_Functions::createErrorClass('first_name', $reg_errors); ?>">
 <label for="first_name">First Name:</label>
 <?php Form_Functions::createFormInput('first_name','text', array('size'=>20, 'maxlengh'=>50)); ?>
</div>
<div class="row inline <?php Form_Functions::createErrorClass('last_name', $reg_errors); ?>">
 <label for="last_name">Last Name:</label>
 <?php Form_Functions::createFormInput('last_name','text', array('size'=>20, 'maxlengh'=>50)); ?>
</div>

 

I noticed though some slight announce, i think when i added an Id to the email tag, when I started to enter the email and then clicked off it the input email box went red indicating and error. Looks like some kind of HTML5 validation, it came up on my mobile device and also my mozilla browser.

  • Upvote 2

Share this post


Link to post
Share on other sites

Thank you very much, its fun using all the stuff from the books i have read by you.

 

Sunday, August 05, 2012

 

Today i have changed all mysqli connections into the object orientated versions all of which is now running rather smoothly. I run into an issue with storing birthday in the database, i wondered if i should have two columns for the month and day but my instincts told me this was not good practice. I know that SQL DATETIME variable needs to store the date as well as time, so Ive decided to store birthday in the database as DATETIME and just include the year 2012 which is a leap year and so February the 29th would be accepted if someone was to have a birthday on that day.

 

I run into I would say a little Parse error which took me about 20 minutes to find. It was my mistake, i went in confident and changed a lot of code at one time, later finding an indication on Dreamweaver right at the bottom of my 300 line script the Parse error. I was like, 'Hey What's up Dreamweaver how could you let one slip like that? I wasn't able to find the error, later i start commenting out code until i found it, then i remember i did read about the code commenting in Larry's book, i won't forget that one again. And now i know by the hard way that its better to check each part as i go.

 

Just done my first oop prepared statement but one thing i wasn't sure about is how can you get a date in format yyyy-mm-dd 00:00:00 into MySQL, which letter do you use, d s i, i tried d it didn't work, so i tried s for string to pass it and it worked. Yeah!

 

Inspiration i got from Larry's code:

 

Before

include ('includes/header.html');

include ('includes/footer.html');

 

After

include (HEADER);

include (FOOTER);

 

Yes you tell me which is better, well thanks to Larry he pointed me in the right direction. ;) Whoops Ive just realized i can use a DATE variable in SQL, okay i will go to fix that now, be back tomorrow with more updates.

  • Upvote 1

Share this post


Link to post
Share on other sites

Monday, August 06, 2012

 

From yesterday DATETIME was replace with DATE for saving the birthday, i used 2012 as a leap year for the year.

 

I have managed server hosting with rackspace, i tried using the php mail() function but it failed to work, so i was instructed to join SendGrid.com SMTP to send my email through. I have made an account with SendGrid.com and Rackspace that are partnered with them have automatically sent my account up so that now the php mail() function will send emails to Postfix which will then relay them to SendGrid as end recipient. Ive just tried my mail function in the registration script in the point where you are sent an activation code, i clicked it, and just in 1 second i received a message to my Samsung Galaxy Note indicating that i had received an email. We get to use 40,000 emails with SendGrid Free per month as Rackspace has partnered up with them.

 

By the way i should mention the reason for using SendGrid.com, most email providers like Gmail, Hotmail etc will flag messages as spam or even blacklist hosts from sending emails so they will be rejected. So if we send our emails via SendGrid.com they will pass through successfully.

 

I have been quite lucky as Rackspace configured the setting for SendGrid, i thought i would have to add in another API, if you are interested to see you can check this out, this is some documentation on how to send emails through php with SendGrid http://docs.sendgrid...ple-using-smtp/.

 

This has been not such a smooth day for me at the beginning, i run into an error problem of having to enter data from my registration form into two tables, an address and user table. I could see that there would be a problem adding two queries at a time or even a multi query, what happens if we have a system crash for example, we may lose have of the info. I wasn't sure what do exactly so i asked Larry early and he kindly recommended i use transactions for this. I dealt with the problem by adding a $mysqli->autocommit(FALSE) at the top of my script this would turn off autocommit on queries. I later used $mysqli->rollback() to delete in previous entered transactions if there was an error and also use the $mysqli->commit() when all records were fine to enter. That leaves my registration form almost finished i will be working on mail function tomorrow and working on the activation page, where a user can enter his username and password for the web site to be fully registered.

  • Upvote 1

Share this post


Link to post
Share on other sites

Tuesday, August 07, 2012

 

Worked on my activate php script today, which is a script where the user is asked to enter the username they would like and set there password. This was the first form i have work on with values passed to to the scrip in the URL so i was required to check the $_GET array. Now the problem is in this little form there is also some validation to check if the user had entered a validate username, password and also the confirmation password matched the first one typed in. So what will happen to our $_GET values if the form is submitted on this page, they will be lost yes. So i had to add in two hidden values for the email and activation code in the form, so now at the top of my php script i also have to check for $_POST values being passed to it, and set the values for the form in these as well if the form has to be submitted again.

 

I have a slight problem now trying to take information from a single row using the oop code as object's, i am using fetch_array() but the first_name which i require from the database is not coming out correctly so its something i need to work on.

 

One other thing i have noticed is that since changed to OOP mysqli connections, my custom error handler seems to be no longer working correctly, so its another thing i will have to look into.

  • Upvote 1

Share this post


Link to post
Share on other sites

Just fixed objects problem with fetch_object()

 

// Retrieve user first name from database.
$q = "SELECT first_name FROM user WHERE email='$email'";
$result = $mysqli->query($q);
$row = $result->fetch_object();
$first_name = $row->first_name;

 

Hmm the two hidden values can be viewed looking at the document source in the form, that may not be safe for somethings.

Share this post


Link to post
Share on other sites

Thanks for that i hope you will continue to enjoy reading my project diary. It is the first time i have written any code, really looking forward to working on Sessions and Cookies as soon as this registration/activation part is cleared up.

Share this post


Link to post
Share on other sites

Wednesday, August 08, 2012

 

Antonio, yes writing code like this its my first time, i have written some small parts to test from Larry's PHP and MySQL 4th Edition, by the way thank you it means a lot to me that statement coming from you. Long way to go yet, either i make my own MVC framework which right now looks to me like the best way otherwise use Yii which is probably better if you are a web designer and just need it for the speed of getting jobs done. I was listening to Mark Zuckerburg saying he coded his first version of facebook in just two weeks, he probably did an MVC straight as he was doing a Computer Science Degree. Another thing that is interesting about facebook is hackathon in which they have to stay up all night and hack some new app together, that's insane.

 

Finally back to my project, the activation form is now nearly complete, i have managed to get a prepared statement working which i was having trouble with yesterday as there was little documentation on how to do it. Here it is:

 

// Update user account with username and password
$q = "UPDATE user SET username=?, pass=?, activation_code=NULL, registration_date=NOW() WHERE (email=? AND activation_code=?) LIMIT 1";
// UPDATE user SET username='$username', pass='$password', activation_code=NULL, registration_date=NOW() WHERE (email='$email' AND activation_code='$activation_code') LIMIT 1;
// UPDATE user SET activation_code='6de7628917d6beb0c0217acb4874fcf0' WHERE email='email@gmail.com' LIMIT 1;
// Prepare the statement:
$stmt = $mysqli->prepare($q);
// Bind the variables:
$stmt->bind_param('ssss', $username, $password, $email, $activation_code);
// Execute the query:
$stmt->execute();

 

One thing i have done here in my code which is quite useful is leave standard SQL statement commented in. You see earlier i had a problem with the prepared statement so i decided to check the SQL in phpmyadmin to make sure they passed, i did find an error and had renamed one of the database fields wrong so i fixed it. So now ive left those SQL statements commented into my php script just in case i have to do some later testing.

 

I have had a bit of a half day today, as worked straight last three day and brain is a little clustered, coffee is not helping right now. There are a few things that need to be done on the activation page:

 

1. Username should not contain any inappropriate words, i think you can guess the type i am talking about, so these needs to be placed into an array and later used in a preg_match.

2. The password must not contain the username this must also be checked and blocked to increase security for the user.

3. The password will need to be hashed, so i can modify Larry's example slightly for this, i was going to use SHA256 for encrypting with a hashing algorithm.

4. Username will need to be converted into lowercase letters before entered into the database, i will use a MySQL function to do this.

5. Username must not contain website brand name.

Share this post


Link to post
Share on other sites

Thursday, August 09, 2012

 

Today i have cleared up the 5 problems i set for myself yesterday, it was funny blocking the inappropriate words but i thought a little more about this later and realised, hmm, what about swear words in other languages, like German, French or Spanish. Well i will come back to do those later on. Actually i am starting to keep a record of notes now for improvements or things that will need to be worked on a little later on this site. I was watching a Facebook video last night and i like their comment "Done is better than Perfect", so that has helped to understand and define a goal for my own work. You may have noticed i have not discussed Javascript or JQuery, yes i do know of these and what they are for but i will be honest with you i have a big site to finish which i can't put a time frame on finishing version 1. PHP alone is taking a lot of time especially with the validation and error message css classes, and firstly i would like to complete the whole site with as much PHP as i can. My website will need some javascript for example i need to make a category selector for loading in products, firstly i was going to start of with a top level of categories, then later work on a jquery dynamic category selector later on before site was launched.

 

The activate.php page is now 100%, but you know what i gave the register page a rerun and i guess what i got an system error showing on the registration page after the 1st person had signed up. So what i did is i put error messages in to indicate which mysql table was having a problem, so found it to be the user table and the error message "Duplicate entry '' for key 'username'". Vow isn't that interesting, yes i set both the username and email in the users table to be unique and it was showing that it wouldn't except an unfilled value for username twice indicating it is a duplicate. I don't see what i can really do to fix this so what i have done is rewritten my table SQL and now just left email as unique only, that fixes the problem. And i have a uniqueness check already set to check for username on the Activate.php page where they user will need to select there username.

 

After completing the activation page, the user will be redirected to the index.php page for now logged in, with their session and cookies. These parts i need to work on now including the login page, logout, and password reset. I will just be using normal sessions now to figure out how this stuff works as its my first time, later i plan on being more secure and moving my sessions into the database.

Share this post


Link to post
Share on other sites

Friday, August 10, 2012

 

I have managed to get sessions working, so after a user completes their registration in the activate.php, they are automatically logged in. Here is a sample of the code up to the redirect, i am also using output buffers in my code to eliminate the header already sent error.

 

// Set session and cookies
$_SESSION['user_id'] = $user_id;
$_SESSION['first_name'] = $first_name;

// Delete the buffer.
ob_end_clean();

// Redirect user to index.php
header("Location: http://localhost/myprojectname/index.php");
exit(); // Quit the script.

 

This code is okay for beginners but it starting to bother me a little due to the fact i have a lot of common code starting to repeat itself. I have decided to start my own Object-Orientated MVC framework which i will start tomorrow, i will also be working on classes for User, Session, Database etc to tidy up code. I am also aware that myself as individual eventually will not be able to deal with all the coding problems single handedly, therefore i will definitely need to pick a ready built framework to work into like Yii. With regards to the OOP MVC i would like to build my own model so i can understand how the model works which would give me more confidence for moving onto a professional framework like Yii. I am also planning to have two versions of my project build, one in my own code and one later built into Yii, the reason for this is because i can test what actually happens the normal way before it is run through any yii extended classes or methods.

 

Okay apart from this my project plans for tomorrow are to work on the login.php page, if i am to get that done i still have the password reset page, password change page, log out page to work on.

Share this post


Link to post
Share on other sites

Done is better. I absolutely agree on that. I'm a little too much of a perfectionist myself, which is why a lot of the things I start on doesn't get finished. I therefor started to ask "What's good enough" instead "what would be perfect" some time ago. Compromizing is important. Build something that works, then improve. Keeping todo-list or adding something like @TODO-comments in your code is good for this.

 

About usernames. Use strlen() to check for a minimum value. Performing checks against curse words is a lost cause. I wouldn't implement that simple because it's a pretty tricky thing to do. Simple time-waster. You should also check passwords to make sure they are of a certain strength. (at least one number and one caps is pretty usual for example)

 

I see you build something in OOP and something procedural. To keep code redudancy to a minimum, develop simple functions that suit together and place them in files that you include. These files could easily be transformed to OOP code later on, too. Developing some static classes for Validation/filtering is also a good thing that will reduce a lot of code.

 

I would wait a bit with a framework. Looks like this is starting to go somewhere. Don't waste a lot of time moving into YII. Finalize something before you do that, then begin on Version 2.0 Super Improved. ;)

 

Good read. Keep up the good work. I'm guessing most people are here to ask about problems. You might consider starting a blog instead to increase the number of readers. Just a thought.

  • Upvote 1

Share this post


Link to post
Share on other sites

Antonio: Yes done is better than perfect, i don't think anyone would have their version 1 code later on, all would be changed i am definite. I like your idea of the TODO comments that was better than my idea on making a separate sheet, ill start to do that now. Here is a sample of my username code.

 

// Create array of inappropriate words:
$banned_words = array ('badword', 'badword2', 'badword3', 'badword4', 'badword5', 'badword6', 'badword7');
// Create string for using in Perl-Compatible Regular Expression
$banned_words_str = implode ("|", $banned_words);
// Check for a valid username:
if (preg_match ('/^[A-Z0-9_]{4,20}$/i', $_POST['username'])) {
if (preg_match ("/$banned_words_str/", $_POST['username'])) {
$reg_errors['username'] = 'Your username must not contain inappropriate language!';
} else {
if (preg_match ("/brandname/", $_POST['username'])) {
 $reg_errors['username'] = "The username must not contain the word 'brandname'!";
} else {
 $username = $mysqli->real_escape_string(trim($_POST['username']));
}
}
} else {
$reg_errors['username'] = 'Please enter a valid username!';
}

 

I am using regular expression Antonio for almost all my inputs apart from selects which already have preset values. Usernames can have lowercase letters uppercase letters and underscores. Passwords must have uppercase letters, lowercase letters and numbers. (Just realized I may have made a mistake here, username is supposed to be lowercase) Password is saved to the database with hashed SHA256.

 

I do kind of agree with you with frameworks, i think its good to get your hands dirty with all the basics first, they do come with their fair share of problems even though things appear to look easy.

 

I don't really want to make a blog or write about this stuff to gain fame or popularity, if i wanted i could make like youtube video's that would be better than a blog. I just like to make my diary here because its where i have learned my base from here, i know other people here are using similar coding and its easier to deal with the problems on this forum.

 

Saturday, August 11, 2012

 

Completed the log in page, once user has signed in they will be automatically directed to the index.php, that is just for now. I had some problems with the password being typed into the log in forum not matching the password in the database, i was using a hashed SHA256. In the database i had the password column as VARBINARY(32), but this was only holding half of the encrypted value, it needed a full VARBINARY(64) to work. So i made the necessary updates and now all is working.

Share this post


Link to post
Share on other sites

Save passwords as Char(64), not Varbinary(64).

 

Also, I hate regular expressions. Use the filter extension or other validation functions like the ctype class when possible. (My own view, others might not agree) The main reason is that writing good regular expressions are hard. Using other functions will make your code cleaner and also not that case-dependent. Your regular expressions are only good for a single use, while a function like validate_string_length($string, $min, $max); will be usable also other places.

  • Upvote 1

Share this post


Link to post
Share on other sites

Tuesday, August 21, 2012

 

I have finished off my whole user registration system as of today, the whole password reset system was also completed. I have coded the password reset system in the way that once you click on the link in the email after requesting a reset you are redirected to a page of the site in which you have to enter your new password also confirming. Well everything works and i am quite impressed.

 

I have not written up much on my diary recently as i have been building my own object orientated mvc framework, i am also building wrapper classes to handle most common tasks including form handling, sessions, page redirects, validation and authentication etc. I can see this code i have written is not exactly professional especially for the web site i want to build. There is one last part i would like to build with the normal procedural code, that is a user product listing page, so users can add products to the website associated to them. I will build this to gain the last practice experience.

 

I have decided after i have built my own OOP mvc to see how this system works 100% i am going to start learning the Yii framework as then it will be something i appreciate to use. I personally don't see the point in using your own MVC as i am really not here to fix bugs and neither have the time to do it. So i am strong with going with the Yii framework and letting them deal with the framework development and bugs. Larry's Yii tutorials will be out end of Sept so i will be getting fired up now for these, i will also try to work through Agile Web Application Development with yii 1.1 and PHP5 just before these come out. But anyway before i do any yii, the best way is to make a small practice MVC oop framework to see how it works, would advise that to anyone before starting to use a framework such as Yii or Codeignitor.

 

Okay will be back to let you know how i get on with the product listing page will be starting this one tomorrow.

Share this post


Link to post
Share on other sites

Wednesday, August 22, 2012

 

Product listing page is going well, i have done all the main parts and including php validation with error form error classes apart. I have the image upload part of the page to finish tomorrow. I am noticing with my website, i am not really going to be able to complete it without starting to add in Javascript, its just impossible without it. Maybe i was wrong about what i said yesterday about going into frameworks so soon, i think i am going to spend more time building my site pages in php, then do a crash learning course with Larry's Modern Javascript book. The worst thing i find is just working through books, learning and forgetting stuff, i have learnt it before but have forgotten, so at least now i have a website with pages for the js to be added to i should be able to finally get this once and for all. I need to work on a multiple image selector with js where i can also pick a default image to show from all the images uploaded. Another hard thing i need to work on is a category selector in which you can pick a category within a category and perhaps a few more levels down. There would be no limit to how many child categories would branch from the parent.

 

Generally though i am finding i am getting more tired with this kind of coding work than i would with anything else, as i am having to plan as i go along as well as writing code, then realizing there are some things i need to go back and change. I guess its going to be a hard struggle till the end of getting a version 1 built.

Share this post


Link to post
Share on other sites

No limits to the nesting of categories? Read about recursion. It's the perfect match for that job. It's a little hard to grasp, but not very tricky once you get it. It's also seriously powerful compared to array solutions for those kind of jobs.

 

The best thing about writing your own framework is realizing what you like and dislike. The feeling of developing "the perfect class" that follow you from project to project is very good. I think my MySQLi wrapper is pretty damn solid myself, but that's because I hate how the standard MySQLi class works. I also love to have some static classes hanging around for the dirty jobs. Things like filtering, validation and error messages. This is very common in Java, but I don't see it used a lot in PHP. Because of this, I like some parts of my framework good while other parts are genuinly crap compared to frameworks like CodeIgniter or Yii. There's really no problem extending core functionality in eighter though, so I like being able to get things how I want.

 

The experience you get is invaluable, though, so even if you sweat some blood, you know much more than when you started. Good luck. Keep us posted.

  • Upvote 1

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
Sign in to follow this  

×
×
  • Create New...