View difference between Paste ID: VRWUBdm5 and nPaEUPbT
SHOW: | | - or go back to the newest paste.
1
<?php
2
3
echo "My first PHP script!";
4
echo "<br>";
5
$x = 5+5;
6
echo $x;
7
echo "<br>";
8
//--------------------------------------------------------
9
echo gettype($x);  //return datatype
10
echo "<br>";
11
12
$color="red";
13
echo "Color is ".$color."<br>";
14
15
define("Name", "Lovely Professional University");  //constant
16
echo Name;
17
echo "<br>";
18
19
printf("Regno is %d",11604722);
20
echo "<br>";
21
22
var_dump($x);  //return datatype and value
23
echo "<br>";
24
//-----------------------------------------------------------
25
$cars = array("Audi","BMW","Toyota");   //array
26
echo "First Car is ".$cars[0]."<br>";
27
var_dump($cars);
28
echo "<br>";
29
//-----------------------------------------------------------------------
30
echo strlen("Hello World!");  //returns the length of a string
31
echo "<br>";
32
echo str_word_count("Hello World!"); //counts the number of words in a string
33
echo "<br>";
34
echo strrev("Hello World!"); //reverses a string
35
echo "<br>";
36
echo strpos("Hello World!", "World"); //searches for a specific text within a string
37
echo "<br>";
38
echo str_replace("World", "India", "Hello World!"); //replaces some characters with some other characters in a string
39
echo "<br>";
40
41
$temp="Smoking is good for Health";
42
echo str_replace("good", "bad", $temp,$count)."<br>";
43
echo $count."<br>";
44
//-------------------------------------------------------------------------------------------------------------------
45
$a=10;
46
$b=10;
47
var_dump($a==$b); //Equal
48
echo "<br>";
49
var_dump($a===$b); //Identical
50
echo "<br>";
51
var_dump($a!=$b); //Not equal
52
echo "<br>";
53
var_dump($a<>$b); //Not equal
54
echo "<br>";
55
var_dump($a!==$b); //Not identical
56
echo "<br>";
57
var_dump($a>$b); //Greater than
58
echo "<br>";
59
var_dump($a<$b); //Less than
60
echo "<br>";
61
var_dump($a>=$b); //Greater than or equal to
62
echo "<br>";
63
var_dump($a<=$b); //Less than or equal to
64
echo "<br>";
65
//----------------------------------------------------------
66
echo $a++."<br>";  //Pre-increment
67
echo ++$a."<br>";  //Post-increment
68
echo $b--."<br>";  //Pre-decrement
69
echo --$b."<br>";  //Post-decrement
70
71
$a=20;				// decision making
72
if($a==2)
73
{
74
	echo "Hello World"."<br>";
75
}
76
elseif ($a=="20")
77
{
78
	echo "This is string value";
79
}
80
else
81
{
82
	echo "Hello Class";
83
}
84
//-------------------------------------------------------------
85
$year=2016;
86
if($year%4==0 && ($year%100!=0 || $year%400!=0))
87
{
88
	echo "<br>"."Leap Year";
89
}
90
else
91
{
92
	echo "Not a Leap Year";
93
}
94
//------------------------------------------------------------------
95
$var=12345;
96
if ($var%3==0)
97
{
98
	echo "<br>"."Divisible by 3";
99
}
100
if ($var%5==0)
101
{
102
	echo "<br>"."Divisible by 5";
103
}
104
if ($var%3==0 && $var%5==0)
105
{
106
	echo "<br>"."Divisible by 3 and 5";
107
}
108
else
109
{
110
	echo "<br>"."Not Divisible by 3 or 5";
111
}
112
113
//-------------------------------------------------------------------------------------
114
echo "<br>".date("d");  //The day of the month (from 01 to 31)
115
echo "<br>".date("D");	//A textual representation of a day (three letters)
116
echo "<br>".date("H");	//24-hour format of an hour (00 to 23)
117
echo "<br>".date("A");  //Uppercase AM or PM
118
echo "<br>".date("L");	//Whether it's a leap year (1 if it is a leap year, 0 otherwise)
119
echo "<br>".date("Y-m-d"); //Year date month
120
121
//----------------------------------------------------------------------
122
$a=10;
123
$b=5;
124
$c="/";
125
switch($c)
126
{
127
	case "+": echo $a+$b;
128
				break;
129
130
	case "-": echo $a-$b;
131
				break;
132
}
133
134
135
//--------------------------------------------------------------------
136
$start = 1;
137
$end = 10;
138
139
$sum = 0;
140
for ($i = $start; $i <= $end; $i++) {
141
    $sum += $i;
142
}
143
144
echo "<br>"."Sum from " . $start . " to " . $end . " = " . $sum;
145
//---------------------------------------------------------------------
146
$arr=array("Abc",10,20);
147
echo "<br>";
148
print_r($arr);
149
echo "<br>".count($arr);
150
echo "<br>".$arr[0]."<br>";
151
var_dump($arr);
152
for($i=0;$i<3;$i++)
153
{
154
	echo "<br>".$arr[$i];
155
}
156
foreach($arr as $x => $x_value) {
157
    echo "<br>"."Key=" . $x . ", Value=" . $x_value;
158
}
159
//------------------------------------
160
$arr["name"]="DP";
161
echo "<br>".$arr["name"];
162
//--------------------------------------
163
164
$numbers = array(4, 6, 2, 22, 11);
165
$numbers[0]=1;
166
$numbers[5]=9;
167
echo $numbers[0];
168
echo $numbers[5];
169
170
sort($numbers);
171
$arrlength = count($numbers);
172
echo "<br>";
173
for($x = 0; $x < $arrlength; $x++) 
174
{
175
    echo $numbers[$x];
176
    echo "<br>";
177
}
178
179
//----------------------------------------------------------------------------
180
$cars = array 			//TWO DIMENSIONAL ARRAY
181
  (
182
  array("Volvo",22,18),
183
  array("BMW",15,13),
184
  array("Audi",5,2),
185
  array("Land Rover",17,15)
186
  );
