· 9 years ago · Apr 24, 2017, 10:08 AM
1HTML Validation
2<!DOCTYPE html>
3<html>
4<body>
5
6<p>Display "Good day!" if the hour is less than 18:00:</p>
7
8<p id="demo">Good Evening!</p>
9
10<form>
11Company name <input type="text" id="hh" name="cn" required pattern="[a-zA-Z]+">
12Mobile number <input type="text" id="nn" name="mn" pattern="[0-9]{10,10}">
13Email <input type="email" id="em" name="e" required >
14<input type="submit">
15<input type="reset">
16</form>
17
18</body>
19</html>
20
21
22PASSWORD VALIDATION
23
24
25<script>
26function validateform(){
27var name=document.myform.name.value;
28var password=document.myform.password.value;
29
30if (name==null || name==""){
31 alert("Name can't be blank");
32 return false;
33}else if(password.length<6){
34 alert("Password must be at least 6 characters long.");
35 return false;
36 }
37}
38</script>
39<body>
40<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
41Name: <input type="text" name="name"><br/>
42Password: <input type="password" name="password"><br/>
43<input type="submit" value="register">
44</form>
45
46
47
48EMAIL VALIDATION
49
50<script>
51function validateemail()
52{
53var x=document.myform.email.value;
54var atposition=x.indexOf("@");
55var dotposition=x.lastIndexOf(".");
56if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
57 alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
58 return false;
59 }
60}
61</script>
62<body>
63<form name="myform" method="post" action="#" onsubmit="return validateemail();">
64Email: <input type="text" name="email"><br/>
65
66<input type="submit" value="register">
67</form>
68
69
70
71
72
73
74
75
76JAVASCRIPT VALIDATION
77<!DOCTYPE html>
78<html>
79<head>
80<script>
81function checkall()
82{
83var x=document.kk.cn.value;
84var y=document.kk.mn.value;
85var z=document.kk.e.value;
86var p=document.getElementById("aa");
87var reg1=/[a-zA-z]+/g;
88var reg2=/[0-9]{10,10}/g;
89var reg3=/[a-z0-9]+[@]+[a-z]+.[a-z]{3,3}/g;
90if(reg1.test(x))
91{
92if(reg2.test(y))
93{
94if(reg3.test(z))
95{
96return true;
97}
98else
99{
100p.innerHTML="Enter a valid email address";
101return false;
102}
103}
104else
105{
106p.innerHTML="Enter a valid phone number";
107return false;
108}
109}
110else
111{
112p.innerHTML="Enter a valid name";
113return false;
114}
115}
116</script>
117</head>
118<body>
119
120<p id="aa">Display "Good day!" if the hour is less than 18:00:</p>
121
122<p id="demo">Good Evening!</p>
123
124<form name="kk">
125Company name <input type="text" id="hh" name="cn" >
126Mobile number <input type="text" id="nn" name="mn">
127Email <input type="text" id="pp" name="e" >
128<input type="submit" onclick="return checkall()">
129<input type="reset">
130</form>
131
132</body>
133</html>
134
135
136
137
138table td:first-child:hover
139
140NEWTABLE.php
141<?php
142$servername = "localhost";
143$username = "root";
144$password = "";
145$dbname = "Database";
146
147// Create connection
148$conn = mysqli_connect($servername, $username, $password, $dbname);
149// Check connection
150if (mysqli_connecterrno()) {
151 die("Connection failed: " . mysqli_connect_error());
152}
153
154// sql to create table
155$sql = "CREATE TABLE MyGuests (
156id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
157firstname VARCHAR(30) NOT NULL,
158lastname VARCHAR(30) NOT NULL,
159email VARCHAR(50),
160reg_date TIMESTAMP
161)";
162
163if (mysqli_query($conn,$sql)) {
164 echo "Table MyGuests created successfully";
165} else {
166 echo "Error creating table: " . mysqli_error($conn);
167}
168
169mysqli_close($conn);
170?>
171
172FORM.php
173
174<?php
175
176$servername = "localhost";
177$username = "root";
178$password = "";
179$dbname = "Database";
180
181// Create connection
182$conn = mysqli_connect($servername, $username, $password, $dbname);
183// Check connection
184if (mysqli_connect_errno()) {
185 die("Connection failed: " . mysqli_connect_error());
186}
187$fn=$_POST['firstname'];
188$ln=$_POST['lastname'];
189$dob=$_POST['dob'];
190$sql = "insert into records(firstname,lastname,dob) values('$fn','$ln','$dob');";
191$r=mysqli_query($conn,$sql);
192if(!$r)
193{die(mysqli_error($conn));
194}
195else
196{echo "Record created";}
197
198$conn->close();
199?>
200
201
202
203
204
205
206DISPLAY.php
207
208<?php
209
210$servername = "localhost";
211$username = "root";
212$password = "";
213$dbname = "Database";
214
215// Create connection
216$conn = mysqli_connect($servername, $username, $password, $dbname);
217// Check connection
218if (mysqli_connect_errno()) {
219 die("Connection failed: " . mysqli_connect_error());
220}
221$fn=$_POST['firstname'];
222$ln=$_POST['lastname'];
223$dob=$_POST['dob'];
224$sql = "insert into records(firstname,lastname,dob) values('$fn','$ln','$dob');";
225$r=mysqli_query($conn,$sql);
226if(!$r)
227{die(mysqli_error($conn));
228}
229else
230{
231$s = "SELECT * FROM records";
232$result = mysqli_query($conn, $s);
233
234if (mysqli_num_rows($result) > 0) {
235 // output data of each row
236echo "<center> " . "<table style='background-color:yellow ;color:red'>";
237 while($row = mysqli_fetch_assoc($result)) {
238echo " <tr>";
239 echo "<td>" . $row['firstname'] . "</td>" . "<td>" . $row['lastname'] . "</td>" . "<td>". $row['dob'] . "</td>" . "</tr>";
240 }
241echo "</table> " . "</center>";
242} else {
243 echo "0 results";
244}
245echo "Record created";}
246
247$conn->close();
248?>
249
250
251
252
253EDIT.php
254
255<?php
256
257$servername = "localhost";
258$username = "root";
259$password = "";
260$dbname = "Database";
261
262// Create connection
263$conn = mysqli_connect($servername, $username, $password, $dbname);
264// Check connection
265if (mysqli_connect_errno()) {
266 die("Connection failed: " . mysqli_connect_error());
267}
268$fn=$_POST['firstname'];
269$sql = "select * from records where firstname='$fn';";
270$r=mysqli_query($conn,$sql);
271if(!$r)
272{die(mysqli_error($conn));
273}
274else
275{
276 echo" <form action='edit1.php' method='post'>";
277 while( $row=mysqli_fetch_array($r))
278 {
279 echo "<input type='text' value=$row[1] name='firstname' disabled>";
280 echo"<input type='text' value=$row[2] name='lastname'>";
281 echo"<input type='text' value=$row[3] name='dob'>;
282 <input type='submit'>
283 </form>"
284
285 }
286}
287$conn->close();
288?>
289
290
291
292EDIT1.php
293
294
295<?php
296
297$servername = "localhost";
298$username = "root";
299$password = "";
300$dbname = "Database";
301
302// Create connection
303$conn = mysqli_connect($servername, $username, $password, $dbname);
304// Check connection
305if (mysqli_connect_errno()) {
306 die("Connection failed: " . mysqli_connect_error());
307}
308$fn=$_POST['firstname'];
309$ln=$_POST['lastname'];
310$dob=$_POST['dob'];
311$sql = "update records set dob='$dob' where firstname='$fn' and lastname='$ln';";
312$r=mysqli_query($conn,$sql);
313if(!$r)
314{die(mysqli_error($conn));
315}
316else
317{echo "Record edited";}
318
319$conn->close();
320?>
321
322
323PHP FILES
324
325
326<?php
327$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
328echo fread($myfile,filesize("webdictionary.txt"));
329fclose($myfile);
330?>
331
332r Open a file for read only. File pointer starts at the beginning of the file
333w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
334a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
335x Creates a new file for write only. Returns FALSE and an error if file already exists
336r+ Open a file for read/write. File pointer starts at the beginning of the file
337w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
338a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
339x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
340
341<?php
342$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
343$txt = "John Doe\n";
344fwrite($myfile, $txt);
345$txt = "Jane Doe\n";
346fwrite($myfile, $txt);
347fclose($myfile);
348?>
349
350
351PHP FILE UPLOAD
352
353
354HTML
355
356
357<!DOCTYPE html>
358<html>
359<body>
360
361<form action="upload.php" method="post" enctype="multipart/form-data">
362 Select image to upload:
363 <input type="file" name="fileToUpload" id="fileToUpload">
364 <input type="submit" value="Upload Image" name="submit">
365</form>
366
367</body>
368</html>
369
370
371PHP
372
373<?php
374$target_dir = "uploads/";
375$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
376$uploadOk = 1;
377$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
378// Check if image file is a actual image or fake image
379if(isset($_POST["submit"])) {
380 $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
381 if($check !== false) {
382 echo "File is an image - " . $check["mime"] . ".";
383 $uploadOk = 1;
384 } else {
385 echo "File is not an image.";
386 $uploadOk = 0;
387 }
388}
389// Check if file already exists
390if (file_exists($target_file)) {
391 echo "Sorry, file already exists.";
392 $uploadOk = 0;
393}
394// Check file size
395if ($_FILES["fileToUpload"]["size"] > 500000) {
396 echo "Sorry, your file is too large.";
397 $uploadOk = 0;
398}
399// Allow certain file formats
400if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
401&& $imageFileType != "gif" ) {
402 echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
403 $uploadOk = 0;
404}
405// Check if $uploadOk is set to 0 by an error
406if ($uploadOk == 0) {
407 echo "Sorry, your file was not uploaded.";
408// if everything is ok, try to upload file
409} else {
410 if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
411 echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
412 } else {
413 echo "Sorry, there was an error uploading your file.";
414 }
415}
416?>
417
418
419PHP Cookies
420
421
422What is a Cookie?
423A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
424
425Create Cookies With PHP
426A cookie is created with the setcookie() function.
427
428Syntax
429setcookie(name, value, expire, path, domain, secure, httponly);
430Only the name parameter is required. All other parameters are optional.
431
432PHP Create/Retrieve a Cookie
433The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).
434
435We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:
436
437Example
438<?php
439$cookie_name = "user";
440$cookie_value = "John Doe";
441setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
442?>
443<html>
444<body>
445
446<?php
447if(!isset($_COOKIE[$cookie_name])) {
448 echo "Cookie named '" . $cookie_name . "' is not set!";
449} else {
450 echo "Cookie '" . $cookie_name . "' is set!<br>";
451 echo "Value is: " . $_COOKIE[$cookie_name];
452}
453?>
454
455</body>
456</html>
457Run example »
458Note: The setcookie() function must appear BEFORE the <html> tag.
459
460Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
461
462
463Modify a Cookie Value
464To modify a cookie, just set (again) the cookie using the setcookie() function:
465
466Example
467<?php
468$cookie_name = "user";
469$cookie_value = "Alex Porter";
470setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
471?>
472<html>
473<body>
474
475<?php
476if(!isset($_COOKIE[$cookie_name])) {
477 echo "Cookie named '" . $cookie_name . "' is not set!";
478} else {
479 echo "Cookie '" . $cookie_name . "' is set!<br>";
480 echo "Value is: " . $_COOKIE[$cookie_name];
481}
482?>
483
484</body>
485</html>
486Run example »
487Delete a Cookie
488To delete a cookie, use the setcookie() function with an expiration date in the past:
489
490Example
491<?php
492// set the expiration date to one hour ago
493setcookie("user", "", time() - 3600);
494?>
495<html>
496<body>
497
498<?php
499echo "Cookie 'user' is deleted.";
500?>
501
502</body>
503</html>
504Run example »
505Check if Cookies are Enabled
506The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
507
508Example
509<?php
510setcookie("test_cookie", "test", time() + 3600, '/');
511?>
512<html>
513<body>
514
515<?php
516if(count($_COOKIE) > 0) {
517 echo "Cookies are enabled.";
518} else {
519 echo "Cookies are disabled.";
520}
521?>
522
523</body>
524</html>
525
526
527
528
529PHP Sessions
530
531PHP 5 Sessions
532? PreviousNext ?
533A session is a way to store information (in variables) to be used across multiple pages.
534
535Unlike a cookie, the information is not stored on the users computer.
536
537What is a PHP Session?
538When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.
539
540Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
541
542So; Session variables hold information about one single user, and are available to all pages in one application.
543
544Tip: If you need a permanent storage, you may want to store the data in a database.
545
546Start a PHP Session
547A session is started with the session_start() function.
548
549Session variables are set with the PHP global variable: $_SESSION.
550
551Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:
552
553Example
554<?php
555// Start the session
556session_start();
557?>
558<!DOCTYPE html>
559<html>
560<body>
561
562<?php
563// Set session variables
564$_SESSION["favcolor"] = "green";
565$_SESSION["favanimal"] = "cat";
566echo "Session variables are set.";
567?>
568
569</body>
570</html>
571Run example »
572Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
573
574
575Get PHP Session Variable Values
576Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php").
577
578Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
579
580Also notice that all session variable values are stored in the global $_SESSION variable:
581
582Example
583<?php
584session_start();
585?>
586<!DOCTYPE html>
587<html>
588<body>
589
590<?php
591// Echo session variables that were set on previous page
592echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
593echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
594?>
595
596</body>
597</html>
598Run example »
599Another way to show all the session variable values for a user session is to run the following code:
600
601Example
602<?php
603session_start();
604?>
605<!DOCTYPE html>
606<html>
607<body>
608
609<?php
610print_r($_SESSION);
611?>
612
613</body>
614</html>
615Run example »
616How does it work? How does it know it's me?
617
618Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
619
620Modify a PHP Session Variable
621To change a session variable, just overwrite it:
622
623Example
624<?php
625session_start();
626?>
627<!DOCTYPE html>
628<html>
629<body>
630
631<?php
632// to change a session variable, just overwrite it
633$_SESSION["favcolor"] = "yellow";
634print_r($_SESSION);
635?>
636
637</body>
638</html>
639Run example »
640Destroy a PHP Session
641To remove all global session variables and destroy the session, use session_unset() and session_destroy():
642
643Example
644<?php
645session_start();
646?>
647<!DOCTYPE html>
648<html>
649<body>
650
651<?php
652// remove all session variables
653session_unset();
654
655// destroy the session
656session_destroy();
657?>
658
659</body>
660</html>
661
662
663HTML DROPDOWN
664
665
666<!DOCTYPE html>
667<html>
668<head>
669<style>
670.dropbtn {
671 background-color: #4CAF50;
672 color: white;
673 padding: 16px;
674 font-size: 16px;
675 border: none;
676 cursor: pointer;
677}
678
679.dropdown {
680 position: relative;
681 display: inline-block;
682}
683
684.dropdown-content {
685 display: none;
686 position: absolute;
687 background-color: #f9f9f9;
688 min-width: 160px;
689 box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
690 z-index: 1;
691}
692
693.dropdown-content a {
694 color: black;
695 padding: 12px 16px;
696 text-decoration: none;
697 display: block;
698}
699
700.dropdown-content a:hover {background-color: #f1f1f1}
701
702.dropdown:hover .dropdown-content {
703 display: block;
704}
705
706.dropdown:hover .dropbtn {
707 background-color: #3e8e41;
708}
709</style>
710</head>
711<body>
712
713<h2>Hoverable Dropdown</h2>
714<p>Move the mouse over the button to open the dropdown menu.</p>
715
716<div class="dropdown">
717 <button class="dropbtn">Dropdown</button>
718 <div class="dropdown-content">
719 <a href="#">Link 1</a>
720 <a href="#">Link 2</a>
721 <a href="#">Link 3</a>
722 </div>
723</div>
724
725</body>
726</html>