0% found this document useful (0 votes)
5 views3 pages

PHP Programming Examples and Tutorials

The document provides several examples of PHP programs, including a foreach loop, form validation, file upload, session creation, and cookie management. Each example is accompanied by HTML code demonstrating its functionality. Additionally, there is a mention of JSP at the end, but no details are provided.

Uploaded by

Srinivas Boini
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)
5 views3 pages

PHP Programming Examples and Tutorials

The document provides several examples of PHP programs, including a foreach loop, form validation, file upload, session creation, and cookie management. Each example is accompanied by HTML code demonstrating its functionality. Additionally, there is a mention of JSP at the end, but no details are provided.

Uploaded by

Srinivas Boini
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

1.

PHP for each loop example program

<html>
<body>

<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}

$myCar = new Car("red", "Volvo");

foreach ($myCar as $x => $y) {


echo "$x: $y<br>";
}
?>

</body>
</html>

2. Php form validation program

<html><body>
<form action="[Link]" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br><input
type="submit"></form>
</body><
/html>

[Link] program

<html><body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>
</body></html>

3. Php file upload program

<html>
<body>

<form action="[Link]" method="post"


enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

[Link]

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]
["name"]);
$uploadOk = 1;
$imageFileType =
strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>

4. php program for creating session.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

5. Php proram creating Cookie


<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
// 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

6. JSP

Common questions

Powered by AI

The foreach loop in PHP can iterate over an object's properties by accessing them as key-value pairs, where the key is the property name and the value is the property value. However, only public properties are accessible through this iteration. Private or protected properties will not be iterated unless within a class method that has the appropriate access rights. Thus, its limitation lies in its inability to access non-public properties directly .

PHP cookies store user information on the client side. They are set with setcookie() specifying the name, value, expiry, and path. Once set, they can be accessed as elements of the $_COOKIE superglobal. However, cookies can be a security concern due to potential vulnerabilities like XSS attacks if user input is not properly sanitized, allowing attackers to read or write cookies. Additionally, cookies can be intercepted if transmitted over unsecured connections .

JSP offers benefits such as robust integration with Java's ecosystem, making it suitable for applications requiring intensive computations or enterprise-level solutions. It supports easy use of Java libraries and tools, enhancing scalability. However, JSP setups can be more resource-intensive and complex than PHP. PHP, being simpler and widely supported, excels in script execution for server-side web development with less overhead and is highly accessible for small to medium applications .

The PHP session management program demonstrates persistence by storing data server-side using session variables. When a session is started with session_start(), data such as 'favcolor' and 'favanimal' is saved in the $_SESSION superglobal. This data remains accessible on subsequent pages during the session lifetime unless the session is destroyed or expires. This ensures user preferences are consistently available as the user navigates a site .

PHP sessions can store user preferences by creating session variables that persist across multiple web pages. By calling session_start(), a session is initialized. You can then set preferences like favorite color or animal as session variables (e.g., $_SESSION['favcolor']). These variables are stored on the server and are accessible on other pages within the session, allowing for a consistent user experience .

The PHP program for file upload involves several key steps. First, an HTML form is used to select a file to upload. The form submits to upload.php with ENCTYPE set to multipart/form-data. In upload.php, the target directory is set, and the target file path is constructed. A check is performed using getimagesize() to verify whether the uploaded file is a real image. If it's a valid image, the uploadOk flag remains 1, and a message confirming the image type is displayed. If not, uploadOk is set to 0, cancelling the upload .

The constructor in the PHP class example is used to initialize a new object of the Car class. It accepts parameters for color and model and assigns them to the class properties $color and $model, respectively. When a Car object is instantiated using new Car('red', 'Volvo'), the constructor is called and these values are set for that specific object instance .

Enhancing security in PHP file upload systems involves several strategies beyond basic image validation. Using a whitelist to specify acceptable file types and sizes, configuring proper directory permissions to protect server files, renaming files to prevent script execution, and thoroughly escaping any file metadata are critical measures. Additionally, ensuring files are handled in a secured HTTPS environment and using security tools like antivirus scanners to detect malicious files further enhances security .

The PHP form validation program takes user input from a form that requests a name and email. It sends this input via POST method to a PHP file, welcome.php, which processes the data. The welcome.php script retrieves the 'name' and 'email' values from the $_POST superglobal array and displays them using echo statements, effectively showing the username and email address input by the user .

Checking both the MIME type and file extension is crucial because relying solely on one can leave the system vulnerable to attacks. MIME type verification ensures the file content is as expected, while extension checks pertain to file handling on the server. If neglected, malicious scripts could be uploaded disguised as harmless files, potentially leading to server exploits or data breaches. Comprehensive validation closes off these security loopholes .

You might also like