187
188
echo "<br>".$cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2];
189
echo "<br>".$cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2];
190
echo "<br>".$cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2];
191
echo "<br>".$cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2];
192
193
for($i=0;$i<3;$i++)
194
{
195
	echo "<br>";
196
	for($j=0;$j<3;$j++)
197
	{
198
		echo $cars[$i][$j];
199
	}
200
}
201
//---------------------------------------------------------------------------
202
203
$marks = array( 
204
            "mohammad" => array (
205
               "physics" => 35,
206
               "maths" => 30,	
207
               "chemistry" => 39
208
            ),
209
            
210
            "qadir" => array (
211
               "physics" => 30,
212
               "maths" => 32,
213
               "chemistry" => 29
214
            ),
215
            
216
            "zara" => array (
217
               "physics" => 31,
218
               "maths" => 22,
219
               "chemistry" => 39
220
            )
221
         );
222
         
223
         /* Accessing multi-dimensional array values */
224
         echo "<br>"."Marks for mohammad in physics : " ;
225
         echo $marks['mohammad']['physics'] . "<br />"; 
226
         
227
         echo "Marks for qadir in maths : ";
228
         echo $marks['qadir']['maths'] . "<br />"; 
229
         
230
         echo "Marks for zara in chemistry : " ;
231
         echo $marks['zara']['chemistry'] . "<br />"; 
232
//----------------------------------------------------------------------------------
233
$cars = array("Volvo", "BMW", "Toyota");
234
sort($cars);
235
//--------------------------------------------------------------------------------
236
$arr1=array("abc","def");
237
$arr2=array("ghi","jkl");
238
print_r(array_merge($arr1,$arr2));   //merging two arrays
239
echo "<br>";
240
$union=$arr1+$arr2;
241
//var_dump($union);  //Union 
242
echo "<br>";
243
print_r($union);
244
245
echo "<br>";
246
$my_array1 = array("size" => "big", 2,3 ); //Associative Array Union and Merge
247
$my_array2 = array("a", "b", "size" => "medium", 
248
                        "shape" => "circle", 4); 
