Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
10 views
Codes of PHP
Uploaded by
selinasacc190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download now
Download
Save Codes of PHP For Later
Download
Save
Save Codes of PHP For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
10 views
Codes of PHP
Uploaded by
selinasacc190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download now
Download
Save Codes of PHP For Later
Carousel Previous
Carousel Next
Save
Save Codes of PHP For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 7
Search
Fullscreen
#Using mysqli_connect
#login.php with form validation
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = mysqli_connect("localhost", "root", "", "your_database_name");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
setcookie("user_email", $email, time() + (86400 * 30), "/"); // 30-day
cookie
setcookie("loggedin", true, time() + (86400 * 30), "/");
$_SESSION['loggedin'] = true;
header("Location: form.php");
exit();
} else {
echo "Invalid email or password.";
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script>
function validateForm() {
const email = document.forms["loginForm"]["email"].value;
const password = document.forms["loginForm"]["password"].value;
if (!email || !password) {
alert("Both email and password are required.");
return false;
}
// Basic email format validation
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address.");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginForm" method="post" action="login.php" onsubmit="return
validateForm()">
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
#Form.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: login.php");
exit();
}
$conn = mysqli_connect("localhost", "root", "", "your_database_name");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$number = $_POST['number'];
$checkbox = isset($_POST['checkbox']) ? 1 : 0;
$query = "INSERT INTO form_data (name, email, age, gender, dob, number,
checkbox) VALUES ('$name', '$email', '$age', '$gender', '$dob', '$number',
'$checkbox')";
if (mysqli_query($conn, $query)) {
echo "Data saved successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="form.php">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Age:</label><br>
<input type="number" name="age" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
<label>Phone Number:</label><br>
<input type="number" name="number" required><br><br>
<label>Agree to Terms:</label>
<input type="checkbox" name="checkbox"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
#Using PDO
#login.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND
password = :password");
$stmt->execute(['email' => $email, 'password' => $password]);
if ($stmt->rowCount() == 1) {
setcookie("user_email", $email, time() + (86400 * 30), "/"); // 30-day
cookie
setcookie("loggedin", true, time() + (86400 * 30), "/");
$_SESSION['loggedin'] = true;
header("Location: form.php");
exit();
} else {
echo "Invalid email or password.";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script>
function validateForm() {
const email = document.forms["loginForm"]["email"].value;
const password = document.forms["loginForm"]["password"].value;
if (!email || !password) {
alert("Both email and password are required.");
return false;
}
// Basic email format validation
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address.");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginForm" method="post" action="login.php" onsubmit="return
validateForm()">
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
#Form.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: login.php");
exit();
}
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$number = $_POST['number'];
$checkbox = isset($_POST['checkbox']) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO form_data (name, email, age, gender,
dob, number, checkbox) VALUES
(:name, :email, :age, :gender, :dob, :number, :checkbox)");
$stmt->execute([
'name' => $name,
'email' => $email,
'age' => $age,
'gender' => $gender,
'dob' => $dob,
'number' => $number,
'checkbox' => $checkbox
]);
echo "Data saved successfully!";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="form.php">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Age:</label><br>
<input type="number" name="age" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
<label>Phone Number:</label><br>
<input type="number" name="number" required><br><br>
<label>Agree to Terms:</label>
<input type="checkbox" name="checkbox"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
#Rest API
<?php
header("Content-Type: application/json; charset=UTF-8");
// Database connection
$host = "localhost"; // Host
$db = "api_example"; // Database name
$user = "root"; // MySQL user
$pass = ""; // MySQL password (default is empty for XAMPP)
$conn = new mysqli($host, $user, $pass, $db);
// Check connection
if ($conn->connect_error) {
die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));
}
// Get the user ID from query string
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
// Prepare the SQL query to fetch user info by ID
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id); // "i" for integer
$stmt->execute();
// Get the result
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// Fetch user data
$user_data = $result->fetch_assoc();
echo json_encode($user_data); // Output data in JSON format
} else {
echo json_encode(["error" => "User not found"]);
}
$stmt->close();
} else {
echo json_encode(["error" => "No user ID provided"]);
}
// Close connection
$conn->close();
?>
#Array , file function
<!DOCTYPE html>
<html>
<head>
<title>PHP Array and File/Image Handling</title>
</head>
<body>
<h1>PHP Array and File/Image Handling Demonstration</h1>
<h2>Array Handling</h2>
<pre>
<?php
// Indexed Array
$indexedArray = array("Apple", "Banana", "Cherry");
echo "Indexed Array:\n";
print_r($indexedArray);
// Associative Array
$associativeArray = array("John" => 25, "Jane" => 30, "Joe" => 35);
echo "\nAssociative Array:\n";
print_r($associativeArray);
// Multidimensional Array
$multiArray = array(
"Fruits" => array("Apple", "Banana", "Cherry"),
"Vegetables" => array("Carrot", "Broccoli", "Peas")
);
echo "\nMultidimensional Array:\n";
print_r($multiArray);
// Array Functions
echo "\nArray Functions:\n";
// array_merge
$mergedArray = array_merge($indexedArray, $associativeArray);
echo "Merged Array:\n";
print_r($mergedArray);
// array_push
array_push($indexedArray, "Date");
echo "After array_push:\n";
print_r($indexedArray);
// array_pop
array_pop($indexedArray);
echo "After array_pop:\n";
print_r($indexedArray);
// array_keys
$keys = array_keys($associativeArray);
echo "Array Keys:\n";
print_r($keys);
// array_values
$values = array_values($associativeArray);
echo "Array Values:\n";
print_r($values);
// array_unique
$uniqueArray = array_unique(array("Apple", "Banana", "Apple", "Cherry"));
echo "Unique Array:\n";
print_r($uniqueArray);
// in_array
$inArray = in_array("Apple", $indexedArray);
echo "Is 'Apple' in indexedArray? " . ($inArray ? "Yes" : "No") . "\n";
// array_search
$searchIndex = array_search("Banana", $indexedArray);
echo "Index of 'Banana' in indexedArray: " . $searchIndex . "\n";
?>
</pre>
<h2>File Handling</h2>
<pre>
<?php
// File Handling
$filename = "example.txt";
$fileContent = "Hello, this is a sample text file.";
// Write to a file using fopen, fwrite, and fclose
$file = fopen($filename, "w");
if ($file) {
fwrite($file, $fileContent);
fclose($file);
echo "File written successfully.\n";
} else {
echo "Unable to open file for writing.\n";
}
// Read from a file using fopen, fread, and fclose
$file = fopen($filename, "r");
if ($file) {
$content = fread($file, filesize($filename));
fclose($file);
echo "Content of the file:\n" . $content . "\n";
} else {
echo "Unable to open file for reading.\n";
}
// Append to a file using fopen, fwrite, and fclose
$file = fopen($filename, "a");
if ($file) {
fwrite($file, "\nThis is an appended line.");
fclose($file);
echo "Content after appending:\n" . file_get_contents($filename) . "\
n";
} else {
echo "Unable to open file for appending.\n";
}
// Delete a file
if (file_exists($filename)) {
unlink($filename);
echo "File deleted successfully.\n";
} else {
echo "File does not exist.\n";
}
?>
</pre>
You might also like
Osc - Experiment - 6
PDF
No ratings yet
Osc - Experiment - 6
11 pages
ASSIGNMENT-11PHP
PDF
No ratings yet
ASSIGNMENT-11PHP
10 pages
php
PDF
No ratings yet
php
11 pages
10000
PDF
No ratings yet
10000
11 pages
Database
PDF
No ratings yet
Database
8 pages
PHP
PDF
No ratings yet
PHP
4 pages
Print
PDF
No ratings yet
Print
11 pages
Sample Code
PDF
No ratings yet
Sample Code
10 pages
Exercise-8 IWP 18BCE0557 Kushal: 1) DB Creation Code
PDF
No ratings yet
Exercise-8 IWP 18BCE0557 Kushal: 1) DB Creation Code
10 pages
Practical12&13
PDF
No ratings yet
Practical12&13
16 pages
php lab program
PDF
No ratings yet
php lab program
22 pages
Sign in
PDF
No ratings yet
Sign in
14 pages
Register Page Code
PDF
100% (1)
Register Page Code
4 pages
Ayan Tiwari ROLL NO-58072 BSC Hons Computer Science 2 Year
PDF
No ratings yet
Ayan Tiwari ROLL NO-58072 BSC Hons Computer Science 2 Year
7 pages
Ushtrimet PAW
PDF
No ratings yet
Ushtrimet PAW
9 pages
Php Mysql Login System
PDF
No ratings yet
Php Mysql Login System
17 pages
PHP 3
PDF
No ratings yet
PHP 3
6 pages
Login and Logout
PDF
No ratings yet
Login and Logout
11 pages
Cookies
PDF
No ratings yet
Cookies
9 pages
Regular Expression
PDF
No ratings yet
Regular Expression
6 pages
Web Programming Assignment-4
PDF
No ratings yet
Web Programming Assignment-4
4 pages
PHP File
PDF
No ratings yet
PHP File
25 pages
Lalaineretardophpsamplecode
PDF
No ratings yet
Lalaineretardophpsamplecode
7 pages
PBT2 Web Programming (F2022, F2026)
PDF
No ratings yet
PBT2 Web Programming (F2022, F2026)
19 pages
22MIS7236 IWT Assignment -3
PDF
No ratings yet
22MIS7236 IWT Assignment -3
14 pages
script programming
PDF
No ratings yet
script programming
19 pages
Login Xampp
PDF
No ratings yet
Login Xampp
4 pages
Using PHP and MySQL in Android To Manage Records
PDF
No ratings yet
Using PHP and MySQL in Android To Manage Records
38 pages
P Do Tutorial
PDF
No ratings yet
P Do Tutorial
25 pages
Class & Homework Solutions: 1. Webapp1: Login App, Storing Credentials in Array Webapp1.html
PDF
No ratings yet
Class & Homework Solutions: 1. Webapp1: Login App, Storing Credentials in Array Webapp1.html
16 pages
Login System
PDF
No ratings yet
Login System
61 pages
Dbms Exp10 Miniproject
PDF
No ratings yet
Dbms Exp10 Miniproject
9 pages
Source Code:: Admin Login Form
PDF
No ratings yet
Source Code:: Admin Login Form
19 pages
Register PHP
PDF
No ratings yet
Register PHP
4 pages
lab9
PDF
No ratings yet
lab9
13 pages
Creating A Simple PHP and MySQL-Based Login System
PDF
No ratings yet
Creating A Simple PHP and MySQL-Based Login System
14 pages
Build A Full Featured Login System With PHP
PDF
No ratings yet
Build A Full Featured Login System With PHP
31 pages
Login
PDF
No ratings yet
Login
2 pages
User PHP
PDF
No ratings yet
User PHP
2 pages
Advanced Web Development
PDF
No ratings yet
Advanced Web Development
15 pages
Create Registration / Sign Up Form Using PHP and Mysql
PDF
No ratings yet
Create Registration / Sign Up Form Using PHP and Mysql
6 pages
yashwd
PDF
No ratings yet
yashwd
26 pages
Database Login Form Task Rutuja Shejul
PDF
No ratings yet
Database Login Form Task Rutuja Shejul
7 pages
Activity 1 Information Assurance and Security 2
PDF
No ratings yet
Activity 1 Information Assurance and Security 2
7 pages
2024
PDF
No ratings yet
2024
5 pages
php
PDF
No ratings yet
php
12 pages
IM Review
PDF
No ratings yet
IM Review
6 pages
Tugas 1
PDF
No ratings yet
Tugas 1
10 pages
Web Solve Papers (2014 To 2020 Coding Questions)
PDF
No ratings yet
Web Solve Papers (2014 To 2020 Coding Questions)
15 pages
mooyaa
PDF
No ratings yet
mooyaa
2 pages
Dbfunctions
PDF
No ratings yet
Dbfunctions
1 page
PHP (Run On XAMPP Server) Two Files 1 Insert - HTML 2 Index - PHP
PDF
No ratings yet
PHP (Run On XAMPP Server) Two Files 1 Insert - HTML 2 Index - PHP
3 pages
5 Easy Steps To Create Simple & Secure PHP Login Script
PDF
No ratings yet
5 Easy Steps To Create Simple & Secure PHP Login Script
22 pages
Page 0 Home Page
PDF
No ratings yet
Page 0 Home Page
3 pages
Ex 11
PDF
No ratings yet
Ex 11
4 pages
Microproject php
PDF
No ratings yet
Microproject php
5 pages
Serverside Paper
PDF
No ratings yet
Serverside Paper
9 pages
Admin and User Login in PHP and Mysql Database
PDF
100% (1)
Admin and User Login in PHP and Mysql Database
13 pages
Login
PDF
No ratings yet
Login
3 pages
150+ C Pattern Programs
From Everand
150+ C Pattern Programs
Hernando Abella
No ratings yet
(InfoAcademy) CyberOpsAssociate-Sedinta13
PDF
No ratings yet
(InfoAcademy) CyberOpsAssociate-Sedinta13
34 pages
Big Data For Dummies
PDF
No ratings yet
Big Data For Dummies
8 pages
New Application /change Request Format: Schematic Flow
PDF
No ratings yet
New Application /change Request Format: Schematic Flow
4 pages
Output
PDF
No ratings yet
Output
22 pages
Ableton File Management
PDF
No ratings yet
Ableton File Management
3 pages
02 Exchange Profile
PDF
No ratings yet
02 Exchange Profile
16 pages
Ball Tree
PDF
No ratings yet
Ball Tree
4 pages
Left Outer Join and Right Outer Join Practice Problems
PDF
No ratings yet
Left Outer Join and Right Outer Join Practice Problems
2 pages
Pengantar Basis Data
PDF
No ratings yet
Pengantar Basis Data
21 pages
DBMS Lab Manual PDF
PDF
80% (10)
DBMS Lab Manual PDF
40 pages
Assignment 5
PDF
No ratings yet
Assignment 5
9 pages
To Help Overcome The Communication Problem Between Users and Developers. Diagrams
PDF
No ratings yet
To Help Overcome The Communication Problem Between Users and Developers. Diagrams
19 pages
Data Science Brochure
PDF
No ratings yet
Data Science Brochure
16 pages
Pandas_Notes
PDF
No ratings yet
Pandas_Notes
6 pages
Visvesvaraya Technological University: K.S.Institute of Technology
PDF
No ratings yet
Visvesvaraya Technological University: K.S.Institute of Technology
38 pages
ASREC (Gramshakti) - Daily MIS Report
PDF
No ratings yet
ASREC (Gramshakti) - Daily MIS Report
25 pages
DBWorksheet Update
PDF
No ratings yet
DBWorksheet Update
34 pages
SQL Practice Problems: Mysql Version
PDF
No ratings yet
SQL Practice Problems: Mysql Version
99 pages
Hadoop Installation
PDF
No ratings yet
Hadoop Installation
7 pages
NODE JS Lab Manual Part1
PDF
No ratings yet
NODE JS Lab Manual Part1
41 pages
சித்தர் நூல்கள் மொத்தம் 15
PDF
No ratings yet
சித்தர் நூல்கள் மொத்தம் 15
945 pages
Bit 4101 Business Data Minning and Warehousing
PDF
No ratings yet
Bit 4101 Business Data Minning and Warehousing
11 pages
Disk Usage by Top Tables
PDF
No ratings yet
Disk Usage by Top Tables
16 pages
DBMS Unit-2 Notes
PDF
No ratings yet
DBMS Unit-2 Notes
43 pages
Da Notes - 2019
PDF
No ratings yet
Da Notes - 2019
201 pages
Cloudpersentation
PDF
No ratings yet
Cloudpersentation
16 pages
Azure Storage
PDF
No ratings yet
Azure Storage
15 pages
Logs and Data Purge
PDF
No ratings yet
Logs and Data Purge
5 pages
T24 - Local Fields
PDF
100% (3)
T24 - Local Fields
16 pages
Dimensional Data Modeling Day 1
PDF
No ratings yet
Dimensional Data Modeling Day 1
19 pages