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)
11 views
7 pages
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)
11 views
7 pages
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
Download
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
Autocratic-Democratic Leadership Style Questionnaire PDF
PDF
100% (5)
Autocratic-Democratic Leadership Style Questionnaire PDF
6 pages
Grade 1 CA January 2024 Final
PDF
100% (1)
Grade 1 CA January 2024 Final
58 pages
Handbook Logistics FRC - PIRAC
PDF
No ratings yet
Handbook Logistics FRC - PIRAC
44 pages
Understanding Bird Behaviour
PDF
100% (5)
Understanding Bird Behaviour
226 pages
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
Q
PDF
No ratings yet
Q
6 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
Cheatsheeet Web
PDF
No ratings yet
Cheatsheeet Web
6 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
Coding
PDF
No ratings yet
Coding
24 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
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
JERIN_ANSWERSHEET
PDF
No ratings yet
JERIN_ANSWERSHEET
4 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
Database Login Form Task Rutuja Shejul
PDF
No ratings yet
Database Login Form Task Rutuja Shejul
7 pages
yashwd
PDF
No ratings yet
yashwd
26 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
Web Solve Papers (2014 To 2020 Coding Questions)
PDF
No ratings yet
Web Solve Papers (2014 To 2020 Coding Questions)
15 pages
Tugas 1
PDF
No ratings yet
Tugas 1
10 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
Serverside Paper
PDF
No ratings yet
Serverside Paper
9 pages
150+ C Pattern Programs
From Everand
150+ C Pattern Programs
Hernando Abella
No ratings yet
Birla Institute of Technology and Science, Pilani Bitsat 2020: Hall Ticket
PDF
No ratings yet
Birla Institute of Technology and Science, Pilani Bitsat 2020: Hall Ticket
2 pages
Components of Network
PDF
No ratings yet
Components of Network
2 pages
Shivam S Genpact.......
PDF
No ratings yet
Shivam S Genpact.......
7 pages
Prinsip Epidemiologi Penyakit Menular
PDF
No ratings yet
Prinsip Epidemiologi Penyakit Menular
50 pages
Lesson 10 Gerunds
PDF
No ratings yet
Lesson 10 Gerunds
8 pages
Volume 2 Nomor 2, Desember 2019 E-ISSN: 2655-7347: Keywords: Defect, Compensation, Gojek, Negligence, Shipment
PDF
No ratings yet
Volume 2 Nomor 2, Desember 2019 E-ISSN: 2655-7347: Keywords: Defect, Compensation, Gojek, Negligence, Shipment
17 pages
Cinefantastique v09n01 (1979)
PDF
100% (1)
Cinefantastique v09n01 (1979)
48 pages
(Translated Texts for Historians, 42) Magnus Aurelius Cassiodorus Senator, Mark Vessey, James W. Halporn (Transl.) - Institutions of Divine and Secular Learning and on the Soul-Liverpool University Pr
PDF
No ratings yet
(Translated Texts for Historians, 42) Magnus Aurelius Cassiodorus Senator, Mark Vessey, James W. Halporn (Transl.) - Institutions of Divine and Secular Learning and on the Soul-Liverpool University Pr
328 pages
XI CBSE Project
PDF
No ratings yet
XI CBSE Project
3 pages
Ironsworn Jumpchain
PDF
No ratings yet
Ironsworn Jumpchain
16 pages
LEARNERS IN PUBLIC PRIVATE SUCsLUCs IN KINDER ELEMJHS SHS ON DIFF DISTANCE TEACHING LEARNING MODALITIES 3
PDF
No ratings yet
LEARNERS IN PUBLIC PRIVATE SUCsLUCs IN KINDER ELEMJHS SHS ON DIFF DISTANCE TEACHING LEARNING MODALITIES 3
28 pages
John J. Reilly Center For Science, Technology, and Values
PDF
No ratings yet
John J. Reilly Center For Science, Technology, and Values
2 pages
Gantt Chart Ip-Compressed
PDF
No ratings yet
Gantt Chart Ip-Compressed
1 page
Prohibited Items List
PDF
No ratings yet
Prohibited Items List
1 page
PWX 951 CommandReference en
PDF
No ratings yet
PWX 951 CommandReference en
152 pages
Abera and Demisie Dashen Bank Internship (Adpa)
PDF
No ratings yet
Abera and Demisie Dashen Bank Internship (Adpa)
21 pages
Compliance - Coi Filter - Dec 2008 - Johny
PDF
No ratings yet
Compliance - Coi Filter - Dec 2008 - Johny
1 page
Baby Rudin Chapter 4
PDF
No ratings yet
Baby Rudin Chapter 4
5 pages
Body Parts
PDF
No ratings yet
Body Parts
7 pages
Registration Form
PDF
No ratings yet
Registration Form
3 pages
Stereo Chemistry
PDF
No ratings yet
Stereo Chemistry
17 pages
Dover Complete Title List For DistributionPDF Compressed
PDF
No ratings yet
Dover Complete Title List For DistributionPDF Compressed
67 pages
2023 - Module 1 Organic Chem
PDF
No ratings yet
2023 - Module 1 Organic Chem
8 pages
Porsche 997 Part Numbers
PDF
100% (1)
Porsche 997 Part Numbers
492 pages
Buenos Aires: Fallmeeting
PDF
No ratings yet
Buenos Aires: Fallmeeting
84 pages
Affidavit Format DIN 1 - Ravi
PDF
No ratings yet
Affidavit Format DIN 1 - Ravi
2 pages