My website has a form where users can upload documents. They are stored in the www.mysite.com/uploads folder.RIght now anyone who types that path in the brower can view those files. I was to make it so only people with access can view it. How would I do that? Thanks.
You should use .htaccess to manage all user with login and password.
More information on the link : http://www.elated.com/articles/password-protecting-your-pages-with-htaccess/
Step 1: do not upload your files to a folder inside docroot. That is, if your document root is /var/www/html, make the upload location something like /var/www/uploads.
Step 2: Create a PHP file accessfile.php that authenticates admin and takes file name as $_GET parameter. e.g. http://site.com/accessfile.php?file=myfile.pdf
Inside accessfile.php, you may want to write a small program as below:
header("Content-Disposition: attachment");
file_get_contents("/var/www/uploads/{$file}");
Step 3: If admin needs to browse, create a quick browse option:
function &list_directory($dirpath) {
if (!is_dir($dirpath) || !is_readable($dirpath)) {
error_log(__FUNCTION__ . ": Argument should be a path to valid, readable directory (" . var_export($dirpath, true) . " provided)");
return null;
}
$paths = array();
$dir = realpath($dirpath);
$dh = opendir($dir);
while (false !== ($f = readdir($dh))) {
if (strpos("$f", '.') !== 0) { // Ignore ones starting with '.'
$paths["$f"] = "$dir/$f";
}
}
closedir($dh);
return $paths;
}
Related
I want to make a module which search within a files (file type: .doc, .docx, .pdf). By using "file_get_contents()" I can find the files but for that I have to specify the location where all the files are. In my case I have the files in many folders (like this: C:\xampp\htdocs\cats1\attachments\site_1\0xxx..) the files are always store in the "0xxx" folder (By other application). I just want to specify the path so that no matter how many "folders" the "0xxx" folder contain, it search within it. I am quite new to php, please do help. My code for this application is below.
<?php
$matched_files = array();
if(isset($_POST['submit']))
{
$skills = $_POST['skills'];
$experience= $_POST['experience'];
$location = $_POST['location'];
$path = 'C:\Docs';
$dir = dir($path);
// Get next file/dir name in directory
while (false !== ($file = $dir->read()))
{
if ($file != '.' && $file != '..')
{
// Is this entry a file or directory?
if (is_file($path . '/' . $file))
{
// Its a file, yay! Lets get the file's contents
$data = file_get_contents($path . '/' . $file);
// Is the str in the data (case-insensitive search)
if (stripos($data, $skills) !== false and (stripos($data, $experience) !== false and (stripos($data, $location) !== false)))
{
$matched_files[] = $file;
}
}
}
}
$dir->close();
$matched_files_unique = array_unique($matched_files);
}
?>
The files that you're mentioning are not text files. Additionally, it is not a good idea to store these files' contents in a database. Here's the approach I would take:
Store these files using their hash (generated from something like
sha1()) as the file name to store the files to the filesystem.
Create a table to store the metadata (file name, data uploaded, hash
name) of the files.
Within the above-mentioned table, create a text column to store
the extracted text from the files. Each file type will require a
different tool. For instance, for PDFs, you can use something like
pdftotext.
Do your searches in the database by selecting the filename (hash)
from the table where the keywords are contained within the text
column (or whatever search criteria you want).
Open the file named by the returned hash and return that file to the
user.
I have a website with a lot of static content pages which are divided by categories, each category has a folder and index.html inside
What I want to do is to put some code inside the main index.php file in a way that whenever a user visits this index.php file, he will be redirected to one of my folders,
For example:
index.php code :
<?php
random_redirect_the_user();
?>
Where random_redirect_the_user() will redirect the user to http://www.example.com/wiki/(FOLDER)
And (FOLDER) is randomly chosen and can be any folder of the ones that appear above.
The question :
What shall I write inside the random_redirect_the_user() to perform this kind of redirection ?
Try something like this: First, get the array of names of all folders:
$dir = '/tmp'; //here set you main folder
$foldersArray = scandir($dir)
Then, get a random name:
$randomFolderKey = array_rand($foldersArray);
After that, do the following:
header('Location: www.youwebsiteUrl/'.$foldersArray[$randomFolderKey])
var $directories = Read your folder list from the server (Search for: PHP Read directories)
Get a random directory (Search for: PHP random)
// You can get a random between 0 and count($directories)
Then redirect your user: (Search for: PHP redirect | PHP header )
And you are done!
This should do what you are looking for.
Hope it helps
function random_redirect_the_user(){
$dir_list = array();
$path = '/path/to/directory/';
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if($entry == '.' || $entry == '..'){
continue;
}
if(is_dir ( $path.''.$entry )){
array_push($dir_list, $path.''.$entry);
}
}
}
$count = count($dir_list);
$random = rand(0,$count);
return $dir_list[$random];
}
$dir = random_redirect_the_user();
echo $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']
}
$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>
I have a function which gives me the complete file structure upto n-level,
function getDirectory($path = '.', $ignore = '') {
$dirTree = array ();
$dirTreeTemp = array ();
$ignore[] = '.';
$ignore[] = '..';
$dh = #opendir($path);
while (false !== ($file = readdir($dh))) {
if (!in_array($file, $ignore)) {
if (!is_dir("$path/$file")) {
//display of file and directory name with their modification time
$stat = stat("$path/$file");
$statdir = stat("$path");
$dirTree["$path"][] = $file. " === ".
date('Y-m-d H:i:s', $stat['mtime']) . " Directory ==
".$path."===". date('Y-m-d H:i:s', $statdir['mtime']) ;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))$dirTree =
array_merge($dirTree, $dirTreeTemp);
}
}
}
closedir($dh);
return $dirTree;
}
$ignore = array('.htaccess', 'error_log', 'cgi-bin', 'php.ini', '.ftpquota');
//function call
$dirTree = getDirectory('.', $ignore);
//file structure array print
print_r($dirTree);
Now here my requirement is , I have two sites
The Development/Test Site- where i do
testing of all the changes
The Production Site- where I finally
post all the changes as per test in
development site
Now, for example, I have tested an image upload in the Development/test site, and i found it appropriate to publish on Production site then i will completely transfer the Development/Test DB detail to Production DB, but now I want to compare the files structure as well to transfer the corresponding image file to Production folder.
There could be the situation when I update the image by editing the image and upload it with same name, now in this case the image file would be already present there, which will restrict the use of "file_exist" logic, so for these type of situations....HOW CAN I COMPARE THE TWO FILE STRUCTURE TO GET THE SYNCHRONIZATION DONE AS PER REQUIREMENT??
EDITED
the requirement has to be a script, which I am going to need as a joomla component functionality.. please reply as per this.
I would suggest using rsync for this.