0% found this document useful (0 votes)
2 views32 pages

SL lab

The document contains a series of HTML and PHP scripts that perform various tasks including greeting users, calculating factorials, checking for prime numbers, analyzing text files, appending data to files, searching for words in files, validating forms, dynamically adding rows to tables, fetching live weather data using an API, and connecting to a database to retrieve data. Each script is designed to be user-friendly and interactive, utilizing JavaScript for client-side functionality and PHP for server-side processing. The examples demonstrate practical applications of web technologies in creating dynamic web applications.

Uploaded by

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

SL lab

The document contains a series of HTML and PHP scripts that perform various tasks including greeting users, calculating factorials, checking for prime numbers, analyzing text files, appending data to files, searching for words in files, validating forms, dynamically adding rows to tables, fetching live weather data using an API, and connecting to a database to retrieve data. Each script is designed to be user-friendly and interactive, utilizing JavaScript for client-side functionality and PHP for server-side processing. The examples demonstrate practical applications of web technologies in creating dynamic web applications.

Uploaded by

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

1.

Write a script to take user input and display a greeting message with their name
=>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Greeting App</title>
</head>
<body>
<h2>Enter your name:</h2>
<input type="text" id="nameInput" placeholder="Your name">
<button onclick="greetUser()">Greet</button>
<p id="greetingMessage"></p>
<script>
function greetUser() {
const name = document.getElementById("nameInput").value;
document.getElementById("greetingMessage").innerText = `Hello, ${name}!
Welcome!`;
}
</script>
</body>
</html>
2. Create a script that calculates the factorial of a given number.
=>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Calculator</title>
</head>
<body>
<h2>Enter a number:</h2>
<input type="number" id="numberInput" placeholder="Enter a number">
<button onclick="calculateFactorial()">Calculate Factorial</button>
<p id="result"></p>
<script>
function calculateFactorial() {
const num = parseInt(document.getElementById("numberInput").value);
if (isNaN(num) || num < 0) {
document.getElementById("result").innerText = "Please enter a non-negative
integer.";
return;
}
let factorial = 1;
for (let i = 2; i <= num; i++) {
factorial *= i;
}
document.getElementById("result").innerText = `Factorial of ${num} is $
{factorial}`;
}
</script>
</body>
</html>
3. Write a script to check whether a number is prime or not.
=>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prime Number Checker</title>
</head>
<body>
<h2>Enter a number:</h2>
<input type="number" id="numberInput" placeholder="Enter a number">
<button onclick="checkPrime()">Check Prime</button>
<p id="result"></p>

<script>
function checkPrime() {
const num = parseInt(document.getElementById("numberInput").value);
if (isNaN(num) || num < 2) {
document.getElementById("result").innerText = "Please enter an integer greater
than 1.";
return;
}
let isPrime = true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
isPrime = false;
break;
}
}
document.getElementById("result").innerText = isPrime ? `${num} is a prime
number.` : `${num} is not a prime number.`;
}
</script>
</body>
</html>
4. Write a script to read a text file and count the number of words, lines, and characters
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Analyzer</title>
</head>
<body>
<h2>Upload a text file:</h2>
<form action="Qno4.php" method="post" enctype="multipart/form-data">
<input type="file" name="textFile" accept=".txt">
<button type="submit">Analyze File</button>
</form>
</body>
</html>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["textFile"])) {
$file = $_FILES["textFile"]["tmp_name"];
if (file_exists($file)) {
$content = file_get_contents($file);
$lines = explode("\n", $content);
$numLines = count($lines);
$numWords = str_word_count($content);
$numChars = strlen($content);
echo "<h2>File Analysis Result:</h2>";
echo "<p>Lines: $numLines</p>";
echo "<p>Words: $numWords</p>";
echo "<p>Characters: $numChars</p>";
} else {
echo "<p>Error: Unable to read the file.</p>";
}
}
?>
5. Create a script to append user-provided data to an existing file .
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Editor</title>
</head>
<body>
<h2>Upload a text file to append data:</h2>
<form action="Qno5.php" method="post" enctype="multipart/form-data">
<input type="file" name="textFile" accept=".txt">
<br><br>
<textarea name="appendText" rows="4" cols="50" placeholder="Enter text to
append..."></textarea>
<br><br>
<button type="submit">Append to File</button>
</form>
</body>
</html>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["textFile"]) &&
isset($_POST["appendText"])) {
$file = $_FILES["textFile"]["tmp_name"];
$appendText = $_POST["appendText"];

if (file_exists($file)) {
file_put_contents($file, "\n" . $appendText, FILE_APPEND);
echo "<h2>File Update Result:</h2>";
echo "<p>Text has been successfully appended to the file.</p>";
} else {
echo "<p>Error: Unable to open the file.</p>";
}
}
?>
6. Develop a script that searches for a specific word in a file and prints the line numbers
where it appears.
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Search</title>
</head>
<body>
<h2>Upload a text file to search for a word:</h2>
<form action="Qno6.php" method="post" enctype="multipart/form-data">
<input type="file" name="textFile" accept=".txt">
<br><br>
<input type="text" name="searchWord" placeholder="Enter word to search">
<br><br>
<button type="submit">Search</button>
</form>
</body>
</html>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["textFile"]) &&
isset($_POST["searchWord"])) {
$file = $_FILES["textFile"]["tmp_name"];
$searchWord = $_POST["searchWord"];

if (file_exists($file)) {
$lines = file($file);
$lineNumbers = [];

foreach ($lines as $lineNumber => $line) {


if (strpos($line, $searchWord) !== false) {
$lineNumbers[] = $lineNumber + 1;
}
}

echo "<h2>Search Results:</h2>";


if (!empty($lineNumbers)) {
echo "<p>Word found on line(s): " . implode(", ", $lineNumbers) . "</p>";
} else {
echo "<p>Word not found in the file.</p>";
}
} else {
echo "<p>Error: Unable to open the file.</p>";
}
}
?>
7. Write a client-side script that validates a simple HTML form with fields like
name ,email, and password.
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<script>
function validateForm() {
let name = document.forms["myForm"]["name"].value;
let email = document.forms["myForm"]["email"].value;
let password = document.forms["myForm"]["password"].value;
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (name == "") {
alert("Name must be filled out");
return false;
}
if (!emailPattern.test(email)) {
alert("Invalid email format");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long");
return false;
}
return true;
}
</script>
</head>
<body>
<h2>Simple Form</h2>
<form name="myForm" action="Qno7.php" method="post" onsubmit="return
validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
if (!empty($name) && filter_var($email, FILTER_VALIDATE_EMAIL) &&
strlen($password) >= 6) {
echo "<h2>Form Submitted Successfully!</h2>";
} else {
echo "<p>Error: Invalid form data.</p>";
}
}
?>
8. Create a script to dynamically add rows to an HTML table using JavaScript.
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Table</title>
<script>
function addRow() {
let table = document.getElementById("dataTable");
let row = table.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);