249
print_r(array_merge($my_array1, $my_array2)); 
250
echo "<br>";
251
$union2=$my_array1+$my_array2;
252
print_r($union2);
253
254
//------------------------------------------------------------------------------
255
//Array Slice
256
echo "<br>";
257
$a=array("red","green","blue","yellow","brown");
258
print_r(array_slice($a,2,3));
259
//------------------------------------------------------------------------------
260
echo "<br>";
261
$str = "Hello world. It's a beautiful day."; //Converting String to Array
262
print_r (explode(" ",$str));
263
//------------------------------------------------------------------------------
264
echo "<br>";
265
$arr = array('Hello','World!','Beautiful','Day!');//Converting Array to String
266
echo implode(" & ",$arr);//here " " is delimiter
267
//-----------------------------------------------------------------------------
268
echo "<br>";
269
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
270
$result=array_flip($a1); //Swapping Array Keys and Value
271
print_r($result);
272
//----------------------------------------------------------------------------
273
echo "<br>";
274
$a=array("a"=>"red","b"=>"green","c"=>"red");
275
print_r(array_unique($a));//Removind Duplicacy in array elements
276
//echo join(" ,",$a);
277
//------------------------------------------------------------------------------------------
278
//WAPS to calculate and display 5 lowest and highest temperatures?
279
echo "<br>";
280
$temp=array(78,60,62,68,71,68,73,85,66,64,76,63,75,76,73,68,62,73,72,65,74,62,62,65,64,68,73,75,79,73);
281
$temp1=array_unique($temp);
282
sort($temp1);
283
echo "List of 5 lowest temperatures are ";
284
print_r(array_slice($temp1,0,5));
285
$temp2=array_reverse($temp1);
286
echo "<br>";
287
echo "List of 5 highest temperatures are ";
288
print_r(array_slice($temp2,0,5));
289
echo "<br>";
290
//----------------------------------------------------------------------------------------------------
291
function fun($b) //Function
292
{
293
    echo $b;
294
}
295
$a=10;
296
fun($a);
297
//--------------------------------------------------------------------------------------------------
298
function fun1($a,$b)
299
{
300
	$c=$a+$b;
301
	return $c;
302
}
303
echo "<br>Sum is ".fun1(5,10);
304
//---------------------------------------
305
echo "<br>";
306
function fun2($dividend,$divisor)
307
{
308
	$quotient=$dividend/$divisor;
309
	$array=array($dividend,$divisor,$quotient);
310
	return $array;
311
}
312
print_r(fun2(10,20));
313
//-------------------------------------------------------------------------
314
function factorial($number) //Factorial of a number using recursion
315
{          
316
    if ($number < 2) 
317
    {
318
        return 1;
319
    }
320
    return ($number * factorial($number-1)); 
321
}
322
echo "<br>Factorial is ".factorial(5);
323
324
function factorial1($num)
325
{
326
	$fact=1;
327
	for($i=$num;$i<0;$i--)
328
	{
329
		 $fact=$fact*$i;
330
	}
331
	return $fact;
332
}
333
echo factorial1(20);
334
//------------------------------------------------------------------
335
function fun3(&$a,&$b)
336
{
337
	$c=$a+$b;
338
	return $c;
339
}
340
$x=10;
341
$y=20;
342
echo "<br>Sum is ".fun3($x,$y);
343
//-----------------------------------
344
function setHeight($minheight=50)
345
{
346
    echo "<br>The height is : $minheight <br>";
347
}
348
setHeight(350);
349
setHeight();
350
setHeight(135);
351
setHeight(80);
352
//------------------------------------------------------------
353
function sayHello()
354
{
355
    echo "hello"."<br>";
356
}
357
$function_holder="sayhello";
358
$function_holder();
359
//--------------------------------------------------------------
360
echo "<br>";
361
function add(...$numbers)
362
{
363
    $sum=0;
364
    foreach($numbers as $n)
365
    {
366
        $sum +=$n;
367
    }
368
    return $sum;
369
}
370
echo add(1,2,3,4);
371
//--------------------------------------------------------
372
echo "<br>";
373
function even(...$numbers)
374
{
375
    $sum=0;
376
    foreach($numbers as $n)
377
    {
378
        if($n%2==0)
379
        {
380
            $sum +=$n;
381
        }
382
    }
383
    return $sum;
384
}
385
echo even(1,2,3,4);
386
//--------------------------------------------------------
387
echo "<br>";    //Local,Global,Static Variables 
388
$a=20;
389
$x=10;
390
function ex()
391
{
392
    $x=5;
393
    global $a;
394
    static $s=30;
395
    $a++;
396
    $s++;
397
    $x++;
398
echo "<br>Global Variable ".$a;
399
echo "<br>Local Variable ".$x;
400
echo "<br>Static Variable ".$s."<br>";
401
}
402
ex();
403
ex();
404
ex();
405
ex();
406
echo $x;
407
// echo $s will give error because scope of static variable is inside the block only.
408
//--------------------------------------------------------------------------------------
409
<?php
410
print_r($_GET)
411
if(isset($_GET['name'],$_GET['Rollo'],$_GET['Age'],$_GET['Address']))
412
?>
413
-----------------------------------------------cookie-----------
414
<?php
415
$cookie_name="user";
416
$cookie_value="Juju Spices";
417
setcookie($cookie_name, $cookie_value, time() + (86400*30), "/");
418
?>
419
420
<html>
421
<body>
422
	<?php
