Display a random link from my site? - php

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;

Related

PHP File count inside a folder

I'm using bootstrap tables and rows to count how much files are in a folder, but the destination is pointing to a different server the code below does not work.
As i'm using localhost (xampp) trying to do this don't know if its possible.
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/'; <!--\\189.207.00.122\folder1\folder2\folder3\test-->
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
Here is a handy little function you might want to try out. Just pass the path to the Directory as the first argument to it and you'd get your result.
NOTE: This Function is RECURSIVE, which means: it will traverse all sub-directories... to disable this behaviour, simply comment out or delete the following lines towards the end of the Funciton:
<?php
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
THE CODE:
<?php
$folder = dirname(__FILE__).'/uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS IN THE SAME DIRECTORY AS index.php
// (/htdocs/php/pages)
// OR
$folder = dirname(__FILE__).'/../uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS ONE DIRECTORY ABOVE
// THE CURRENT DIRECTORY (/htdocs/php)
// THIS IS MOST LIKELY RIGHT
// OR
$folder = dirname(__FILE__).'/../../uploads';// ASSUMES YOUR uploads DIRECTORY
// IS TWO DIRECTORIES ABOVE
// THE CURRENT DIRECTORY (/htdocs)
// MAKE SURE THE FOLDER IN QUESTION HAS THE RIGHT PERMISSIONS
// OR RATHER CHANGE PERMISSIONS ON THE FOLDER TO BE ABLE TO WORK WITH IT
chmod($folder, 0777);
var_dump(getFilesInFolder($folder));
// IF YOU PASS false AS THE THE 2ND ARGUMENT TO THIS FUNCTION
// YOU'D GET AN ARRAY OF ALL FILES IN THE $path2Folder DIRECTORY
// AS WELL AS IN SUB-DIRECTORIES WITHIN IT...
function getFilesInFolder($path2Folder, $countOnly=true){
$files_in_dir = scandir($path2Folder);
$returnable = array();
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $path2Folder . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && !preg_match("#^\..*#", $temp_file_or_dir)){
$arrRX = array('#\.{2,4}$#', '#\.#');
$arrReplace = array("", "_");
$returnVal = preg_replace($arrRX, $arrReplace, $val);
$returnable[$returnVal] = $temp_file_or_dir;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return ($countOnly) ? count($returnable) : $returnable;
}
Use $_SERVER['DOCUMENT_ROOT'] to get your root directory.
$dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';

Make folders accessible to select users only

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;
}

PHP to build gallery navigation

I was wondering if it is possible to use my server's file structure to automatically build a navigation menu for an image gallery.
Currently I have a simple "showcase" with hard-coded links to different folders of images (using jquery and ajax and php, some things that I don't quite understand but learned how to use from tutorials and the like). Basically, I have three files:
main.php
main.css
images.php
and I use hard links on main.php to call the images.php script to load a specific folder containing images into a div on the main page.
Here is my current nav setup:
<ul>
<li>Animals</li>
<li>People</li>
<li>Objects</li>
</ul>
My question is: Since all my images are in subdirs under the "images" dir, is there a way I can just build the navigation points (php script?) using the names of the subdirs in "images"? (such that it is kept up to date when I add more folders)
also, for some reason I can't make the variables on my script include the 'images.php?dirname=images/', is there any way to fix that?
If they are all in the images directory, you can specify a $image_path
<?php
$image_path = '/full/path/to/images';
if ($_GET['gallery']) {
$gallery_path = $image_path . '/' . $_GET['gallery'];
# if $_GET['gallery'] is `animals`:
#
# $gallery_path = '/full/path/to/images/animals'
# load your images within this path
}
?>
And to get all the subdirectories use dir
<?php
$image_path = '/full/path/to/images';
$d = dir($image_path);
while (false !== ($entry = $d->read())) {
if (is_dir($image_path . $entry)) {
if (($entry != '.') || ($entry != '..')) {
echo $entry; # or print your html code for each directory.
}
}
}
?>

get all file names from a directory in php

(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}

PHP: How can I grab a single file from a directory without scanning entire directory?

I have a directory with 1.3 Million files that I need to move into a database. I just need to grab a single filename from the directory WITHOUT scanning the whole directory. It does not matter which file I grab as I will delete it when I am done with it and then move on to the next. Is this possible? All the examples I can find seem to scan the whole directory listing into an array. I only need to grab one at a time for processing... not 1.3 Million every time.
This should do it:
<?php
$h = opendir('./'); //Open the current directory
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..') { //Skips over . and ..
echo $entry; //Do whatever you need to do with the file
break; //Exit the loop so no more files are read
}
}
?>
readdir
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Just obtain the directories iterator and look for the first entry that is a file:
foreach(new DirectoryIterator('.') as $file)
{
if ($file->isFile()) {
echo $file, "\n";
break;
}
}
This also ensures that your code is executed on some other file-system behaviour than the one you expect.
See DirectoryIterator and SplFileInfo.
readdir will do the trick. Check the exampl on that page but instead of doing the readdir call in the loop, just do it once. You'll get the first file in the directory.
Note: you might get ".", "..", and other similar responses depending on the server, so you might want to at least loop until you get a valid file.
do you want return first directory OR first file? both? use this:
create function "pickfirst" with 2 argument (address and mode dir or file?)
function pickfirst($address,$file) { // $file=false >> pick first dir , $file=true >> pick first file
$h = opendir($address);
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..' && ( ($file==false && !is_file($address.$entry)) || ($file==true && is_file($address.$entry)) ) )
{ return $entry; break; }
} // end while
} // end function
if you want pick first directory in your address set $file to false and if you want pick first file in your address set $file to true.
good luck :)

Categories