Tuesday 12 July 2011

PHP Upload single file

PHP Upload single file Simple PHP uploading file scripts.
1. upload.php
2. upload_ac.php


Step
1. Create file upload.php.
2. Create file upload_ac.php.
3. Create folder "upload" for store uploaded files.
Create file upload.php
 <table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="upload_ac.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile" type="file" id="ufile" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
Create file upload_ac.php
<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES['ufile']['name']; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif

$path= "upload/".$HTTP_POST_FILES['ufile']['name'];
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$HTTP_POST_FILES['ufile']['name'] = file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file

echo "File Name :".$HTTP_POST_FILES['ufile']['name']."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
echo "<img src=\"$path\" width=\"150\" height=\"150\">";
}
else
{
echo "Error";
}
}
?>

Sending Forgotten Password

Sending Forgotten Password
How you send password via email address when they forgotten their password
Suppose any member forgot his password to login any website.We will send him his password to his email address.

1. forgot_password.php
2. send_password_ac.php

Database
1. members


Syntax
$email_to=$_POST['email_to'];

"SELECT password FROM table_name WHERE email='$email_to'";

Create table "members"
This is our database, table "Members" MS saha's password is "951412dwe" and his e-mail is "mark@phpeaststep.com"


CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `test_mysql`
--
INSERT INTO `members` VALUES (1, 'Billly', 'Blueton', 'email_1@somewhere.com', '789789');
INSERT INTO `members` VALUES (2, 'Jame', 'Campbell', 'email_2@somewhere.com', '654123ddf');
INSERT INTO `members` VALUES (3, 'Mark', 'Jackson', 'email_4@somewhere.com', '951412dwe');
* replace email_1, 2 , 3 with your e-mail address for testing

forgot_password.php

Create form and text field, name it "email_to" action at "send_password_ac.php"

############### Code

<table width="380" border="0" cellpadding="3" cellspacing="1" >
<tr>
<td width="33%"><strong>Enter your email : </strong></td>
<td width="67%">
<form name="form1" method="post" action="send_password_ac.php">
<input name="email_to" type="text" id="mail_to" size="25">
<input type="submit" name="Submit" value="Submit">
</form>

</td>
</tr>
</table>
send_password_ac.php
What to do?
1. after press submit button the form will send e-mail address to "send_password_ac.php".
2. at "send_password_ac.php" we have to find this e-mail address in our database.
3. if found this e-mail in our database give password to variable name "$your_password" and send this variable to e-mail that sent from our form.
4. if not found this e-mail in database, displays message "Not found your e-mail in our database"

  ############### Code
<?
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name


//Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// value sent from form
$email_to=$_POST['email_to'];

// table name

$tbl_name=members;

// retrieve password from table where e-mail = $email_to(mark@phpeasystep.com)
$sql="SELECT password FROM $tbl_name WHERE email='$email_to'";
$result=mysql_query($sql);

// if found this e-mail address, row must be 1 row
// keep value in variable name "$count"

$count=mysql_num_rows($result);

// compare if $count =1 row
if($count==1){

$rows=mysql_fetch_array($result);

// keep password in $your_password
$your_password=$rows['password'];
// ---------------- SEND MAIL FORM ----------------

// send e-mail to ...
$to=$email_to;

// Your subject
$subject="Your password here";

// From
$header="from: your name <your email>";

// Your message
$messages= "Your password for login to our website \r\n";
$messages.="Your password is $your_password \r\n";
$messages.="more message... \r\n";
// send email
$sentmail = mail($to,$subject,$messages,$header);


}

// else if $count not equal 1
else {
echo "Not found your email in our database";
}

// if your email succesfully sent
if($sentmail){
echo "Your Password Has Been Sent To Your Email Address.";
}
else {
echo "Cannot send password to your e-mail address";
}

?>

  ***Update***
I've got a lot of complains about security of sending the real password that exists in dababase. This may cause some troubles.

a new way to send password you can adapt from my verifying email tutorial