423
		if(!isset($_COOKIE[$cookie_name]))
424
		{
425
			echo "Cookie named " . $cookie_name . " is not set!";
426
		}
427
		else
428
		{
429
			echo "Cookie " . $cookie_name . " is set!<br>";
430
			echo "Value is: " . $_COOKIE[$cookie_name];
431
		}
432
		?>
433
	</body>
434
</html>
435
------------------------------------session-------------------
436
<?php
437
session_start();
438
?>
439
<!DOCTYPE html>
440
<html>
441
<body>
442
<?php
443
$_SESSION["favcolor"] = "green";
444
$_SESSION["favanimal"] = "cat";
445
446
echo "Session variables are set.";
447
?>
448
</body>
449
</html>
450
----------------------------------------------------------------------------------
451
<?php
452
session_start();
453
?>
454
<!DOCTYPE html>
455
<html>
456
<body>
457
458
<?php
459
// Echo session variables that were set on previous page
460
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
461
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
462
?>
463
464
</body>
465
</html>
466
------------------------------------------------------------------------------------------
467
<?php
468
session_start();
469
?>
470
<!DOCTYPE html>
471
<html>
472
<body>
473
474
<?php
475
print_r($_SESSION);
476
?>
477
478
</body>
479
</html>
480
---------------------------------------Sanitization------------------------------
481
<?php
482
print_r(filter_list());
483
if(isset($_POST['submit']));
484
$a=	$_POST['name'];
485
if(empty($a))
486
{
487
	echo "Name Not found";
488
}
489
else
490
{
491
	$a=filter_var($a,FILTER_SANITIZE_STRING);
492
	echo "<br>";
493
	echo $a."==is Sanitized.<br>";
494
	if(!preg_match("/^[a-zA-Z]+$/",$a))
495
	{
496
		echo "Name Invalid<br>";
497
	}
498
	else
499
	{
500
		echo "Valid Named<br>";
501
	}
502
503
}
504
$b=$_POST['Roll'];
505
506
$c=$_POST['Age'];
507
$d=$_POST['Address'];
508
echo "Name is {$a},Roll  is {$b},Age is {$c},Address is {$d}";
509
510
?>
511
512
<form action="get.php" method="POST">
513
	<input type="text" name="name" placeholder="Name" required="name">
514
	<input type="text" name="Roll" placeholder="roll">
515
	<input type="text" name="Age" placeholder="age">
516
	<input type="text" name="Address" placeholder="add">
517
	<input type="Submit">
