Tuesday, June 26, 2012

PHP Learning - How to Create Password Protected Page

Most often, visitors are required to enter username and password to view a page. You can create user auth either with HTTP and Apache or specify in PHP code. Today, let's take a look how to with HTTP and Apache.

You use instructions to Apache, called directives, to set up your authentication application. Directives allow you to specify the files that are password-protected and the valid user names and IDs. The simplest way to use Apache directives for authentication is to create a file called .htaccess

For example, I want to protect my folder called "user". Thus I will create a file called .htaccess. in that file, I specifies the following lines:

AuthUserFile c:\secret\.htpass

AuthGroupFile /dev/null

AuthName Accounting Department

AuthType Basic

Require valid-user

then in the Windows command prompt, i can type

c:\Apache\bin\htpasswd -c c:\secret\.htpass jeff

to create a username for Jeff (in order to do this, you need to go to your httpd.txt file and change "AllowOverride None" to "AllowOverride Authconfig")

Another way to create a page that requires user name and password is through using Http Auth in PHP. Unlike Http auth with Apache, Http auth with PHP have username and password stored in database, in my example, i will use Mysql (since it is my favorite database)

First, I want to create a database, called "Jefftest"

Create database Jefftest;

Then create a table in the database

CREATE TABLE User (

user_name CHAR(10) NOT NULL,

password CHAR(255) NOT NULL,

create_date DATE NOT NULL,

PRIMARY KEY(user_name) );

Then you can access the database from your PHP script with the MySQL functions that are built into PHP. In here, i won't tell you how to access Mysql by using php built-in function (I might in the future) since it is fairly complex to php beginners. But at least you got the idea of how this function is achieved by using HTTP with the apache server.


View the original article here

PHP Learning - Working with Data(4)

PHP provides many built-in functions for manipulating strings. When you want to remove the leading or trailing spaces, you can use the following statement:
$string = trim($string) ; # removes leading & trailing spaces
$string = ltrim($string) ; # removes leading spaces
$string = rtrim($string) ; # removes trailing spaces

PHP can also help you split a string into words. The general
form of this function is as follows:
str_word_count(“string”,format);
In this expression, format can be 1, meaning return the words as a numeric
array; or 2, meaning return the words as an array where the key is the position
of the first character of the word. It may be confusing to you at this point, I will explain array in detail in the future of my php lesson.
To give you an example here:
$string = “Counting Words”;
$number of words = str_word_count($string);
$word1 = str_word_count($string,1);
$word2 = str_word_count($string,2);

if we echo $word1, we get:
$word1[0] = Counting
$word1[1] = Words
if we echo $word2, we get:
$word2[0] = Counting
$word2[9] = Words


View the original article here

PHP Learning-Work With Constants

Constants are similiar to variables, it is created by using "define" statement, such as:
define ("Yao Ming","Best NBA Center");
a number can also be defined
define("interest", .02);

To display constants, we can use "print_r" or "echo" statement
print_r(Yao Ming);
you will get "Best NBA Center"

