PHP random file display - javascript

I am using the same script from the link given below to display the files in the directory.
Link list based on directory without file extension and hyphens in php
$directory = 'folder/';
$blacklist = array(
'index'
);
foreach (glob($directory . "*.php") as $file) {
$parts = pathinfo($file);
if (!in_array($parts['filename'], $blacklist)) {
$name = preg_replace("/-/", "", $parts['filename']);
echo "<li>{$name}</li>";
}
}
The above script displays all the files (except index.php) in a folder. But I just want to display five random files. Is this possible?
http://s30.postimg.org/hbb1ce67l/screen.jpg

Based off your edit, I think this is what you're trying to do?
<?php
// Get all files ending in .php in the directory
$rand_files = glob("*.php");
// If the string "index.php" is contained in these results, remove it
// array_search returns the key of the $needle parameter (or false) if not found
if (($location = array_search("index.php", $rand_files)) !== false) {
// If "index.php" was in the results, then delete it from the array using unset()
unset($rand_files[$location]);
}
// Randomly choose 5 of the remaining files:
foreach (array_rand($rand_files, 5) as $rand_index) {
$fname = $rand_files[$rand_index];
echo "<a href='$fname'>$fname</a>\n";
}
?>

Related

Single page application with file treeview using ajax/php

I am currently working with a web-based document management system, I am creating it as a single page using ajax/php connection. I have my file tree view, that displays the folders and files using this code:
if (isset($_GET['displayFolderAndFiles'])) {
function listIt ($path) {
$items = scandir($path);
foreach ($items as $item) {
// Ignore the . and .. folders
if ($item != "." AND $item != "..") {
if (is_file($path . $item)) {
// this is the file
}
else {
// this is the directory
// do the list it again!
echo "<li><span class='fa fa-chevron-right caret'></span><button class='btn-der' id='directory" . $id . "' onclick='directoryAction(this);' value='" . $path . $item . "/'>" . $item . "</button>";
echo "<ul class='nested'>";
listIt($path . $item . "/");
//echo("<input type='text' value='".$path.$item."/'>");
echo "</ul></li>";
}
$id++;
}
}
}
listIt("./My Files/");
}
with this code it is hard for me to manipulate the tree view. I use ajax to get the result.
What I want is to reload the tree view when i add, delete file or folder. I also want to load the page once I do some queries in my application without refreshing the page.
I want to have the functionalities like the sample image, the application is FileRun.
Can someone recommend or suggest some ways to address my problem.
Will I use some javascript library or else?
Reference/Sample: Web-based Document Management System (FileRun)
You can use something like this:
public function treeArr($dir){
// First we get the directory
$paths = scandir($dir, SCANDIR_SORT_NONE);
// We remove .. && . from our array
unset($paths[array_search('.', $paths, true)]);
unset($paths[array_search('..', $paths, true)]);
// Add empty array for our tree
$arr = [];
// Check isour paths array empty
if (count($paths) < 1)
return;
// If not empty we get through all paths and add what we want
foreach($paths as $path){
$current_dir = $dir.'/'.$path;
$isDir = is_dir($current_dir);
$expandable = count( scandir( $current_dir ) ) > 2 ? true : false;
// In my case, I needed path name
// Is it expandable (as is it directory and does it contains or is it empty)
// Is it dir or file, if it is not dir it will be false so its file
// And path for that folder or file
$path_data = [
'name' => $path,
'expandable' => $expandable,
'isDir' => $isDir,
'path' => $current_dir,
];
if($expandable) $path_data['data'] = $this->treeArr($dir.'/'.$path);
// If our dir is expandable we go to read files and folders from in it and call self function with that path
array_push($arr, $path_data);
// At the end we add everything into array
}
return $arr;
}
It works for my needs and on client side you can style and add this as you like.
Within foreach you can check for other things, like file extension, date, size and pass everything you need about that. Like if it is html file and you have some live editor, you can check is it html and if it is add like 'isHTML' => true, and then on front:
if(file.isHTML) { //run the code }

Lost variable i script

I have some problem with a variable in my script I need to "send" the variable through some different files
The variable comes from the link:
index.php?email=emailname#emailname.com
The script is a file upload script. It's using 3 files in the process, please here:
/public_html/upload/index.php
/public_html/upload/content/index.php
/public_html/upload/content/UploadHandler.php
/public_html/upload/index.php is that runs the script and where the variable is received from the link:
index.php?email=emailname#emailname.com
The file code of /public_html/upload/index.php looks like:
<?php
// change the name below for the folder you want
$dir = "content/".$_GET["email"];
$file_to_write = 'test.txt';
$content_to_write = "The content";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
// a different way to write content into
// fwrite($file,"Hello World.");
fwrite($file, $content_to_write);
// closes the file
fclose($file);
// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;
$_SESSION['tmem']= $_GET["email"];
?>
I know that $_GET["email"] works since I can the code: <?=$_GET["email"]?> on the index.php file to see if it receive the variable.
The code:
$_SESSION['tmem']= $_GET["email"];
should forward the variable to the next file:
/public_html/upload/content/index.php
that looks like this:
session_start();
$dir = "content/" . $_GET["email"];
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler( array ('upload_url' =>$dir) );
And that code should forward the variable to the codes of the script where the upload patch is. Codes on the file: /public_html/upload/content/UploadHandler.php looks like:
'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/'.$_GET['email'].'/',
'upload_url' => $this->get_full_url().'/'.$_GET['email'].'/',
'input_stream' => 'php://input',
'user_dirs' => false,
'mkdir_mode' => 0755,
'param_name' => 'files',
Can somebody see where in the process I lose the variable?
I think, in this part of code:
session_start();
$dir = "content/" . $_GET["email"];
you try to get your "email" from URI instead of getting it from session (tmem).

Recognising strings between certain tags in external file -PHP

I am new to php, and want a script that can recognise text between certain tags in an external file.
I managed to find an answer here, that recognises the text in tags in a set string, but I am unsure of how to get the file to recognise the tags in an external text file.
PHP:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "The <tag>Output</tag>"; // this is the string
$parsed = innerh($fullstring, "<tag>", "</tag>");
echo $parsed;
?>
External File:
<tag>This text</tag> <!-- This is the target -->
Similar to what you are already doing. Currently you are making a string with that tag and when you want to read it from a file you can simply do
$fullstring = file_get_contents('your-file.html');
No other changes are required. You might need to provide full path of that file but that's about it.
That function reads a file and returns its contents in a string which you can save in your variable just like you built the variable manually.
Your code must be somthing like this:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
// Open a file with READ-ONLY flag ("r") and start of begining for read.
// See: http://php.net/manual/en/function.fopen.php
$fp = fopen("/path/to/file", "r");
// Check that file is opened and ready for read
if ($fp) {
// Until we have content on file, we resume reading
while (!feof($fp)) {
// Read from file, line by line.
// See: http://php.net/manual/en/function.fgets.php
$line = fgets($fp);
// Process line by line and print result
$parsed = innerh($line, "<tag>", "</tag>");
echo $parsed;
/* If your input file is a file without a new line or something like it,
just add a `$line = '';` before while line and change read line with
`$line .= fgets($fp);`, also remove process line and print line. After
that your file is on $line variable ;). */
}
}
?>

Basic PHP iterations and explode? as well as header

<?php
include_once("database.php");
Header("content-type: application/x-javascript");
if(isset($_GET["files"])){
$src = explode("+",$src);
for($i = 0;$i<=count($src);$i++){
echo "console.log('$src');";
echo "console.log('$src[$i]');";
$file = preg_replace('#[^a-z0-9]#','',$src[$i]);
echo "console.log('You\'ve select $file');";
}
exit();
}else{
echo "console.error('No Files were found. Please try again, make sure your request is correct')";
}
?>
I'm trying to create a dynamic JavaScript file, and the consoles are working but my iteration of the $src is not working.
EX:
$_GET["files"] ===> file1+file2+file3+file4
url looks like myfile.php?files=file1+file2+file3+file4
So basically I want to split these up into an array by seperating the + in the $_GET I'm new to PHP and I'm trying to learn this on my own but there is not clear cut documentation that I can find quickly.
ALSO
Am I do my preg_replace correctly? I want to ensure there is no malicious injection going on
UPDATE
if(isset($_GET["files"])){
$src = explode("+",$_GET["files"]);
foreach($src as $files){
$file = preg_replace('#[^a-z0-9]#','',$files);
echo "console.log('$file');";
}
exit();
}
//Direct Output:
==>You've Selected aweelemtawe
//Output should be:
==>You've Selected awc
==>You've Selected elemt
==>You've Selected awe
For the incorrect usage of explode()
The following line contains your explode() call
$src = explode("+",$src);
At this stage (using the code example you've posted above) $src will not contain any data to be explode()ed. You want to use the $_GET['files'] value as the parameter
$src = explode("+", $_GET['files']);
See the php docs on explode for more info on how it works.
For your looping/iteration
For your loop you may also want to change your loop to check for $i < count($src). If you have file1+file2+file3+file4 the array will have 4 items at index 0, 1, 2 and 3. You want that statement to read $i < 4 not $i <= 4.
However... as #TML suggested, using foreach is preferred over for when directly iterating over an array.
foreach(explode('+', $_GET['files']) as $file)
{
// work with $file here (each one will be an element of the exploded array)
}
For the sake of simplifying the example, the above is essentially equivalent to
$src = explode('+', $_GET['files']);
foreach($src as $file)
{
// work with $file here (each one will be an element of the exploded array)
}

Struggling to create a php array to fetch photos from directory that can be used as an array in JavaScript

Basically I am trying to create a photo slideshow that will display specific photos depending on the userid. These photos will be stored in the directory of my web server space. Currently I have a html (not changed into php) file with basic html layout, css style sheet and an external js file that has my code that makes the photos fade in and out. I have added php at the bottom of my html. This is what I have:
$user_id = $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
and in my javscript, the code I had before for the array of photos:
// List of images for user one
var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";
which I have now commented out and replaced it with this:
var userphoto = <? echo json_encode($galleryarray); ?>;
I am hoping to be able to change the src of photodisplay with the new array:
photodisplay[x].attr("src", userphoto[x]);
Sorry if my problem is not clear at all. I am very confused myself. :( hopefully someone can help!
$user_id = (int) $_GET['userid'];
print "<h1> Hi, $user_id </h1>";
function returnimages($dirname = "Photos/1") {
$dirname = str_replace('..', '.', $dirname); //only remove this if you know why it's here
$pattern = "*{.jpg,.png,.jpeg,.gif}"; //valid image extensions
return glob($dirname . DIRECTORY_SEPARATOR . $pattern, GLOB_BRACE);
}
echo "var galleryarray = ".json_encode(returnimages()).";\n";
?>
Also, you should use <?= json_encode($ret) ?> because the PHP short tag (<?) is deprecated, but <?= is not, and is the equivalent of <?php echo.

Categories

Resources