518
</form>
519
----------------------------------------------------------------form validation---------------------
520
<?php
521
$a=$_GET["name"];
522
if(empty($a))
523
{
524
	echo 'name not found';
525
}
526
else
527
{
528
	if(!preg_match("/^[a-zA-Z]*$/",$a))
529
	{	
530
		echo "only letters are allowed<br>";
531
	}
532
	else
533
	{
534
		echo $a."<br>";
535
	}
536
}
537
$b=$_GET["email"];
538
if(empty($b))
539
{
540
	echo 'email not found<br>';
541
}
542
else
543
{
544
	if(!filter_var($b,FILTER_VALIDATE_EMAIL))
545
	{	
546
		echo "invalid email<br>";
547
	}
548
	else
549
	{
550
		echo $b."<br>";
551
	}
552
}
553
$c=$_GET["number"];
554
if(empty($c))
555
{
556
	echo 'number not found<br>';
557
}
558
else
559
{
560
	
561
	if(!preg_match("/^[0-9]{10}+$/",$c))
562
	{	
563
		echo "only numbers are allowed<br>";
564
	}
565
	else
566
	{
567
		echo $c;
568
	}
569
}																								
570
?>
571
------------------------------------------------------database query------------------------
572
<?php
573
$username ="root";
574
$password = "";
575
$hostname ="localhost";;
576
577
//connetion to the database
578
$dbhandle =mysql_connect($hostname, $username, $password)
579
	or die("Unable to connect to mySql");
580
echo"Connected to MySQL<br>";
581
// select a database to work with
582
$selected = mysql_select_db("examples",$dbhandle)
583
or die("Could not select examples");
584
585
//execute the SQL query and return records
586
$result = mysql_query("SELECT id, model, year FROM cars");
587
588
//fetch the data from the database
589
while($row =mysql_fetch_array($result))
590
{
591
	echo "ID:".$row{'id'}."Name:".$row{'model'}."year:".$row{'year'}."<br>";
592
}
593
//close the connection
594
mysql_close($dbhandle);
595
?>
596
---------------------------------------------------------------create database------------
597
<?php
598
$hostname = "localhost";
599
$username = "root";
600
$password = "";
601
602
603
// Create connection
604
$conn = new mysqli($hostname, $username, $password);
605
// Check connection
606
if ($conn->connect_error) {
607
    die("Connection failed: " . $conn->connect_error);
608
} 
609
610
// Create database
611
$sql = "CREATE DATABASE myDB1";
612
if ($conn->query($sql)== TRUE) {
613
    echo "Database created successfully";
614
} else {
615
    echo "Error creating database: " . $conn->error;
616
}
617
618
$conn->close();
619
?>
620
-------------------------create table--------------------
621
 sql to create table
622
$sql = "CREATE TABLE employee (
623
emp_id INT(1) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
624
emp_name VARCHAR(30) NOT NULL,
625
emp_dept VARCHAR(30) NOT NULL,
626
salary INT(6)
627
)";
628
-----------------------------------data insert
629
<?php
630
$hostname = "localhost";
631
$username = "root";
632
$password = "";
633
$dbname = "mydb";
634
635
// Create connection
636
$conn = new mysqli($servername, $username, $password, $dbname);
637
// Check connection
638
if ($conn->connect_error) {
639
    die("Connection failed: " . $conn->connect_error);
640
} 
641
642
$sql = "INSERT INTO employee (emp_id,emp_name,emp_dept,salary)
643
VALUES (1,'a','CSE',40000);";
644
$sql = "INSERT INTO employee (emp_id,emp_name,emp_dept,salary)
645
VALUES (2,'b','IT',30000);";
646
$sql = "INSERT INTO employee (emp_id,emp_name,emp_dept,salary)
647
VALUES (3,'c','EEE',45000);";
648
$sql = "INSERT INTO employee (emp_id,emp_name,emp_dept,salary)
649
VALUES (4,'d','ECE',50000);";
650
$sql = "INSERT INTO employee (emp_id,emp_name,emp_dept,salary)
651
VALUES (5,'e','CSE',55000);";
652
653
654
655
if ($conn->multi_query($sql) === TRUE) {
656
    echo "New records created successfully";
657
} else {
658
    echo "Error: " . $sql . "<br>" . $conn->error;
659
}
660
661
$conn->close();
662
?>
663
----------------------------------------------------post method-----------
664
665
<?php
666
667
668
if(isset($_POST["Submit"]))
669
{
670
	extract($_POST);
671
672
$a=	$_POST["name"];
673
$b=$_POST['roll'];
674
$c=$_POST['class'];
675
if(empty($name)){
676
echo "value is NOT there";
677
}
678
else
679
{
680
	echo $a;
681
}
682
}
683
684
?>
685
686
<form  action="post.php" method="post">
687
	name<input type="text" name="name" placeholder="">
