In a file called docs.php I have made the following code to display all the files inside uploads folder
The foreach() loops all the files there stored in a view of the website and has an hyperlink that let it be open in the browser (in my model file it has restriction's to only pds, png or jpg files)
What i'm not able to do is inside the foreach() loop for every iteration is display some sort of hyperlink (example: Delete me!) that permits the user to click and delete only that particular file physical from the server, the others not clicked must remain visible.
My php code inside a view to the forloop() is:
<?php
$files=\yii\helpers\FileHelper::findFiles('uploads/', ['except'=>['*.DS_Store']]);
if (isset($files[0])) {
foreach ($files as $index => $file) {
$nameFile = substr($file, strrpos($file, '/') + 1);
echo Html::a($nameFile, Url::base().'/uploads/'.$nameFile) . "<br/>" . "<br/>" ; // render do ficheiro no browser
}
} else {
echo "There are no files available for download.";
}
?>
As i assume you have concept of FileHelper, but to delete file you have to use php native function unlink(filePath). unlink()
Related
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']];
?>
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']
}
I am trying to upload multiple images into the folder using php . The code can print out the file names which means I get the files but now it does not upload them and I get no error : below is my code
<?php
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name']as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
#print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target);
}
}
?>
In target you have to give the file name too. Please use the code below,
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name'] as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target.$_FILES['FILE_NAME']['name']);
}
}
I think the problem is in the foreach loop.
foreach ($_FILES['FILE_NAME']['tmp_name'] as $key => $val) {
// this loops through the tmp_name of $_FILES['FILE_NAME']
// which is a string
}
I think you meant something like:
foreach ($_FILES as $index => $fileArray) {
$tmpName = $fileArray['tmp_name'];
echo "File at key $index is temporarily uploaded at $tmpName";
}
The code above will loop through all uploaded files and print it's current filename.
It might happen that your target folder is not writable.
I also think, that the cause of which you're not getting errors is, that you have the following:
print_r($key);
Yous should have:
print_r($error);
There can be multiple reasons for this :
The target folder must exist before trying to move the file from temp location to the target and must also be writable
the move_uploaded_file takes the second argument as the file name followed by the directory name, so it can be something like : target folder/user.file.name.ext
If you are uploading multiple files, then the $_FILES must be accessed as shown in the link : http://php.net/manual/en/features.file-upload.multiple.php
for the php error messages that you may encounter, here is a list : http://php.net/manual/en/features.file-upload.errors.php
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'm trying to create an Intranet page that looks up all pdf documents in a UNC path and the returns them in a list as hyperlinks that opens in a new window. I'm nearly there however the following code displays the FULL UNC path - My question how can I display only the Filename (preferably without the .pdf extension too). I've experimented with the basename function but can't seem to get the right result.
//path to Network Share
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>$file</a><br>";
}
The links work fine it just the display text shows //myserver/adirectory/personnel/document.pdf rather than just document. Note the above code was taken from another example I found whilst researching. If there's a whole new better way then I'm open to suggestions.
echo basename($file);
http://php.net/basename
Modify your code like this:
<?
$uncpath = "//myserver/adirectory/personnel/";
//get all files with a .pdf extension.
$files = glob($uncpath . "*.pdf");
//print each file name
foreach ($files as $file)
{
echo "<a target=_blank href='File:///$file'>".basename($file)."</a><br>";
}
?>
You may try this, if basename() does not work for some reason:
$file_a = explode('/',$file);
if (trim(end($file_a)) == '')
$filename = $file_a[count($file_a)-2];
else
$filename = end($file_a);