concept
- your user insert email to request password form
- find that email in our database
- if found, random a confirmation code and send it to email address to verify the email and also keep confirmation code in temp_database(don't forget to creates it first)
- when your user open email and click on confirmation link
- random and send new random password to email address again
- random new password you can use this code

<?

$random_password=md5(uniqid(rand()));
$new_password=substr($random_password, 0, 8);
echo $new_password;
?>
- After email has been sent, update an old password in database to a new random password.

- If you can wait i'm writing on it now, waits for a few day 

Monday 11 July 2011

Automatic refresh webpage

Automatic refresh webpage / Set time to redirect
When you need your web page automatic refresh in 5 second or any second, use this meta tag. it's a simple code, put it between HEAD tag in your web page. 
 
Overview
This script easy but powerful. Many websites use this scripts to redirect to another page or refresh the same page, for example, my website updates in every 10 minutes and I want to show user my latest content then I put this script to my page and set it refreshs in every 10 minutes.

Automatic Refresh / Redirect
<HEAD>
<meta http-equiv='refresh' content='2;url='file_name or URL'>
</HEAD>
// content = time (second)
// file_name = name of file you want to refresh or redirect 

Sunday 10 July 2011

PHP - Implementing Secure Login with PHP, JavaScript, and Sessions (without SSL)

login.php

<?php 
//
// LOGIN PAGE
//
//   Server-side:
//     1. Start a session
//     2. Clear the session
//     3. Generate a random challenge string
//     4. Save the challenge string in the session
//     5. Expose the challenge string to the page via a hidden input field
//
//  Client-side:
//     1. When the completes the form and clicks on Login button
//     2. Validate the form (i.e. verify that all the fields have been filled out)
//     3. Set the hidden response field to HEX(MD5(server-generated-challenge + user-supplied-password))
//     4. Submit the form

session_start();
session_unset();
srand();
$challenge = "";
for ($i = 0; $i < 80; $i++) {
    $challenge .= dechex(rand(0, 15));
}
$_SESSION[challenge] = $challenge;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Login</title>
        <script type="text/javascript" src="http://pajhome.org.uk/crypt/md5/md5.js"></script>
        <script type="text/javascript">
            function login() {
                var loginForm = document.getElementById("loginForm");
                if (loginForm.username.value == "") {
                    alert("Please enter your user name.");
                    return false;
                }
                if (loginForm.password.value == "") {
                    alert("Please enter your password.");
                    return false;
                }
                var submitForm = document.getElementById("submitForm");
                submitForm.username.value = loginForm.username.value;
                submitForm.response.value =
                    hex_md5(loginForm.challenge.value+loginForm.password.value);
                submitForm.submit();
            }
        </script>
    </head>
    <body>
        <h1>Please Login</h1>
        <form id="loginForm" action="#" method="post">
            <table>
                <?php if (isset($_REQUEST[error])) { ?>
                <tr>
                    <td>Error</td>
                    <td style="color: red;"><?php echo $_REQUEST[error]; ?></td>
                </tr>
                <?php } ?>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" name="username"/></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type="password" name="password"/></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <input type="hidden" name="challenge" value="<?php echo $challenge; ?>"/>
                        <input type="button" name="submit" value="Login" onclick="login();"/>
                    </td>
                </tr>
            </table>
        </form>
        <form id="submitForm" action="authenticate.php" method="post">
            <div>
                <input type="hidden" name="username"/>
                <input type="hidden" name="response"/>
            </div>
        </form>
    </body>
</html>

authenticate.php

<?php 

//
// AUTHENTICATE PAGE
//
//   Server-side:
//     1. Get the challenge from the user session
//     2. Get the password for the supplied user (local lookup)
//     3. Compute expected_response = MD5(challenge+password)
//     4. If expected_response == supplied response:
//        4.1. Mark session as authenticated and forward to secret.php
//        4.2. Otherwise, authentication failed. Go back to login.php
$userDB = array("john" => "abc123",
"bob"  => "secret",
"anna" => "passwd")
function getPasswordForUser($username) {
// get password from a simple associative array
// but this could be easily rewritten to fetch user info from a real DB
global $userDB;     return $userDB[$username];
} 
function validate($challenge, $response, $password) {
return md5($challenge . $password) == $response;
} 
function authenticate() {
if (isset($_SESSION[challenge]) &&
isset($_REQUEST[username]) &&
isset($_REQUEST[response])) {
$password = getPasswordForUser($_REQUEST[username]);
if (validate($_SESSION[challenge], $_REQUEST[response], $password)) {
$_SESSION[authenticated] = "yes";
$_SESSION[username] = $_REQUEST[username];;
unset($_SESSION[challenge]);
} else {
header("Location:login.php?error=".urlencode("Failed authentication"));
exit;
}
} else {
header("Location:login.php?error=".urlencode("Session expired"));
exit;
}
}
session_start();
authenticate();
header("Location:secret.php");
exit();
?>

common.php

<?php

//
// COMMON PAGE
//
//   Defines require_authentication() function:
//     If the user is not authenticated, forward to the login page
//     

session_start();
function is_authenticated() {
return isset($_SESSION[authenticated]) &amp;&amp;
$_SESSION[authenticated] == "yes";
}
function require_authentication() {
if (!is_authenticated()) {
header("Location:login.php?error=".urlencode("Not authenticated"));
exit;
}
}
?>

Thursday 30 June 2011

How can we submit a form without a submit button?


<html>
<body bgcolor="cornsilk" text= "greeen">
 <h1>abc</h1>
</html>

//then//


 <html>
<body>
<input type="button" name="btn" value= "Show me"onClick="xyz()">
 </body>
<script language= "javascript">
 function xyz()
  { document:location= "abc.html";
  }
  </script>
  </html>

Tuesday 14 June 2011

operator
An operator is a symbol or series of symbols that, when used in conjunction with values, performs an action and usually produces a new value.
operand
An operand is a value used in conjunction with an operator. There are usually two operands to one operator.
Expression
Expression is any combination of functions, values, and operators that resolves to a value. As a rule of thumb, if you can use it as if it were a value, it is an expression.

Constants

Variables offer a flexible way of storing data because you can change their values and the type of data they store at any time. If, however, you want to work with a value that you do not want to alter throughout your script's execution, you can define a constant. You must use PHP's built-in function define() to create a constant. After you have done this, the constant cannot be changed. To use the define() function, you must place the name of the constant and the value you want to give it within the call's parentheses. These values must be separated by a comma, like so:
 
define ("CONSTANT_NAME", 42);
 

The if Statement


An if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block of code inside braces). The if statement evaluates an expression between parentheses. If this expression results in a true value, the statement is executed. Otherwise, the statement is skipped entirely. This enables scripts to make decisions based on any number of factors.