688
	rollo<input type="text" name="roll" placeholder="">
689
	class<input type="text" name="class" placeholder="">
690
691
	<input type="Submit">
692
</form>
693
694
------------------------------------db.php-----------
695
<?php
696
$g=mysqli_connect('localhost','root','','hd1');
697
if($g==false)
698
{
699
	echo "connection is not done";
700
}
701
else
702
{
703
	echo "connection is done";
704
}
705
706
if(isset($_POST["submit"]))
707
{
708
	extract($_POST);
709
710
$a=$_POST["first_name"];
711
$b=$_POST['last_name'];
712
$c=$_POST['reg_no'];
713
$d=$_POST['password'];
714
$sql="INSERT INTO mytable(first_name,last_name,reg_no,password) VALUES ('$a', '$b', '$c','$d')";
715
716
if(mysqli_query($g,$sql))
717
{
718
	echo "data insert";
719
}
720
else{
721
	echo "data not insert";
722
}
723
}
724
725
726
?>
727
<form  action="db.php" method="post"><br>
728
	first_name<input type="text" name="first_name" placeholder=""><br>
729
	last_name<input type="text" name="last_name" placeholder=""><br>
730
	reg_no<input type="text" name="reg_no" placeholder=""><br>
731
	password<input type="password" name="password" placeholder=""><br>
732
	<input type="submit" name="submit">
733
734
---------------------------------------------------------login.php-----------
735
<?php
736
$connect=mysqli_connect("localhost","root","" ,"hd1");
737
738
if($connect->connect_error)
739
{
740
   die("connection failed:" . $connect->connect_error);
741
}
742
echo "Connnection success";
743
744
745
if(isset($_POST['login'])){
746
	$first_name=$_POST['first_name'];
747
	$password=$_POST['password'];
748
	$query="select * from mytable where first_name='$first_name' and password='$password'";
749
	$result=mysqli_query($connect,$query);
750
	if(mysqli_num_rows($result)>0)
751
	{
752
		echo "Login ";
753
754
   }
755
	else
756
    {
757
        echo "<script>alert('error login')</script>";
758
    }
759
    }
760
761
 ?>
762
763
 <form method="POST" action="login.php">
764
    <input type="text" name="first_name" placeholder="first_name" required/>
765
    <input type="password" name="password" placeholder="password" required/>
766
    <button name="login" type="submit">Login</button>
767
</form>
768
-----------------------------------------------email sent----------
769
<?php
770
include('C:/xamppp/htdocs/phpclass/PHPMailerAutoload.php');
771
include('C:/xamppp/htdocs/phpclass/class.smtp.php');
772
$mail= new PHPMailer();
773
$mail->isSMTP();
774
$mail->SMTPAuth= true;
775
$mail->SMTPSecure='t1s'; //transport layer security protocol
776
$mail->Host = 'smtp.gmail.com';
777
$mail->Port = 587;
778
$mail->Username= 'sharmashikha0698@gmail.com';
779
780
$mail->Password = '';
781
$mail->Subject = 'hello';
782
$mail->Body = 'mail';
783
$mail->addAddress('sharmashikha0698@gmail.com');
784
$mail->Send();
785
if(!$mail->Send())
786
{
787
	echo "message not sent";
788
}
789
else
790
{
791
	echo "message  sent";
792
793
}
794
?>
795
-------------------------------------overriding---------
796
<?php
797
// The parent class has hello method that returns "beep".
798
class Car {
799
  public function hello()
800
  {
801
    echo "beep";
802
  }
803
}
804
 
805
//The child class has hello method that returns "Halllo"
806
class SportsCar extends Car {
807
  public function hello()
808
  {
809
    echo "Hallo";
810
	parent::hello(); 
811
  }
812
}
813
    
814
//Create a new object
815
$sportsCar1=new SportsCar();
816
  