Constants are really easy to understand, I will talk about Data in the next php learning session. (Emm, may be you are wondering why today's lesson is so short...... Take it easy, buddy, we will go through this step by step)


View the original article here

PHP Learning basics-PHP variables(1)

Basically, variables in php are containers that holds information. Variables starts with $, for example, you can name your variable $first_name, $last_name.... Be careful, variables can not start with a number, thus $4name would not be allowed in php as variable.
Some examples of variables:
$price=4;
$name="Jeff";
Something worth to notice here, when you assign a variable to a number, you don't need include "", however, when you assign variable to a string(I will explain later as we go through php in my blog), you either have to use "" or '', and a ; is always followed after you name the variable

To display a variable value, you can use "echo" or "print_r", for example:
$popsinger="Jeff Chang";
echo $popsinger ;(or print_r ($popsinger);)
For either of the command, you will get result "Jeff".
Of course, you can use "echo" command print more results once, looking at the example below:
$first_name="Jeff";
$last_name="Chang";
echo "Pop singer is", "$first_name," ", $last_name;
The result will be: Pop singer is Jeff Chang.

A little more complicated example:
$web="web";
echo "take a look at this $website";
What do we do now? we noticed that the variable "$website" does not even exist here, to tell php that we want to display website, we can use something like
echo "take a look at this {$web}site; Then you will get the desired result(It is just an example to show you something, of course i know i can just use $website="website", lol)

Look at this:
$name="NBA player";
$name="Yao Ming"
ok, why there is $ here?? if you look carefully, actually, we are creating a new variable here, which is $NBA player="Yao Ming"

To remove a variable, you can use: unset (variablename), such as unset($name), and you can unset more than one at a time, use "," to separate the variable name, such as unset($name, $NBAplayer)
Isn't that easy?? Emm... php language is not scary at all.... I think it is enough for today, we will have fun as we go through php.


View the original article here

PHP learning - Working With Data(1)

In previous lesson, we have learned variables. In php, variables can store data in different types. The different types of data are:
Interger: A whole number (no fractions), such as 10, 0, -43Floating point number: A number that include decimal places, such as 5.36, 4.232Character string: A series of single characters, such as "good", "hello"Boolean: a true or false valuePhp is smarter than you think, it evaluate the variable you stored and will assign an approriate data type to the variable. For example:
$number=2 ; # php store it as interger
$sports="football" #php store it as character string

You can also tell php the type of data you want to store, look at the following example:
$number=(int) $var1; #you are telling php to store $var1 as interger
$sports=(string)$var2; #you are telling php to store $var2 as character string

To find out the type of a variable, use var_dump:
var_dump($var1) #you are asking php what type of data is variable1

PHP provides a shortcut for adding 1 to a variable, for example:
$number=$number+1; can be rewrite as $number++;
$number=$number-1; can be rewrite as $number--;
Other forms of shortcut includes:
$number+=3;
$number-=2;
$number*=4;
$number/=5;


View the original article here

PHP Learning - Working with Data(2)

Use build-in function for simple math calculations:
To compute a square root: $number=sqrt(91);
Round up to the next interger $number=ceil(27.63);
There are a lot of function help you with calculations, I will not list them here

Usually, you will want to control how to display the number, then the statement number_format comes into play.
number_format(number,decimals,"decimalsep","thousandsep)
number is the number to be formatted. This must always be included.

decimals is the number of decimal places. If decimals is not included,
the number of decimal places is 0 by default.

decimalsep is the character used to separate the decimal places. The
default is a decimal point. If you include this, you must also include
thousandsep.

thousandsep is the character used to separate the number into thousands.
The default is a comma. If you include this parameter, you must
also include decimalsep.

For more complicated formatting, you can use the statement "printf" and "sprintf".


View the original article here

PHP Learning - View and Modify Arrays

In my last lesson, I talked about how to create arrays, and we are going to continue today by starting with the topic of how to view arrays in php, then we will look into how to modify arrays in php.
You can see the structure and values of any array by using one of two
statements — var_dump or print_r. The print_r() statement, however,
gives somewhat less information. To display the $studying_day array, use
the following statement:
print_r($studying_day); and you will get the output:
Array
(
[1] => english
[2] => french
[3] => math
[4] => business
)
To get a more detailed information other than the key and value, you can use:
var_dump($studying_day);

array(3) {
[1]=>
string(7) “english”
[2]=>
string(6) “french”
[3]=>
string(4) “math”
[4]=>
string(8)"business"
}
Arrays can be changed at any time in the script, just as variables can.
Let's say I am sick of english(actually I am), thus i decided not to study english anymore, then I can use the following statement to remove it from my previously made array:
$studying_day[1] = " "; # this set the value to empty, but it does not remove
unset(studying_day[1]); # this statement completely remove it from the group
Sort Array:
One of the most useful features of arrays is that PHP can sort them for you.
To sort my array, I can use the statement: sort($studying_day);
$studying_day[1]="english";
$studying_day[2]="french";
$study_day[3]="math";
$study_day[4]="business";
To sort array that contains word as key, we use asort($arrayname); for example, we have a new array:
$computer[cpu]="AMD";
$computer[mainboard]="ESC";
$computer[keyboard]="BENQ";
$computer[screen]="LCD";
when I use asort($computer), I get the following results:
$computer[cpu]="AMD";
$computer[keyboard]="BENQ";
$computer[mainboard]="ESC";
$computer[screen]="LCD";
Some other useful sorting include:
rsort($arrayname) #Sorts by value in reverse order; assigns new numbersas the keys.
ksort($arrayname) #Sorts by key.
krsort($arrayname) #Sorts by key in reverse order.
usort($arrayname, function) #Sorts by a function.


View the original article here

PHP Learning - Working with Data(3)

Use special characters in strings:
php provides some special characters you can use in string: /n and /t
$string = “NBA \nPlayer”;
echo $string;
you will get the result :
NBA
Player

$string = “Line 1 \n\tLine 2”;
echo $string;
you will get the result:
Line 1
Line 2

These special character can only be used with double quotes, I will explain the differences between single-quoted string and double-quoted string
If you enclose a variable in double quotes, PHP uses the value of the variable.
However, if you enclose a variable in single quotes, PHP uses the literal variable. To illurstrate, see the following example:
$name ="Yao Ming";
$output1 = "$name";
$output2 = '$name';
echo $output1;
echo $output2;
you will get the result
Yao Ming
$name

Sometimes you want a character in a double-quoted string to be treated as a
literal, not as a special character, even though it has special meaning.
You can tell PHP to output characters, rather than use their special meaning, by preceding
the character with a backslash (\). This is called escaping the character.
For example, the following two strings produce the same output:
$var1="music";
$string = "The variable name is \$var1";
echo $string;
you will get the result: "The variable name is $var1" instead of "The variable name is music"


View the original article here

PHP Learning - Working with Array



Starting from today, we are going to work with arrays.
Arrays are complex variables that store a group of values under a single
variable name. An array is useful for storing a group of related values.
For example, you can store information about a computer, such as computer case, CPU, memory, and cost, in a single array named $Mycomputerinfo. Information in an array can be handled, accessed, and modified easily.
First, let's take a look at how to create arrays.
Just like createing variables, to create an array, first, we need to assign values to an array. Let's say I have a plan for studying different subject, then:
$studying_day[1]="english";
$studying_day[2]="french";
$study_day[3]="math";
$study_day[4]="business";
......
if you are crazy about studying, then you can creat along list. We observe the general formating for array is:
$arrayname[key]="value";
Array can use either numbers or strings for keys. If you don't assign any value to the key, for example, if I use $studying_day[]="english"; then the key will automatically assigned to a value of zero.
We can also use a shortcut for the above array. $studying_day(1=>"english","french","math","business");
You can also create an array with a range of values by using the following
statement:
$years = range(2001, 2010); the result looks like the following:
$years[0] = 2001
$years[1] = 2002
. . .
$years[8] = 2009
$years[9] = 2010
In my next php learning lesson, I am going to talk about how to view arrays.
View the original article here

PHP Lesson - Basic Programming (1)

After talking about basic php components, such as strings, intergers, arrays, let's move on to inergrate them together and start our basic programming journey.

First, we begin with setting up conditions. Put into simply words, Conditions are expressions that PHP tests or evaluates to see whether they are true or false. Some common operator often see including:
== Are the two values equal in value?
=== Are the two values equal in both value and data type?
> Is the first value larger than the second value?
>= Is the first value larger than or equal to the second value?
< Is the first value smaller than the second value?
<= Is the first value smaller than or equal to the second value?
!== Are the two values not equal to each other in either value or data type?

PHP tests comparisons by evaluating them and returning a Boolean value, either TRUE or FALSE. For example, look at the following comparison:
$a==$b If $a=1 and $b=1, the comparison returns TRUE. If $a =1 and $b =2, the comparison
returns FALSE.

Sometimes you just need to know whether a variable exists or what type of data is in the variable. Following are some common ways to test variables:
isset($varname) # True if variable is set, even if nothing is stored in it.
empty($varname) # True if value is 0 or is a string with no characters in it or is not set.
is_array($var2): Checks to see if $var2 is an array
is_float($number): Checks to see if $number is a floating point
number
is_null($var1): Checks to see if $var1 is equal to 0
is_numeric($string): Checks to see if $string is a numeric string
is_string($string): Checks to see if $string is a string

Sometimes you need to compare character strings to see whether they fit
certain characteristics, rather than to see whether they match exact values. For example, when we gather comments from visitors, we want to make sure they are offering a valid email address. The following are some commonly used special characters that you can use in patterns.
^ Beginning of the line
$ Ending of the line
. Any single character
? Preceding character is optional
() Groups literal characters into grema string that must be matched exactly
[] A set of optional characters
- All the characters between two characters
So if we want to validate a user's mail address, we can use: ^.+@.+\.com$
The expression ^.+@.+\.com$ matches the string: johndoe@somedomain.com


View the original article here

Use PHP Code to Send Email

Yesterday, I was assigned an task of creating a contest registration page so that when people register, I should get their information and at the same time, the person who register should get an welcome email from me. How can I accomplish that by php? I know it is a very easy job for a php expert. For me, I am just like all you guys here - a beginner! I start to recall the functions and did some research on the web and finally, I get it done! Please look at the following code and explanations for this email sending php code:

First, I think, if I want to send them a welcome email, which is store in my server called "welcome-mail,html", I should first, tell php find, open and then read the file. So I start by writing the following code:

// I assigned the filename to a variable to tell php where my file is stored
$file = 'welcome-mail.html';
// I am telling php to open the file by using the build-in function in php - "fopen"
$fh = fopen($file, 'r') or die('Could not open file!');
// Tell php to read the file it opend in the last step and then assign a variable $data to content of the file
$data = fread($fh, filesize($file)) or die('Could not read file!');
//After reading the content, close the file by using function "fclose"
fclose($fh);

Then, I need to retrive the information about my registered user:
$fname = trim($_POST['fname']); //Get the first name of register
$lname = trim($_POST['lname']); //Get the last name of register
$mail = trim($_POST['email']); //Get the email of register
$site = trim($_POST['website']); //Get the web address of register
$subject="Thank you for your registration"; // the subject that the participator see
$subject_main="We get another one to join, Rock!"; // the subject I see
$name=$fname.' '.$lname;
$mailmessage="\r\n Name: ".$name."\r\n Website: ".$site."\r\n Email Address: ".$mail;
$mailmessage=$data ; //assign the content of the file to a new variable - "$mailmessage"

Then I am telling php to send the following to different email address, which is to say, send an email to me that tells me there is another person who wants to join the contest and at the same time, send an welcome mail to that new participator.

// Additional headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$headers .= 'To: '.$fname.' '.$lname.' <'.$mail.'>' . "\r\n";
$headers .= 'From: Jeff Cai' . "\r\n";
mail('mymail.com', $subject_main, $message, $headers);
mail($mail, $subject, $mailmessage, $headers);
echo "
Thank you for your registration! You will receive an email from us shortly.

We will provide you tips on how you can make your chances of winning even better and keep you updated with our contest standings. ";

To sum up, here is the whole php code:
$file = 'matt-email.html';
$fh = fopen($file, 'r') or die('Could not open file!');
$data = fread($fh, filesize($file)) or die('Could not read file!');
fclose($fh);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$mail = trim($_POST['email']);
$site = trim($_POST['website']);
$subject="Thank you for your registration";
$subject_main="We get another one to join";
$name=$fname.' '.$lname;
$mailmessage="\r\n Name: ".$name."\r\n Website: ".$site."\r\n Email Address: ".$mail;
$mailmessage=$data ;

// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: '.$fname.' '.$lname.' <'.$mail.'>' . "\r\n";
$headers .= 'From: Jeff Cai' . "\r\n";

// send an html mail...
mail('mymail.com', $subject_main, $message, $headers);
mail($mail, $subject, $mailmessage, $headers);
echo "
Thank you for your registration! You will receive an email from us shortly.

We will provide you tips on how you can make your chances of winning even better and keep you updated with our contest standings.";
?>


View the original article here