What Is a Function?

A function, then, is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which they then work with. When finished, a function can pass a value back to the calling code.

What Is an Array?

An array enables you to store as many values as you want in the same variable.
Type Specifies
Specifier
Description
d
Displays an argument as a decimal number
b
Displays an integer as a binary number
c
Displays an integer as its ASCII equivalent
f
Displays an integer as a floating-point number (double)
o
Displays an integer as an octal number (base 8)
s
Displays an argument as a string
x
Display an integer as a lowercase hexadecimal number (base 16)
X
Displays an integer as an uppercase hexadecimal number (base 16)


Portability
PHP is designed to run on many operating systems and to cooperate with many servers and databases. You can build for a Unix environment and shift your work to NT without a problem. You can test a project with Personal Web Server and install it on a Unix system running on PHP as an Apache module.
Variables
A variable is a special container you can define to hold a value. Variables are fundamental to programming.
A variable is a holder for a type of data. It can hold numbers, strings of characters, objects, arrays, or booleans. The contents of a variable can be changed at any time.
PHP is loosely typed, which means it calculates data types as data is assigned to each variable.

Six standard data types available in PHP.
          Type                                                              Example                                                  Description
            Integer                                                                                  5                                                                           A whole number
            Double                                                                             3.234                                   A floating-point number
            String                                                                              "hello"                                  A collection of characters
            Boolean                                                                           true                                    One of the special values true or false
           Object                                                                  class Item
                                                                                    { var $name = "item"; }
                                                                                     $obj1 = new Item();
                                                                                    $obj2 = new Item();
                                                                                   $obj1->name = "widget 5442";
                                                                                  print "$obj1->name<br />";
                                                                                 print "$obj2->name<br />";
                                          
           Array                                          $membertypes = array ("regular", "regular", "regular", $regular");                     "Arrays"
Special Data Types
                   Type                                                                                                                                                          Description
            Resource                                                                    Reference to a third-party resource (a database, for example)
            NULL                                                                         An uninitialized variable

PHP Is Open Source

To many people, open source simply means free, which is, of course, a benefit in itself.
Well-maintained open-source projects offer users additional benefits, though. You benefit from an accessible and committed community that offers a wealth of experience in the subject. Chances are that any problem you encounter in your coding can be answered swiftly and easily with a little research. If that fails, a question sent to a mailing list can yield an intelligent, authoritative response.
You also can be sure that bugs will be addressed as they are found, and that new features will be made available as the need is defined. You will not have to wait for the next commercial release before taking advantage of improvements.
There is no vested interest in a particular server product or operating system. You are free to make choices that suit your needs or those of your clients, secure that your code will run whatever you decide.

Speed of Development

Because PHP allows you to separate HTML code from scripted elements, you will notice a significant decrease in development time on many projects. In many instances, you will be able to separate the coding stage of a project from the design and build stages. Not only can this make life easier for you as a programmer, but it also can remove obstacles that stand in the way of effective and flexible design.

Why Choose PHP?


There are some compelling reasons to work with PHP. For many projects, you will find that the production process is significantly faster than you might expect if you are used to working with other scripting languages. At Corrosive we work with both PHP and Java. We choose PHP when we want to see results quickly without sacrificing stability. As an open-source product, PHP is well supported by a talented production team and a committed user community. Furthermore, PHP can be run on all the major operating systems and with most servers.

PHP :- : Hypertext Preprocessor. It is a server-side scripting language often written in an HTML context. Unlike an ordinary HTML page, a PHP script is not sent directly to a client by the server; instead, it is parsed by the PHP engine. HTML elements in the script are left alone, but PHP code is interpreted and executed. PHP code in a script can query databases, create images, read and write files, talk to remote servers—the possibilities are endless. The output from PHP code is combined with the HTML in the script and the result sent to the user.
PHP 5 introduces numerous new features
·       PHP has new integrated for support for XML. The various functions and classes provided to handle XML in different ways all now use the same underlying library (libxml2). This should make XML features more stable and interoperable.
·       The SQLite SQL library is now bundled with PHP, together with all the functions you need to work with it.
·       PHP now supports private and protected methods and properties in classes.
·       PHP supports class constants.
·       Objects passed to functions and methods are now passed by reference. That is, a reference to an object is passed around your script rather than copies of objects. This significantly reduces the likelihood of bugs in object-oriented code.
·       PHP supports static methods and properties, making more advanced object-oriented designs possible.
·       Methods can now be declared to require particular object types.
·       The comparison operator (===) now checks that two references point to the same object. Previously, it was hard to test objects in this way.
·       PHP now supports abstract classes and interfaces.

Saturday 21 May 2011

This is the first program .

// If you are a  php learner this program will help you.to view "HELLO PHP" through your browser.
//This is first program of php
<html>
<body bgcolor= "cornsilk"text="blue">
<div>
<?php
function cmc()
 {
   echo"<h1>HELLO PHP</h1>";
 }
  $p= cmc();
  $p;
?>
</div>
</body>
</html>
Welcome to  PHP