I am aware that this kind of question has already been asked before, but I have a slightly different case.
foreach($dir as $file)
{
$file = '<li>'.basename($file).'</li>';
echo $file;
}
This is my script to display files in a folder and link to them. The way it is now, I use the $_GET['file'] on the other page to receive the information on the other page. The other page is supposed to display a photo/video with the file that has been linked, however I don't know how to use the $_POST or $_SESSION in this case, since it's a loop and I don't want the information about the file be in the link.
Also, I don't want any forms. I want to click the link with the name of the file and the other website to already have the information about the file and display the video or image.
Use like this by storing the media path in session and use the corresponding index to pass.
First file:
<?php
$i = 1;
session_start();
$dir = array('1.jpg', '2.jpg', '3.jpg');
echo '<ul>';
foreach($dir as $file)
{ //echo $i.'---'.$file."<br />";
echo '<li>'.$file.'</li>';
$_SESSION['media_'.$i] = $file;
$i++;
}
echo '</ul>';
?>
test.php
<?php
session_start();
echo $_SESSION['media_'.$_GET['file']];
?>
Related
I have a task to do in which i have to list the directories with it's files which i did, but i don't understand how to delete file or edit specific file in the directories any help will be appreciated Thanks.
<?php
error_reporting(0);
if(isset($_GET['dir']))
{
// /$path = 'E:\xampp\\'.$_GET['dir'];
$path = $_GET['dir'];
}
else
{
$path = 'E:\xampp\\';
}
if(is_dir($path))
{
$arrDir = scandir($path);
echo "<ul>";
foreach ($arrDir as $key => $value)
{
echo "<a href='http://localhost/vishrut/FileUpload/filelist.php?
dir=".$path.'/'.$value."'>".$value.'</a><br>';
}
echo "</ul>";
}
else
{
echo "<textarea>";
echo file_get_contents($path);
echo "</textarea>"."<br>";
}
?>
There are lots of PHP's functions to handle files: https://www.php.net/manual/en/ref.filesystem.php
For your needs see these:
file_get_contents to read the entire file contents
file_put_contents to write the content in a file
unlink to delete a file
So, the steps to modify a file may be:
get the complete contents with file_get_contents:
$contents = file_get_contents($filePath);
apply your edits to the $contents content:
$newContents = ...
overwrite the file content:
file_put_contents($filePath, $newContents);
To delete a file is simple:
unlink($filePath);
It's important to note that your code is subjected to injection because you don't check the user data passed with $_GET.
If your script will be used only by you it's ok, instead you must check all user input: the first rule of Web programming is NEVER TRUST YOUR USERS! Also trusted users may write wrong characters in the url and that may have unexpected results (e.g. delete the wrong file!)
Read https://www.php.net/manual/en/mongodb.security.script_injection.php
I have a system I am developing to handle documents. Now everything process wise is working fine. The only thing I cannot seem to get is the file browser.
Whenever someone submits a document a folder is created with their name and the documents placed inside. I have a bit of code to view the folders but there is no way to add a button so the user can go back to the system.
see my code below:
<?php
$dir = opendir('SubmittedDocs/');
echo '<ul>';
while ($read = readdir($dir))
{
if ($read!='.' && $read!='..')
{
echo '<li>'.$read.'</li>';
}
}
echo '</ul>';
closedir($dir);
?>
i have an application that is used to edit .txt files. the application is made up of 3 parts
Displays contents of a folder with the files to be edited(each file is a link when clicked it opens on edit mode).
writing in to a file.
saving to file.
part 2 and 3 I have completed using fopen and fwrite functions that wasn't too hard. the part that i need help is part one currently I open the file by inputing its location and file name like so in the php file where i have the display function and save function:
$relPath = 'file_to_edit.txt';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath ! ");
but what i want is for the file to open in edit mode when clicked instead of typing in the files name every time.
$directory = 'folder_name';
if ($handle = opendir($directory. '/')){
echo 'Lookong inside \''.$directory.'\'<br><br>';
while ($file = readdir($handle)) {
if($file !='.' && $file!='..'){
echo '<a href="'.$directory.'/'.$file.'">'.$file.'<a><br>';
}
}
}
this is the code that ti use to display the list of files that are in a specified folder.
Can anyone give me some pointers how I can achieve this ? any help will be greatly appreciated.
To get content of file use file_get_contents();
To put content of file use file_put_contents(); with FILE_APPEND flag for editing.
To recieve list of files in directory you can use DirectoryIterator
Example:
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
If you don't want to put filenames you can put read files once put in db assign ids to them and use links with id param. The other solution is to store files in session array and assign keys for them. When you want to get a file you just need to provide key instead of whole filename and path.
Example with $_SESSION
$file_arr = array();
foreach (new DirectoryIterator('PATH/') as $fileInfo) {
if($fileInfo->isDot()) continue;
$file_arr[] = array("path" => $fileInfo->getPathname(), 'name' => $fileInfo->getFilename());
}
$_SESSION['files'] = $file_arr;
then in view you can use
foreach($_SESSION['files'] as $k=>$file)
{
echo "<a href='edit.php?f=".$k."'>'.$file['name'].'</a>";
}
and edit.php
$file = (int)$_GET['f'];
if(array_key_exits($file, $_SESSION['files'])
{
$fileInfo = $_SESSION[$file'];
//in file info you have now $fileInfo['path'] $fileInfo['name']
}
The purpose of the script is to change the names of of a list of images within a directory for an ecommerce site. So specifically when the script is rand a user will type in a word or phrase that they would like a set or list of files to be prefixed with. The script will iterate over each file changing the prefix and appending the next available number starting from zero.
I'd like to display/render on the page to the user what files have been changed. right now when the script is ran it displays the current files within the directory, and then it list the changed files and their names within the directory.
How can i get the file list only to display when the script has finish processing the new names?
Why does the script not append the proper incremented number to the file name? It renames files the following order:
abc0.jpg
abc1.jpg
abc10.jpg
abc11.jpg
abc12.jpg
abc13.jpg
<?php
$display_file_list;
//Allow user to put choose name
if (isset($_POST['file_prefix'])){
$the_user_prefix = $_POST['file_prefix'];
//open the current directory change this to modify where you are looking
$dir = opendir('.');
$i=0;
//Loop though all the files in the directory
while(false !==($file = readdir($dir)))
{
//This is the way we would like the page to function
//if the extention is .jpg
if(strtolower(pathinfo($file, PATHINFO_EXTENSION)) =='jpg')
{
//Put the JPG files in an array to display to the user
$display_file_list[]= $file;
//Do the rename based on the current iteration
$newName = $the_user_prefix.$i . '.jpg';
rename($file, $newName);
//increase for the next loop
$i++;
}
}
//close the directory handle
closedir($dir);
}else{
echo "No file prefix provided";
}
?>
<html>
<body>
<form action="<?=$_SERVER['PHP_SELF']?>" method="POST">
<input type="text" name="file_prefix"><br>
<input type="submit" value="submit" name="submitMe">
</form>
</body>
</html>
<?php
foreach ($display_file_list as $key => $value) {
echo $value. "<br>";
}
?>
"How can i get the file list only to display when the script has finish processing the new names?"
I think this will work for you;
$path = "path/to/files";
$files = glob("{$path}/*.jpg");
$files_renamed = array();
foreach ($files as $i => $file) {
$name = "{$path}/{$prefix}{$i}.jpg";
if (true === rename($file)) {
$files_renamed[] = $name;
}
}
print_r($files_renamed);
I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content.
I'd like to randomly grab a file from this folder and echo it into a div. Here is what I have:
<?php
function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
<div class="my-div">
<?php echo random_update(); ?>
</div><!--end my-div-->
I am getting 500 errors? Also, my intention is to only echo 1 file at a time. Will the provided code accomplish that?
Php does not recognize the syntax you used. You have to bypass it like this:
<?php
function random_update($dir = NULL)
{
if ($dir === NULL) {
$dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
}
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Also, you might want to enable error dumping in your development environment so you know what went wrong next time.
Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code:
<?php echo random_update(); ?>
for this one:
<?php echo file_get_contents (random_update()); ?>
because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div.
You can't use any expression as "default" function's argument value.