Javascript onfocus in Forms

A nice feature to use with javascript in your forms, is a way to show the currently selected field. When a viewer is in a particular input field it will select that field however you would like – i.e. A border or background color change.

Here is a basic html/js for changing the border:

[code lang=”html”]


[/code]

onfocus: The input changes to a 2px size border on the focus.

onblur: The input changes back to default – 1px size border.

That is how you can simply change the border. However you may want to change other features, or maybe many features at once. For this I recommend using “this.className”. That way you can specify a new class all together and change many appearances.

[code lang=”html”]


[/code]

Now when it is selected it will change background color, border, and font weight. You can specify any style changes in the classes in css.

You can see functional examples of these here.

Filed under: Web ProgrammingTagged with: , ,

PHP Mail (Send Email)

If you have a contact us page or something that sends an email with the use of php, it will use the “mail()” function of PHP. Here is the function:

[code lang=”php”]mail(‘Send To’,’Email Title’,’Email Message’,’Headers’,’Parameters’);[/code]

Send To = Who the email is being sent to.
Email Title = Title of the email, appears in inbox.
Email Message = The body text of the message sent.
Headers = Specifies additional headers, like From, Cc, and Bcc.
Parameters = Specifies additional parameters.

Here is an example:

[code lang=”php”]

[/code]

You have to be careful with the mail function and using headers/parameters. These are often ways of hackers sending faulty information to the script which can allow for header infections, etc. Always be sure to clean your variables you are sending to the function.

Here is a good way to check an email with preg_match:

[code lang=”php”]
function check_email($str){
if(preg_match(“/^[a-z0-9&\’\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is”, $str)) {
$email = trim($str);
return $email;
}
}
[/code]

Enjoy!

Filed under: PHP, Web ProgrammingTagged with: ,

Uploading Files with PHP

With many forms you may want to include some sort of upload of a file. There are many functions for files in PHP that you can use to do this.

Some things you may want to consider when uploading a file to your server:

  • File extension – what type of file is being uploaded.
  • File size – How big is the file, should the be a limit?
  • What to do on a successful upload.

Here is a basic form uploading to the file “upload.php”.

[code lang=”html”]


[/code]

Now on upload.php we need to have code that reacts to this form being submitted, other wise nothing will happen obviously.

[code lang=”php”][/code]

That would be our code for upload.php. When the form is submitted it will execute that code and perform the upload as long as it passes the tests.

You  can specify any directory, extensions, filesize limit you want of course. Enjoy.

Filed under: Scripts, TutorialsTagged with: , ,

Using HTML Meta tags

Meta HTML tags can be very helpful for gaining some search engine rank and promoting your website better. However, these simple tags are not going to drive your website immediately to the top of the lists.

Meta tags are basically information located in the head of your webpage(s). This content is not visible to the viewer, however does communicate with the browser.

Some of the most common meta tags include:

  • Description
  • Keywords
  • Character Set
  • Author
  • Robots

Here is an example for meta tags of a website about fast cars:

[code lang=”html”]



[/code]

The robots tag is used to tell whether or not a page should be indexed by search engines. For example, if you don’t want your page to be indexed use the following code:

[code lang=”html”]

Page Not Indexed


[/code]

The meta tags are supported by all major browsers out there. These can help your website with it’s niche and search engine listings.

Filed under: HTMLTagged with: , ,

Using PHP with Email Activation

Let’s say you have a website with registration. However, you want to have all registered users verify their email address to their account before being able to use all the functions of your site. To do this we can use PHP and simply create an activation code for each user when they register.

Let’s make a simple HTML form that submits a username, password, and email address.

[codesyntax lang=”html4strict” title=”Registration Sample Form”]
<table width=”100%” align=”center” border=”0″ cellpadding=”2″ cellspacing=”0″>
<tr>
<td align=”left”>Username:</td>
<td align=”left”><input type=”text” name=”username” size=”25″ /></td>
</tr>
<tr>
<td align=”left”>Password:</td>
<td align=”left”><input type=”password” name=”password” size=”25″ /></td>
</tr>
<tr>
<td align=”left”>Email Address:</td>
<td align=”left”><input type=”text” name=”email” size=”25″ /></td>
</tr>
<tr>
<td align=”left” colspan=”2″><input type=”submit” name=”submit” value=”Submit” /> <input type=”reset” name=”reset” value=”Reset” /></td>
</tr>
</table>
[/codesyntax]

You would probably want to add a password confirm input or whatever else inputs you want in your registration. This is just for the purpose of submitting the value of the username, password, and email address to our function which will email the user based on the submitted email and include the username and password.

In your registration code you can make an activation code by the following:

[codesyntax lang=”php” title=”Generate Activation Code Function”]
<?php
function generateCode(){
$codelength = 20; // How long you want the activation code to be.
$characters = “abcdefghijklmnopqrstuvwxyz1234567890”; // All accepted characters.
$activatecode = “”;
for($i=0;$i&lt;=$codelength;$i++){
$activatecode .= substr(str_shuffle($characters),0,1);
}
return $activatecode;
}

$userActivationCode = generateCode();
?>
[/codesyntax]

Along with your registration code when you submit the user’s data to your mysql database you would include this in there. We must be connected to a mysql database in order to alter a table (in this case “users”). You can see how to connect to a Mysql database here! You will need to create a column in your users table for both the activation code and their activated status. Like so:

[code lang=”php”]
<?php
$createcolumn = mysql_query(“ALTER TABLE `users` ADD COLUMN activatecode VARCHAR(20)”);
$createcolumn = mysql_query(“ALTER TABLE `users` ADD COLUMN activatestatus INT(5) DEFAULT 0″);
?>
[/code]

The activatestatus column is used to check if their account is activated or not. Now, let’s make it so they have to click this link in their email after they have registered.

Upon registration we will send an email to them with this code in it.

[codesyntax lang=”php” title=”Send Activation Email Function”]
<?php
function sendActivationEmail($email,$username,$password,$actcode){
// Let’s make sure the email address is valid.
if(preg_match(“/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/”, $email)){

// Clean up the username and password.
$username = trim(addslashes($username));
$password = trim(addslashes($password));

if($username && $password){
// Now let’s send the email to them!

mail($email,”Welcome to mysite.com!” Thank you for registering! Below are your account details as well as your activation link needed to complete registration.\n\n
Username: $username\n
Password: $password\n\n
Your activation link:\n http://mysite.com/?actcode=$actcode\n\n
Thank you and welcome to the site!”);
// You can edit the details of the email however you wish of course.

return “Your activation email has been sent to the email specified.”;
} else {
return “Please enter a username and password.”;
}
} else {
return “Invalid email address entered.”;
}
}

// To send the email we define it as $sendEmail with the parameters of our submitted email, username, and password.
$sendEmail = sendActivationEmail($_POST[“email”],$_POST[“username”],$_POST[“password”], $userActivationCode);
?>
[/codesyntax]

This $sendEmail contains the returned value from our sendActivationEmail() function. So apon submitting the registration form this function is called, and stores the returned value in this variable. To display the result of this function you would simply echo or print the variable.

Example:

[code]
<?php
// Once the registration form has been submitted and we called our sendActivationEmail() function.
if(!empty($sendEmail)){ echo $sendEmail; }
?>
[/code]

Now, this function uses four variables that are pre-defined. The $actcode comes from the function we created called “generateCode”. The username, password, and email variables are coming from a form the user submits to register.

Okay, now we have sent them their email with the link. So when they click the link, what happens? Well we need to make this code. What we will do is execute a sql query to update their row in the table and set activatestatus = 1.

[codesyntax lang=”php” title=”Index.php Activate User PHP”]
<?php
if(isset($_GET[“actcode”])){

// Clean the activate code.
$activatecode = trim(addslashes($_GET[“actcode”]));

// Check for their row with that specified activate code.
$sql = mysql_query(“SELECT id FROM users WHERE activatecode = “.$activatecode.” AND activatestatus = ‘0’ LIMIT 1″);

if(mysql_num_rows($sql) > 0){
// Code exists and they aren’t active, let’s make them active.
$update = mysql_query(“UPDATE users SET activatestatus = ‘1’ WHERE activatecode = “.$activatecode.””);
echo “Your account has been activated!”;
} else {
// Code not found.
echo “Invalid activation code.”;
}
}
?>
[/codesyntax]

Now that the user’s activate status has been updated to “1” we can check this column when logging the user in. So when the user goes to enter their login details (username and password) we will simply add a “WHERE username = ‘$username’ AND password = ‘$password’ AND activatestatus = ‘1’“. This will ensure no unactivated accounts may login.

And there you have it. Email activation is quite useful. Enjoy.

Filed under: TutorialsTagged with: , ,

PHP preg_replace

Preg_replace in PHP uses regular expressions to replace matches in the subject with the given replacement. The syntax of preg_replace is as follows:

[code lang=”php”]
preg_replace(pattern,replacement,subject [,limit]);
[/code]

A good example of using preg_replace is with simple bbcode and smilies. However with more complex bbcode there are other ways that would proove to be much easier and more useful. Let’s say you want to replace smiley code with the image of your smilies.  Here is how you would do it with preg_replace:

[code lang=”php”]
$str = $_POST[“textbox”];

$smiliesFind = array(
‘/:\)/’,
‘/:P/’,
);