817
//Get the result of the hello method
818
echo $sportsCar1 -> hello();
819
?>
820
-----------------------------session login------
821
<?php
822
session_start();
823
$message="";
824
if(count($_POST)>0) {
825
 $con = mysqli_connect('127.0.0.1:3306','root','','admin') or die('Unable To connect');
826
$result = mysqli_query($con,"SELECT * FROM login_user WHERE name='" . $_POST["name"] . "' and password = '". $_POST["password"]."'");
827
$row  = mysqli_fetch_array($result);
828
if(is_array($row)) {
829
$_SESSION["id"] = $row[id];
830
$_SESSION["name"] = $row[name];
831
} else {
832
$message = "Invalid Username or Password!";
833
}
834
}
835
if(isset($_SESSION["id"])) {
836
header("Location:index.php");
837
}
838
?>
839
<html>
840
<head>
841
<title>User Login</title>
842
</head>
843
<body>
844
<form name="frmUser" method="post" action="" align="center">
845
<div class="message"><?php if($message!="") { echo $message; } ?></div>
846
<h3 align="center">Enter Login Details</h3>
847
 Username:<br>
848
 <input type="text" name="name">
849
 <br>
850
 Password:<br>
851
<input type="password" name="password">
852
<br><br>
853
<input type="submit" name="submit" value="Submit">
854
<input type="reset">
855
</form>
856
</body>
857
</html>
858
-----------------------------------session index 
859
<?php
860
session_start();
861
?>
862
<html>
863
<head>
864
<title>User Login</title>
865
</head>
866
<body>
867
868
<?php
869
if($_SESSION["name"]) {
870
?>
871
Welcome <?php echo $_SESSION["name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.
872
<?php
873
}else echo "<h1>Please login first .</h1>";
874
?>
875
</body>
876
</html>
877
---------------------------session logout-----------
878
<?php
879
session_start();
880
unset($_SESSION["id"]);
881
unset($_SESSION["name"]);
882
header("Location:login.php");
883
?>
884
---------------------------------------------------cookie login
885
<?php
886
session_start();
887
if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
888
	if($_COOKIE['username']=='abc' && $_COOKIE['password']=='123') {
889
		$_SESSION['username'] = $_COOKIE['username'];
890
		header('location:welcome.php');
891
	}
892
	else
893
		$error = "Account's Invalid";
894
}
895
896
if(isset($_POST['login'])){
897
	if($_POST['username']=='abc' && $_POST['password']=='123'){
898
		$_SESSION['username'] = $_POST['username'];
899
		if($_POST['remember'] != NULL) {
900
			setcookie('username', $_POST['username'], time() + (86400 * 30), "/");
901
			setcookie('password', $_POST['password'], time() + (86400 * 30), "/");
902
		}
903
		header('location:welcome.php');
904
	}
905
	else {
906
		$error = "Account's Invalid";
907
	}
908
}
909
?>
910
<form method="post">
911
	<fieldset>
912
		<legend>Login</legend>
913
		<?php echo isset($error) ? $error : ''; ?>
914
		<table cellpadding="2" cellspacing="2">
915
			<tr>
916
				<td>Username</td>
917
				<td><input type="text" name="username"></td>
918
			</tr>
919
			<tr>
920
				<td>Password</td>
921
				<td><input type="password" name="password"></td>
922
			</tr>
923
			<tr>
924
				<td>Remember Me</td>
925
				<td><input type="checkbox" name="remember"></td>
926
			</tr>
927
			<tr>
928
				<td>&nbsp;</td>
929
				<td><input type="submit" name="login" value="Login"></td>
930
			</tr>
931
		</table>
932
	</fieldset>
933
</form>
934
-----------------------------------------------------------------Welcome Page
935
<?php
936
session_start();
937
if(isset($_GET['action']) && $_GET['action']=='logout'){
938
	// Remoce session
939
	unset($_SESSION['username']);
940
	// Remoce cookie
941
	setcookie('username', '', 0, "/");
942
	setcookie('password', '', 0, "/");
943
	header('location:index.php');
944
}
945
echo 'Welcome '.$_SESSION['username'];
946
?>
947
<br>
948
<a href="welcome.php?action=logout">Logout</a>