cell1.innerHTML = document.getElementById("name").value;
cell2.innerHTML = document.getElementById("email").value;
cell3.innerHTML = document.getElementById("password").value;
}
</script>
</head>
<body>
<h2>Simple Form</h2>
<form name="myForm" onsubmit="addRow(); return false;">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email"><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>

<button type="submit">Add Row</button>


</form>

<h2>Data Table</h2>
<table border="1" id="dataTable">
<tr>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>
</table>
</body>
</html>
9. Write a script to fetch and display live weather data using a free API(e.g., OpenWeather
API). (Implement with help of AJAX).
=>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Live Weather Data</title>

<style>

body {

font-family: Arial, sans-serif;

padding: 20px;

#weather {

margin-top: 20px;

.hidden {

display: none;

</style>

</head>

<body>

<h1>Live Weather Data</h1>

<div>

<label for="city">Enter City: </label>


<input type="text" id="city" placeholder="City name">

<button onclick="getWeather()">Get Weather</button>

</div>

<div id="weather" class="hidden">

<h3>Weather Information:</h3>

<p id="cityName"></p>

<p id="temp"></p>

<p id="description"></p>

<p id="humidity"></p>

</div>

<script>

function getWeather() {

var city = document.getElementById('city').value;

var apiKey = '1c756e43cd59d612ed38078e6d82e2bc'; // Replace with your OpenWeather


API key

if (city !== '') {

var xhr = new XMLHttpRequest();

var url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=$


{apiKey}&units=metric`;

// Log the URL to ensure it's being formed correctly

console.log(url);

xhr.open('GET', url, true);

xhr.onreadystatechange = function() {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

var data = JSON.parse(xhr.responseText);


console.log(data); // Log the response data to the console

displayWeather(data);

} else {

// Log the error details to the console

console.error("Error fetching data: ", xhr.status, xhr.statusText);

alert('City not found or there was an issue with the API request');

};

xhr.send();

} else {

alert('Please enter a city name');

function displayWeather(data) {

if (data.cod === 200) {

document.getElementById('weather').classList.remove('hidden');

document.getElementById('cityName').innerText = `City: ${data.name}`;

document.getElementById('temp').innerText = `Temperature: ${data.main.temp}°C`;

document.getElementById('description').innerText = `Weather: $
{data.weather[0].description}`;

document.getElementById('humidity').innerText = `Humidity: ${data.main.humidity}%`;

} else {

alert('City not found');

}
}

</script>

</body>

</html>

10. Write a PHP script to connect to a database and retrieve data from a table.
=><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Database Data</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>

<h1>Database Data</h1>

<?php
// Database connection parameters
$servername = "localhost"; // Database server (usually 'localhost')
$username = "root"; // Database username (default is 'root' for XAMPP/MAMP)
$password = ""; // Database password (leave blank for XAMPP/MAMP default)
$dbname = "jspractical"; // Name of your database

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// SQL query to select data from the table


$sql = "SELECT j_id, name, email FROM js_table"; // Adjust 'users' to your table name
$result = $conn->query($sql);

// Check if data is returned


if ($result->num_rows > 0) {
// Output data in a table
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";

while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["j_id"] . "</td><td>" . $row["name"] . "</td><td>" .
$row["email"] . "</td></tr>";
}

echo "</table>";
} else {
echo "0 results";
}

// Close the connection


$conn->close();
?>

</body>
</html>

11. Create a simple login system using PHP and validate credentials from a database.
=><?php
session_start();

// Check if the user is already logged in


if (isset($_SESSION['username'])) {
echo "<p>Welcome, " . $_SESSION['username'] . "!</p>";
echo "<a href='logout.php'>Logout</a>";
exit;
}

// Check if the login form was submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$password = $_POST['password'];

// Database connection details


$servername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "jspractical";

// Create connection
$conn = new mysqli($servername, $dbUsername, $dbPassword, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Query to check the user in the database


$sql = "SELECT * FROM js_table WHERE name = ? AND password = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name,$password); // Password is hashed using MD5 (for
simplicity in this example)
$stmt->execute();
$result = $stmt->get_result();

// Check if the user exists


if ($result->num_rows > 0) {
// Start a session and store the username
$_SESSION['name'] = $name;
// header("Location: welcome.php"); // Redirect to a welcome page
echo "<p style='color:blue;'>Login successful</p>";
exit;
} else {
echo "<p style='color:red;'>Invalid username or password</p>";
}

// Close connection
$conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login System</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="Qno11.php">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>

<label for="password">Password</label>
<input type="password" id="password" name="password" required>

<input type="submit" value="Login">


</form>

</body>
</html>
12. Develop a PHP script to process an HTML form and store the data in a MySQL database.
=>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['name'];
$password = $_POST['password'];
$email = $_POST['email'];

try {
$connection = mysqli_connect('localhost', 'root', '', 'jspractical');
$sql = "INSERT INTO js_table (name, password, email) VALUES ('$name', '$password',
'$email')";
$connection->query($sql);
if ($connection->affected_rows == 1) {
echo"Registration successful!"; // Set success message
exit();
} else {
$errorMessage = "Insert failed"; // Set failure message
}
} catch (Exception $e) {
$errorMessage = 'Connection Error: ' . $e->getMessage();
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>

<form method="post" action="Qno12.php">


<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="Enter name" required />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Enter password"
required />
</div>
<div>
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Enter email" required />
</div>
<div>
<button type="submit" name="register">Register</button>
</div>
</form>
</body></html>
14. Investigate the role of scripting languages in modern web development and how they
differ from traditional programming languages.
=>
Scripting languages are essential in modern web development, enabling dynamic, interactive
websites. They are typically interpreted, allowing for flexibility and rapid development. For
example, JavaScript handles client-side interactivity, while server-side languages like PHP
and Node.js generate dynamic content and interact with databases.
Differences from Traditional Programming Languages:
1. Execution: Scripting languages are interpreted at runtime, while traditional languages are
compiled into machine code before execution.
2. Use Cases: Scripting languages excel in web development and automation, whereas
traditional languages are used for performance-critical applications.
3. Performance: Scripting languages are slower but more flexible, while compiled
languages offer better performance.
4. Development Speed: Scripting languages allow faster development, while traditional
languages have longer development cycles.
5. Flexibility: Scripting languages are more flexible for quick changes, whereas traditional
languages provide more control over system-level tasks.
In web development, scripting languages are favored for their ease and speed, while
traditional languages are used when performance and low-level access are necessary.

15. 15. Explore the evolution of scripting languages and their impact on software
development practices.
=>
The evolution of scripting languages has significantly impacted software development
practices by enabling faster, more flexible, and efficient workflows.
Key Milestones:
 1960s-1980s: Early scripting languages like Shell scripts and Perl automated system
tasks, increasing efficiency for administrators.
 1990s: JavaScript enabled dynamic, interactive websites, while PHP and Perl powered
server-side scripting for dynamic content.
 2000s: Python and Ruby simplified web development, with frameworks like Rails and
Django speeding up app creation.
 2010s-Present: Node.js enabled full-stack JavaScript, while modern front-end
frameworks like React and Angular made UI development more efficient.
Impact on Software Development:
1. Increased Productivity: Simple syntax and rapid coding boost developer efficiency.
2. Faster Prototyping: Quick iterations allow for faster testing and development.
3. Improved Collaboration: Common tools and languages streamline team efforts across
front-end and back-end development.
4. Automation: Scripting is crucial for DevOps, testing, and deployment automation.
5. Cross-Platform Development: Scripting languages enable applications to run across
various platforms.
Scripting languages have evolved to dominate modern development, driving innovation,
rapid prototyping, and improved collaboration in software creation.

You might also like