$smiliesReplace = array(
‘,
‘,
);

print preg_replace($bbcodeFind,$bbcodeReplace,$str);[/code]

This will take all of those matches in the input $_POST[‘textbox’] and replace it with the HTML code of the smiley’s image. Now, why does the find code use slashes like this?

When using regular expressions you need a syntax. The slashes provide that regular expression and the backslashes are needed to escape the parts that could be mistaken as something else in the preg_replace.  This goes for anything you want to escape when executing php code.

We can use preg_replace for some bbcode as well:

[code lang=”php”]
$bbcodeFind = array(
‘/\[color\=(.*?)\](.*?)\[\/color\]/is’,
‘/\[b\](.*?)\[\/b\]/is’,
‘/\[i\](.*?)\[\/i\]/is’,
);

$bbcodeReplace = array(
$2‘,
$1‘,
$1‘,
);

print preg_replace($bbcodeFind,$bbcodeReplace,$str);
[/code]

You can see the use of “(.*?)” in the find array. This will apply the code to any text found inside the tags we supply. This is how it would appear:

Green text!
Bold text!
Italic text!

Filed under: PHP, Web ProgrammingTagged with: ,

PHP Classes and Functions

A great way to organize your tons of functions you will most likely have on your website is by using classes. Classes can be used to hold many functions that you group together – usually by their purpose on the website.

For example, you would probably have functions for executing sql queries in a class of something like “sql”.

Here is how a class is shown in PHP:

[code lang=”php”]

[/code]

A class is created with “class” then space, the name of the class, and brackets (opening and closing).

Let’s say you created this class and you want to execute a function out of this class in your php page. To start a class on your page you have to give the class a variable, like so:

[code lang=”php”]
$sql = new sql();

// Execute function.
$sql->doSql(“SELECT * FROM tbl WHERE id = ‘5’”);
[/code]

This will set $sql as the variable for class “sql”. Executing the functions in a class are just the variable plus the arrow and the function.Continue reading

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , ,

Mysql Database Connect

To connect to a Mysql database you need a few things first.

Of course you need to have the database created with a name you make up as well as the username and password of the mysql account that can connect to that database. This is very simple if you are using web managing software such as Cpanel or DirectAdmin. Under the Mysql databases area you can do all of this quickly.

For many websites mysql connections are included in a common file such as “config.php”. Here is how a basic mysql connection looks:

[code lang=”php”]
$host = “localhost”;
$db_username = “USERNAME”;
$db_password = “PASSWORD”;
$db_name = “DATABASE”;

mysql_connect($host,$db_username,$db_password) or die(mysql_error());

// should there be any errors, we will receive them before reaching any further
// we have connected to the mysql server successfully, now let’s get into the database

mysql_select_db($db_name) or die(mysql_error());

// if the following returns no errors, you are now connected to your mysql database
[/code]

$host – The host that you are connecting to. Usually set to “localhost”.
$db_username – The username of the account that connects to the database specified.
$db_password – The password of the account that connects to the database specified.
$db_name – The name of the database you are connecting to. This is shown in your domain managing area.

This code will connect to a mysql database and if there are any errors reported it will end php and display the errors.

Filed under: Scripts, Tutorials, Web ProgrammingTagged with: ,