0% found this document useful (0 votes)
372 views16 pages

PHP Lab - Iv Sem - Bca

Manual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
372 views16 pages

PHP Lab - Iv Sem - Bca

Manual
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

1. Create a basic form and add validations using javascript

Aim : To create a basic student registration form and add validations using javascript

Description :

Forms in javascript are used to collect user input and data. A form is created using html tags
and can be manipulated using javascript. Forms contain input elements such as text boxes,
radio buttons, checkboxes, drop-down lists, etc. Which allow the user to input data.

Source code :

<!Doctype html>

<html>

<head>

<title>student registration form</title>

<script>

Function validateform() {

Var name = document.forms["Registrationform"]["Name"].value;

Var email = document.forms["Registrationform"]["Email"].value;

Var phone = document.forms["Registrationform"]["Phone"].value;

// validate name

If (name === "") {

Alert("Please enter your name.");

Return false;

// validate email

Var emailregex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

If (!Emailregex.test(email)) {

Alert("Please enter a valid email address.");

Return false;
P.V.V.SANDEEP MCA 1
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

// validate phone number

Var phoneregex = /^\d{10}$/;

If (!Phoneregex.test(phone)) {

Alert("Please enter a valid 10-digit phone number.");

Return false;

</script>

</head>

<body>

<h2>student registration form</h2>

<form name="Registrationform" Onsubmit="Return validateform()">

<label for="Name">name:</label>

<input type="Text" Id="Name" Name="Name" Required><br><br>

<label for="Email">email:</label>

<input type="Email" Id="Email" Name="Email" Required><br><br>

<label for="Phone">phone:</label>

<input type="Text" Id="Phone" Name="Phone" Required><br><br>

<input type="Submit" Value="Submit">

</form>

</body>

</html>

Output :

P.V.V.SANDEEP MCA 2
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

2. Create a php program to find odd or even number from given number

Aim : To create a php program to find odd or even number from given number

Description :

The program assigns the desired number to the $number variable. It then uses the modulo
operator (%) to check if the number is divisible evenly by 2. If the result is 0, it indicates an
even number, and the program displays an appropriate message. Otherwise, it indicates an
odd number, and a different message is displayed

Source code :

<?Php

$number = 15; // replace with the desired number to check

If ($number % 2 == 0) {

Echo "$number is an even number.";

} else {

Echo "$number is an odd number.";

?>

Output :

15 is an odd number.

3. Write a php program to find maximum of three numbers

P.V.V.SANDEEP MCA 3
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

Aim: To write a php program to find maximum of three numbers

Description :

The program defines a function findmaximum() that takes three numbers as inputs. The max()
function is used to compare the three numbers and return the maximum among them.

The program then demonstrates the usage by assigning values to the $number1, $number2,
and $number3 variables. The findmaximum() function is called with these variables, and the
result is stored in the $maximum variable. Finally, the maximum number is displayed using
echo.

Source code :

<?Php

// function to find the maximum of three numbers

Function findmaximum($num1, $num2, $num3) {

Return max($num1, $num2, $num3);

// example usage

$number1 = 15;

$number2 = 27;

$number3 = 9;

$maximum = findmaximum($number1, $number2, $number3);

Echo "The maximum number among {$number1}, {$number2}, and {$number3} is:
{$maximum}";

?>

Output :

The maximum number among 15, 27, and 9 is: 27

4. Demonstrating while loop in php for accessing array elements

Aim : Demonstrating while loop in php for accessing array elements

Description :
P.V.V.SANDEEP MCA 4
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

We have an array called $fruits that contains different fruit names. We use the count()
function to determine the length of the array and store it in the $length variable.

Next, we initialize a counter variable $i with a value of 0. The while loop runs as long as the
value of $i is less than the $length. Inside the loop, we access each array element using the $i
index and display it using echo. We then increment the counter variable $i by 1 in each
iteration.

The while loop continues until $i reaches the value of $length, ensuring that we access all the
elements of the $fruits array.

Source code :

<?Php

// example array

$fruits = array("Apple", "Banana", "Orange", "Mango", "Grapes");

// get the length of the array

$length = count($fruits);

// initialize a counter variable

$i = 0;

// while loop to access array elements

While ($i < $length) {

Echo "Fruit: " . $fruits[$i] . "\n";

$i++;

?>

Output :

Fruit: Apple

Fruit: Banana

Fruit: Orange

Fruit: Mango
P.V.V.SANDEEP MCA 5
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

Fruit: Grapes

5. Demonstrating for each loop in php

Aim : To demonstrating for each loop in php

Description :

We have an array called $fruits that contains different fruit names. The foreach loop allows us
to iterate over each element of the array.

Inside the foreach loop, we assign each array element to the variable $fruit in each iteration.
We then use echo to display the current fruit using $fruit variable.

The foreach loop automatically handles the iteration over each element of the array, and the
loop continues until all elements have been processed.

Output :

<?Php

// example array

$fruits = array("Apple", "Banana", "Orange", "Mango", "Grapes");

// foreach loop to access array elements

Foreach ($fruits as $fruit) {

Echo "Fruit: " . $fruit . "\n";

?>

Output :

Fruit: Apple

Fruit: Banana

Fruit: Orange

Fruit: Mango

Fruit: Grapes

6. Write a php program to demonstrate various string functions

P.V.V.SANDEEP MCA 6
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

Aim : To write a php program to demonstrate various string functions

Description :

Strings can arrive from many sources, including user input, databases, files, and web pages.
Before you begin to work with data from an external source, you often will need to find out
more about it. Php provides many functions that enable you to acquire information about
strings.

Source code:

<?Php
$test = "Scallywag";

Print $test[0];

Print $test[2]; // indexing

If (strlen($membership) == 4) {

Print "Thank you!";

} else {

Print "Your membership number must have 4 digits<p>";

} // length of the string

$membership = "Pab7";

If (strstr($membership, "Ab")) {

Print "Thank you. Don't forget that your membership expires soon!";

} else {

Print "Thank you!";

} //substring with in a string

$membership = "Mz00xyz";

If (strpos($membership, "Mz") === 0) {

Print "Hello mz";

} //position of sub string

$test = "Scallywag";
P.V.V.SANDEEP MCA 7
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

Print substr($test,6); // prints "Wag"

Print substr($test,6,2) // prints "Wa" //part of a string


?>

Output :

Your membership number must have 4 digits

Thank you. Don't forget that your membership expires soon!

Hello

Mz

Wag

Wa

7. Write a php program to demonstrate various string functions

Aim: To write a php program to demonstrate various string functions

Description :

Php includes a lot of date and time functions. These functions are coming under php date and
time-related extensions.these are used to perform various operations with date and time, like
getting date-time information based on the input or parameters passed, performing date time
manipulation, converting date input formats from one another and more.

Getting the current date and time information.

Getting the current date in a specified format.

Calculating the timestamp of the given date.

Source code :

<?Php

$mydate=getdate(date("U"));

Echo "$mydate[weekday], $mydate[month] $mydate[mday], $mydate[year]";

?>
P.V.V.SANDEEP MCA 8
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

Output:

Wednesday, october 12, 2022.

8. Write a php program to perform read and write operations on a file

Aim : To write a php program to perform read and write operations on a file

Description :

We perform read and write operations on a file.

We specify the file path as $file_path (replace it with the actual path of your file).

We write content to the file using file_put_contents(). In this case, we write the string "This is
some content to write to the file." To the file specified by $file_path.

We read the content of the file using file_get_contents(). The content of the file is stored in
the variable $content_read.

We display the content of the file using echo.

Source code :

<?Php

// file path

$file_path = 'example.txt';

// write to file

$content_to_write = "This is some content to write to the file.\n";

File_put_contents($file_path, $content_to_write);

// read from file

$content_read = file_get_contents($file_path);

// display file content

Echo "File content:\n";

Echo $content_read;

?>

Output :
P.V.V.SANDEEP MCA 9
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

File content:

This is some content to write to the file.

9. Creating user login form in php with mysql

Aim : To creating user login form in php with mysql

Description :

In php you can easily do this using the mysqli_connect() function. All communication between
php and the mysql database server takes place through this connection. Here're the basic
syntaxes for connecting to mysql using mysqli and pdo extensions.

Mysql_connect — open a connection to a mysql server

Source code :

<?Php

// mysql database credentials

$hostname = 'localhost'; // replace with your mysql server hostname

$username = 'root'; // replace with your mysql username

$password = 'password'; // replace with your mysql password

$database = 'example_db'; // replace with your mysql database name

// establish a mysql database connection

$conn = mysqli_connect($hostname, $username, $password, $database);

// check if the connection was successful

If (!$conn) {

Die("Connection failed: " . Mysqli_connect_error());

// function to authenticate user login

Function authenticateuser($username, $password) {

Global $conn;

$username = mysqli_real_escape_string($conn, $username);


P.V.V.SANDEEP MCA 10
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

$password = mysqli_real_escape_string($conn, $password);

$query = "Select * from users where username = '$username' and password = '$password'";

$result = mysqli_query($conn, $query);

If (mysqli_num_rows($result) == 1) {

Return true; // authentication successful

} else {

Return false; // authentication failed

// example usage - form submission

If (isset($_post['submit'])) {

$username = $_post['username'];

$password = $_post['password'];

If (authenticateuser($username, $password)) {

Echo "Authentication successful! Welcome, $username.";

} else {

Echo "Authentication failed. Invalid username or password.";

?>

<!Doctype html>

<html>

<head>

<title>user login</title>

</head>

P.V.V.SANDEEP MCA 11
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

<body>

<h1>user login</h1>

<form method="Post" Action="<?Php echo $_server['php_self']; ?>">

<label for="Username">username:</label>

<input type="Text" Id="Username" Name="Username" Required><br><br>

<label for="Password">password:</label>

<input type="Password" Id="Password" Name="Password" Required><br><br>

<input type="Submit" Name="Submit" Value="Login">

</form>

</body>

</html>

Output :

Successful login

Authentication successful! Welcome, username.

Failed login

Authentication failed. Invalid username or password.

10. Demonstrating file uploads

Aim : To demonstrating file uploads

Description :

When the form is submitted (method="Post"), the php code is executed to handle the file
upload.

The code checks if the upload directory exists and creates it if necessary.

The uploaded file is accessed using the $_files superglobal.

If the file was uploaded without errors (upload_err_ok), the file name is extracted and the file
is moved from the temporary location to the target directory using move_uploaded_file().

P.V.V.SANDEEP MCA 12
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

If the file upload is successful, a success message is displayed. Otherwise, an appropriate error
message is shown.

The html form includes an input field of type "File" (name="Filetoupload") and the enctype
attribute is set to "Multipart/form-data" To enable file uploads.

Source code :

<?Php

If ($_server["Request_method"] == "Post") {

$uploaddir = "Uploads/"; // directory to store uploaded files

// check if the upload directory exists, create it if not

If (!Is_dir($uploaddir)) {

Mkdir($uploaddir);

$uploadedfile = $_files["Filetoupload"];

// check if a file was uploaded without errors

If ($uploadedfile["Error"] === upload_err_ok) {

$filename = basename($uploadedfile["Name"]);

$targetpath = $uploaddir . $filename;

// move the uploaded file to the target directory

If (move_uploaded_file($uploadedfile["Tmp_name"], $targetpath)) {

Echo "File uploaded successfully!";

} else {

Echo "Error uploading file.";

} else {

Echo "Error: " . $uploadedfile["Error"];

}
P.V.V.SANDEEP MCA 13
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

?>

<!Doctype html>

<html>

<head>

<title>file upload</title>

</head>

<body>

<h1>file upload</h1>

<form method="Post" Enctype="Multipart/form-data">

<input type="File" Name="Filetoupload" Required>

<br><br>

<input type="Submit" Value="Upload">

</form>

</body>

</html>

Output :

Successful file upload

File uploaded successfully!

Error during file upload

Error uploading file.

11. Demonstrating working with cookies

Aim : To demonstrating working with cookies

Description : A cookie is a small text file that lets you store a small amount of data (nearly 4kb)
on the user's computer. They are typically used to keeping track of information such as

P.V.V.SANDEEP MCA 14
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

username that the site can retrieve to personalize the page when user visit the website next
time.

Setting a cookie in php

The setcookie() function is used to set a cookie in php. Make sure you call
the setcookie() function before any output generated by your script otherwise cookie will not
set.

Source code :

<?Php

// set a cookie

$cookiename = "User";

$cookievalue = "John doe";

$cookieexpiration = time() + (86400 * 30); // 30 days

Setcookie($cookiename, $cookievalue, $cookieexpiration, "/");

// retrieve and display the cookie value

If (isset($_cookie[$cookiename])) {

$cookievalue = $_cookie[$cookiename];

Echo "Cookie value: " . $cookievalue;

} else {

Echo "Cookie not set.";

?>

Output :

Cookie value: John doe

12. Demonstrating user sessions

Aim : To . Demonstrating user sessions

Description :

P.V.V.SANDEEP MCA 15
PRAGATI WOMENS DEGREE COLLEGE PHP & MYSQL II BCA – IV SEM

A php session stores data on the server rather than user's computer. In a session based
environment, every user is identified through a unique number called session identifier or sid.
This unique session id is used to link each user with their own information on the server like
emails, posts, etc.

Source code :

<?Php

// start the session

Session_start();

// set session variables

$_session['username'] = 'johndoe';

$_session['role'] = 'admin';

// retrieve and display session variables

$username = $_session['username'];

$role = $_session['role'];

Echo "Username: " . $username . "<br>";

Echo "Role: " . $role;

?>

Output :

Username: Johndoe

Role: Admin

P.V.V.SANDEEP MCA 16

You might also like