×


18. 07. 28
posted by: Anjali
Hits: 4127

PHP Reading from Directories

Write a program in PHP to read from directory.

Solution

Let's implement a script to allow directory browsing of the uploaded content. Browsing directories is actually straightforward in PHP.

The following script can be used for this purpose -

<html>
<head>
<title>A divison table in PHP</title>
</head>
<body>
<?php
$current_dir = '/uploads/';
$dir = opendir($current_dir);

echo '<p>Upload directory is $current_dir</p/>';
echo '<p>Directory Listing:</p>';
echo '<ul>';
while($file = readdir($dir))
{
echo "<li>".$file."</li>"
}
echo '</ul>';
closedir($dir);
?>
</body>
</html>

The PHP function opendir() opens a directory handle. It takes directory path as parameter that to be opened. The readdir() function read from directory handle. The entries are returned in the order in which they are stored by the filesystem. The closedir() function is used to close a directory handle that is opened by the opendir() function.





Related Articles

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP MYSQL Advanced Search Feature PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Insert image in database




18. 06. 20
posted by: Anjali
Hits: 6540

PHP set session on login

Write a program to set session on successful login.

Solution

As we know HTTP is a stateless protocol, when a user requests one page, followed by another, HTTP does not provide a way for you to tell that both requests came from the same user. The idea of session control is to be able to track a user during a single session on a website.

First, we create a form with a text field called name and a submit button. Then, we Set the method to post and action to submit.php. The form looks like this-


<form name="form" method="post" action="submit.php">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>

Create an another page 'submit.php' and insert the following code -

<?php
// initiate session
session_start();
// check that form has been submitted and that name is not empty
if ($_POST && !empty($_POST['name'])) {
// set session variable
$_SESSION['name'] = $_POST['name'];
}
?>
<html>
<head>
<title>Set Session</title>
</head>
<body>
<?php
// check session variable is set
if (isset($_SESSION['name'])) {
// if set, greet by name
echo 'Hi, '.$_SESSION['name'];
echo 'Welcome to this page.';
}
else {
// if not set, send back to login
echo 'Please <a href="form.php">Login</a>';
}
?>
</body>
</html>

In the above example, If $_SESSION['name'] has been set, a welcome message is displayed. Otherwise, the page tells the visitor that it doesn’t recognize the user, and provides a link to login from the first page.





Related Articles

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




18. 06. 18
posted by: Anjali
Hits: 1854

PHP move uploaded file to safety location

Write a program to move the uploaded file to safety location

Solution

When a user uploads a file to a PHP script using the <input type="file" /> HTML element, PHP stores the file in a temporary location and deletes it upon completion of the script execution. Therefore, you have to access the uploaded file within the script. To do so, PHP contains the function move_uploaded_file(), which moves a file from one location to another. The great thing about move_uploaded_file() is that the function first does a sanity check, whether the filename you provide really is an uploaded file or if a malicious user just tried to trick you into moving /etc/passwd or c:\boot.ini somewhere else.

<?php
if(isset($_POST['submit']) &&  isset($_FILES['file'])) {
	$move = move_uploaded_file($_FILES['File']['tmp_name'],
	'/tmp/' . basename($_FILES['File']['name']));
	echo ($move) ? 'File moved' : 'File failed to move';
} else {
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"
	method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
}
?>

Suppose the path /tmp exists and is writable by the web server and the PHP process. Then, the preceding code moves the uploaded file to this directory, using its original filename (and you do not care whether the filename already exists).





Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




18. 06. 18
posted by: Anjali
Hits: 8623

PHP differentiate between fgets, fgetss and fgetcsv

fgets() function

fgets() function reads one line at a time from a file. It reads until it encounters a new line character (\n) or EOF. The maximum length read is the length specified minus 1 byte.

You can use many different functions to read from files. The fgets() function, for example, is useful when you are dealing with a files that contain plain text that you want to deal with in chunks.

string fgets ( resource $handle [, int $length ] )

Example

<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($file);
?>


fgetss() function

An interesting variation on fgets() is fgetss(), which has the following syntax -

string fgetss(resource fp, int length, string [allowble_tags])

The function is similar to fgets() except that it strips out any PHP and HTML tags found in string. If you want to leave in any particular tags, you can add them in the allowable_tags string. You would use fgetss() for safety when reading a file written by someone else or containing user input.


Example

<?php
$file = fopen("test.txt","r");
echo fgetss($file);
fclose($file);
?>



fgetcsv() function

The function fgetcsv() is another variation on fgets(). It has the following prototype.

array fgetcsv(resource fp, int length [, string  delimiter [, string enclosure]])

The function breaks up lines of files when you have used a delimiting character, such as the tab character or a comma. If you want to reconstruct the variable from the order separately rather than as a line of text, fgetcsv() allows you to do this simply.


Example

<?php
$file = fopen("test.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>





Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Insert image in database




18. 06. 18
posted by: Anjali
Hits: 6781

PHP convert string into an array

Write a program to convert the given string into an array.

Suppose the string is -

$a = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';

Solution

Sometimes, arrays are not used to store information; instead, a string is used. The single values are all within the string, but are separated by a special character.

The following example convert string into array -

<?php
$csvdata = 'Burch Jr, Philip H., The American establishment, Research in political economy 6(1983), 83-156';
$a = explode(',', $csvdata);
$info = print_r($a, true);
echo "<pre>$info</pre>";
?>

The PHP function explode() creates an array out of these values, you just have to provide the character(s) at which the string needs to be split.

Output of the above code -

Array
(
    [0] => Burch Jr
    [1] =>  Philip H.
    [2] =>  The American establishment
    [3] =>  Research in political economy 6 (1983)
    [4] =>  83-156
)




Related PHP Programs for Practice

PHP - Division table program
PHP - Prime Number Program
PHP - Print numbers 10 to 1 using recursion
PHP - Loop through an associative array
PHP - Differentiate between fgets, fgetss and fgetcsv
PHP - Set session on login
PHP - Convert text to speech
PHP - Copying or moving a file
PHP - Locking a file
PHP - CURL Cookie Jar
PHP - Password Hashing
PHP - Emoji Unicode Characters
PHP - Age calculator
PHP - Get array key
PHP - Capitalize first letter
PHP - Set Timezone
PHP - Remove duplicates from array
PHP - Calculate percentage of total
PHP - Fibonacci Series Program
PHP - Lock a file
PHP - Insert image in database




Read more articles


General Knowledge



Learn Popular Language