|
|
The following PHP scripts shows how to maintain a mailing list. the users are asked to subscribe/unsubscribe to a mailing list and the entire mails are stored in the database.
The user has to type his email id and his/her name and select the radio button subscribe/unsubscribe. Since one email ids are unique, the email id field is a primary key.
Database Queries:
create database dummy;
create table mail(id varchar(100) primary key, name varchar(100))
HTML Form:
<FORM method =post action=sub.php>
<CENTER>
<FONT FACE = “ALGERIAN” SIZE = 6><BR><BR><B><u>SUBSCRIBER / UNSUBSCRIBER </U></B></FONT><BR><BR><BR><BR>
<FONT SIZE = 4><B>Enter E-Mail ID:</B></FONT><INPUT TYPE = text NAME = eid><BR><BR>
<FONT SIZE = 4><B>Name:</B></FONT><INPUT TYPE = text NAME = ename><BR><BR>
<INPUT TYPE = “radio” name = “radio” value = “Radio1″ > Subscriber
<INPUT TYPE = “radio” name = “radio” value = “Radio2″ > Unsubscriber <BR><BR>
<INPUT TYPE = submit VALUE = submit>
<INPUT TYPE = reset VALUE = reset>
</CENTER>
</FORM>
<FORM method =post action=sub.php>
<CENTER>
<FONT FACE = “ALGERIAN” SIZE = 6><BR><BR><B><u>SUBSCRIBER / UNSUBSCRIBER </U></B></FONT><BR><BR><BR><BR>
<FONT SIZE = 4><B>Enter E-Mail ID:</B></FONT><INPUT TYPE = text NAME = eid><BR><BR>
<FONT SIZE = 4><B>Name:</B></FONT><INPUT TYPE = text NAME = ename><BR><BR>
<INPUT TYPE = “radio” name = “radio” value = “Radio1″ > Subscriber
<INPUT TYPE = “radio” name = “radio” value = “Radio2″ > Unsubscriber <BR><BR>
<INPUT TYPE = submit VALUE = submit>
<INPUT TYPE = reset VALUE = reset>
</CENTER>
</FORM>
// Sub.php
<?php
$u = $_POST['eid'];
$p1 = $_POST['ename'];
$p2 = $_POST['radio'];
$con=mysql_connect(”localhost”,”root”,”") or die(”DB connection Failed”);
$db=mysql_select_db(”dummy”,$con) or die(mysql_error());
$query1 = “select * from mail where id = ‘$u’ “;
$query2 = “insert into mail values(’$u’,'$p1′)”;
$query3 = “delete from mail where id = ‘$u’”;
if ($p2 == “Radio1″)
{
$r1 = mysql_query($query1) or die (”Query1 Failed”);
$num = mysql_num_rows($r1);
if ($num == 1)
{
echo “Hai!$u You are already subscribed”;
}
else
{
$r2 = mysql_query($query2) or die (”Insertion query Failed”);
echo “Hai!$u.Thanks for signing up”;
}
}
else if ($p2 == “Radio2″)
{
$r1 = mysql_query($query1) or die (”Query1 Failed”);
$num = mysql_num_rows($r1);
if ($num == 1)
{
$r3 = mysql_query($query3) or die (”Deletion query Failed”);
echo “Hai! $u ur unsubscribed”;
}
else
{
echo “Hai! $u couldnt find ur name in the list”;
}
}
mysql_close($con);
?>
- Simple
- Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English, although very strict English! This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the language itself.
- Easy to Learn
- As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.
- Free and Open Source
- Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple terms, you can freely distribute copies of this software, read it’s source code, make changes to it, use pieces of it in new free programs, and that you know you can do these things. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good – it has been created and is constantly improved by a community who just want to see a better Python.
- High-level Language
- When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc.
- Portable
- Due to its open-source nature, Python has been ported (i.e. changed to make it work on) to many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.
You can use Python on Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and even PocketPC !
- Interpreted
- This requires a bit of explanation.
A program written in a compiled language like C or C++ is converted from the source language i.e. C or C++ into a language that is spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software copies the program from hard disk to memory and starts running it.
Python, on the other hand, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don’t have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc, etc. This also makes your Python programs much more portable, since you can just copy your Python program onto another computer and it just works!
- Object Oriented
- Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.
- Extensible
- If you need a critical piece of code to run very fast or want to have some piece of algorithm not to be open, you can code that part of your program in C or C++ and then use them from your Python program.
- Embeddable
- You can embed Python within your C/C++ programs to give ’scripting’ capabilities for your program’s users.
- Extensive Libraries
- The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, ftp, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), Tk, and other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the ‘Batteries Included’ philosophy of Python.
Source: http://www.ibiblio.org/g2swap/byteofpython/read/features-of-python.html
The expansion of TCL/TK is Tool Command Language / Tool Kit. Why TCL/Tk to bne chosen, following are the features or reasons
- Its free – yes its open source, you can modify and redistribute it
- Help through community – Abundant help available through Tcl forums and community
- Network Based Applications – its based on event driven programming model that makes network programming easy.
- Testing purpose – Tcl is an ideal language to use for automated hardware and software testing, and it may well be the dominant language used for this purpose.
- Deployment – Dynamic languages often make deployment harder, because you need to get both the language interpreter and the application scripts onto the target machine. Most dynamic languages provide tools to “compile” everything into a single executable
- Extend, Embed and Integrate – Can be easily extend, embed and integrate with other languages like C, C++ and Java.
- Easy to Learn
- Cross Platform – Runs on windows, Linux, solaris, Macintosh,
- GUI – using Tk toolkit, canvas widget makes it easy to create displays with graphics, yet it also provides powerful facilities such as bindings and tags.
- Rapid Development – The most important reason why people use Tcl is that it gets their job done faster
Source: http://www.tcl.tk/about/features.html
#!c:/perl/bin/perl -w
print “Content-Type: text/html \n\n”;
$email=”tspradeepkumar\@yahoo.com”;
print $email;
if($email =~ /^(\w|\-|\_|\.)+\@((\w|\-|\_)+\.)+[a-zA-Z]{2,}$/i)
{
print “\n $email is a valid id”;
}
else
{
print “\n Provide a valid email id”;
}
$url=”http://www.eadhoc.com“;
print “\n $url \n”;
if($url =~ /^http:\/\/+(www)+\.+[a-zA-Z0-9\-]+\.+[a-zA-Z]{2,6}$/i)
{
print “$url is a valid url”;
}
else
{
print “\n Provide a valid url “;
}
Source : http://www.openpeta.com
<?php
/*
* FileName:validation.php
* Created on Jan 16, 2007
* Author:Antony
*/
function validateUname($uname) {
if (ereg(’^[a-zA-Z0-9_]{3,50}$’, $uname))
return true;
else
return false;
}
function validatePassword($pwd) {
if (strlen($pwd) >= 6)
return true;
else
return false;
}
function validateEmail($email) {
if (eregi(’^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$’, $email))
return true;
else
return false;
}
function validateDate($date) {
if (ereg(’(^[0-9]{1,2})-[0-9]{1,2}-([0-9]{4}$)’, $date))
return true;
else
return false;
}
function validateMobile($mobile) {
if (ereg(’(^[+0-9]{1,3})*([0-9]{10,11}$)’, $mobile))
return true;
else
return false;
}
function validateUrl($url) {
if (ereg(’^[http://]+[www]*\.[0-9a-zA-Z_.]+\.[a-zA-Z.]{1,5}$’, $url))
return true;
else
return false;
}
function validatePin($pin) {
if (ereg(’^[0-9]{6}$’, $pin))
return true;
else
return false;
}
?>
To Set cookies using PHP, setcookie() function is used. Cookie is a piece of information that stored in the client’s machine (usually browser) by the server.
setcookie() contains 6 parameters
- Name of the cookie- usage- “FirstCookie”
- The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is ‘Iamthecookie’, this value is retrieved through $_COOKIE['Iamthecookie']
- Expiration time of a cookie- usage – time()+60 //means that current time + 60 seconds,
- The path on the server in which the cookie will be available on. If set to ‘/’, the cookie will be available within the entire domain . If set to ‘/osp/’, the cookie will only be available within the /osp/ directory and all sub-directories such as /osp/bar/ of domain . The default value is the current directory that the cookie is being set in.
- The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you’d set it to ‘.example.com’. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain.
- Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to , the cookie will only be set if a secure connection exists. The default is 0. On the server-side, it’s on the programmer to send this kind of cookie only on secure connection.
<?php
$c=setcookie(”name”,”Iamthecookie”,time()+100, “/”,”.eadhoc.com”, 0);
if($c)
echo “The cookie set successfully”;
else
echo “Cookies may be disabled or not set”;
?>
The above script sets a cookie of name ‘name’ and value being ‘Iamthecookie’ which will be available for 100 seconds, and it is for the entire server eadhoc.com and it is not secure (as it uses 0 – HTTP)
to delete the above said cookie,
change the code to
<?php
$c=setcookie(”name”,”",time()-100);
if($c)
echo “The cookie deleted successfully”;
else
echo “Something Wrong”;
?>
How to send email using PHP. The following section describes that with coding…..
Before using Mail in PHP, note that, PHP mail is intended for only a small scale use and not for large scale Email systems. So for large scale, you may use other mal softwares.
Email can be sent
- as ordinary plain message
- as an HTML Message
- with attachments
We will see, one by one
Mail in PHP
there is a function mail() which helps in sending mails through PHP Scripts.
the syntax is mail(To address, Subject, Message, headers)
To address – to which address you want to send mail
Subject of the mail -
Message – body of the mail and
headers – are the http headers sent along with the mail to inform the email clients
Example Headers are
- “From:abc@xyz.com ” //to inform the from address
- “Reply-To:xyz@xyz.com ” //Reply to a different email id
- “Bcc:a@a.com ” //Blind Carbon Copy
- “Cc:b@b.com” //Carbon Copy
- Return-Path:abc@a.com”
- X-Mailer: PHP5 //inform the email client
- MIME-Version:1.0
- Content-Type: text/plain” //text/html or multipart/mixed, multipart/alternative (content type is useful for attaching files with MIME headers)
- Content-Disposition: attachment;filename=”image.jpg”
- Content-Transfer-Encoding: base64″ //Encoding Standards
Email as ordinary Plain message
<?php
$to=”abc@xyz.com”;
$subject=”This is a Simple mail from PHP”;
$message=”<h1>this is a text message</h1>”;
$m=mail($to,$subject,$message);
if($m)
echo “Mail sent successfully”;
else
echo “Mail Failed”;
?>
The mail() function returns a boolean value, so if the mail is sent successfully, it returns 1 else 0. Since the above script does not uses any headers, the mail will be sent as plain text mail and the H1 tag wont be validated for a HTML.
The following code send mail as a HTML page
Email as HTML message
<?php
$to=”abc@xyz.com”;
$subject=”This is a Simple mail from PHP”;
$message=”<h1>this is a text message</h1>”;
$headers = “Content-Type: text/html \r\n”;
$m=mail($to,$subject,$message,$headers);
if($m)
echo “Mail sent successfully”;
else
echo “Mail Failed”;
?>
The above script uses a MIME type as text/html, to the message with H1 rendered as an HTML Tag and the message will display with size of header 1
Email with attachments
Lot of headers to be used for Emails with attachments.
<?php
//set the to, subject and message
$to=”tspembedded@gmail.com”;
$subject=”Here’s the mail with attachment”;
$message=”I am attaching a PDF file for your information”;
//Open the file to attach
$filename=”rts.pdf”; //name of the file and its path
$f=fopen($filename,”rb”); //open the file under binary mode
$data=fread($f,filesize($filename)); //read the file and its size
fclose($f); //close the file pointer
//header setting
$data=chunk_split(base64_encode($data)); //split the file and encode each chunks to base 64
$headers=”Content-Type: application/pdf \r\n”; //since it is a pdf file, mention the mime type
$headers.=”Content-Disposition: attachment;filename=rts.pdf \r\n”; //header to attach the file with filename
$headers.=”Content-Transfer-Encoding: base64 \r\n”.$data.”\r\n”; //header with encode setting
$m=mail($to,$subject,$message,$headers);
if($m)
echo “mail to $to is a success”;
else
echo “Mail to $to Failed”;
?>
the Mime type used in the above script is application/pdf, so only the attachment will be shown in the email client, but the message wont be showed at all…
to make mixed mode, use the mime type as multipart/mixed.
For any other queries and suggestions, Please Comment!!!!!!
Username/password Creation in PHP and MySQL. a Simple form is designed to get the username and two passwords the objectives are
1. Both the username and password should contain atleast 6 characters
2. both the passwords should be same
3. upon submitting to the database, the existence of username is checked with the database, if the username already exists, then the user is allowed to select some other, else user is created.
//html file is given below, file name is
<h2>User Registration Form</h2>
<pre>
<form action=”userregis.php” method=”post”>
Enter the username: <input name=”username” type=”text” /> Enter the password: <input name=”password1″ type=”password” />
Confirm the password: <input name=”password2″ type=”password” />
<input type=”submit” value=”create” />
</form>
</pre>
//userregis.php
<?php
include(”dbconnect.php”);
$u=$_POST['username'];
$p1=$_POST['password1'];
$p2=$_POST['password2'];
$query1=”Select * from usertable where user=’$u’”;
$query2=”Insert into usertable values (’$u’,password(’$p1′))”;
if(strlen($u)<6 or strlen($p1)<6)
{
echo “The username and password should contain atleast 6 characters”;
}
else if($p1!=$p2)
{
echo “The Passwords should be same”;
}
else
{
$r1=mysql_query($query1) or die(”Database Selection Failed”);
$num=mysql_num_rows($r1);
if($num==1)
{
echo “The username <h3> $u </h3> is already exists”;
}
else
{
$r2=mysql_query($query2) or die(”Database Insertion Failed”);
if($r2)
echo “Username <h3> $u </h3> is successfully created”;
else
echo “Database Insertion Failed”;
}
}
?>
<?php
include(”dbconnect.php”);
$u=$_POST['username'];
$p1=$_POST['password1'];
$p2=$_POST['password2'];
$query1=”Select * from usertable where user=’$u’”;
$query2=”Insert into usertable values (’$u’,password(’$p1′))”;
if(strlen($u)<6 or strlen($p1)<6)
{
echo “The username and password should contain atleast 6 characters”;
}
else if($p1!=$p2)
{
echo “The Passwords should be same”;
}
else
{
$r1=mysql_query($query1) or die(”Database Selection Failed”);
$num=mysql_num_rows($r1);
if($num==1)
{
echo “The username <h3> $u </h3> is already exists”;
}
else
{
$r2=mysql_query($query2) or die(”Database Insertion Failed”);
if($r2)
echo “Username <h3> $u </h3> is successfully created”;
else
echo “Database Insertion Failed”;
}
}
?>
//dbconnect.php
<?php
$con=mysql_connect(”localhost”,”root”,”abc123″) or die(mysql_error());
$db=mysql_select_db(”dummy”,$con) or die (mysql_error());
?>
If a user visits a website, where he is asked for validating his username and password and will be validated with the MySQL Database. the following scripts demonstrate this.
Step 1: create a database called dummy by executing “create database dummy” in mysql command window or shell window
Step 2: Create a table called usertable with two fields ‘user’ and ‘pass’ and populate with some values.
create table usertable (user varchar(20), pass varchar(30));
insert into usertable values (’pradeep’,'pradeep’);
Step 3: write the following html script and name it as user.html
<form method=post action=user.php>
Enter the Username: <input type=text name=username> <BR>
Enter the password: <input type=password name=password> <BR>
<input type=submit>
</form>
Step 4: Write the following PHP script and name it as user.php
<?php
$user=$_POST['username']; //get the username from the previous page (html page)
$pass=$_POST['password']; //get the password from the previous page
$conn=mysql_connect(”localhost”,”root”,”hitler”) or die(”Connection Failed”. mysql_error());
mysql_select_db(”dummy”,$conn) or die(mysql_error());
$query=”Select * from usertable where user=’$user’ and pass=’$pass’”;
$result=mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);//returns atleast 1 row if the username password combination is valid
echo $num;//display the number of rows returned
if($num != 0)
{
echo “Welcome Mr.$user, you are authenticated”;
}
else
{
echo “Username/password combination Failed”;
}
mysql_close($conn);
?>
The above script checks for the username and password combination, if the combination is success, then atleast one row will be returned, else the returned rows will be 0.
There are different sorting functions used to sort the arrays and other variables. Some of the their functions are listed below:
sort() – used to sort an array in normal order
rsort() – used to sort an array in normal reverse order
asort() – used to sort array and maintain the index association(key value pair maintains even after sorting)
arsort() – same as asort() but in reverse order
ksort() – used to sort an array by its keys….
Example Program
<?php
$fruits[0]=”Orange”;
$fruits[1]=”Mango”;
$fruits[2]=”Banana”;
print_r($fruits);
sort($fruits);
print_r($fruits);
?>
The above script displays the fruits array in normal order and also in sorted order…. simply replace the sort function with other sort functions and may see the results.
for key value, change the fruits array like the following script
$fruits=array(10=> “Orange”, 100=> “Mango”, 1000=>”Banana”);
and use the functions ksort, asort and arsort () and see that the key value pair is unchanged…..
|
|
Recent Comments