On click echo attribute - javascript

I am trying to create a gallery that uses PHP to go through asset folders and serve as sort of an album system. The code below retrieves files as albums :
<?php
include_once("../PhpScript/RetAlbInfo.php");
$files = array_slice(scandir('../Assets/Gallery/'), 2);
for($albflcnt = 0;$albflcnt<count($files);$albflcnt++){
echo "<div style='...'><div class='albm' style='...' onmousedown='gotoalbum();albnm();'></div><p style='...'>".$files[$albflcnt]."</p></div>";
}
?>
The problem is that I cannot find a way to get folder names from each <p> tag and append it to the url so it would show it's sub folder.

you can use glob() with GLOB_ONLYDIR option
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
or
<?php
$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
?>

You might be wanting a RecursiveDirectoryIterator? Not 100% sure. Here is a basic example. There are portions that may or may not be relevant. This basically builds a bread crumb system of sorts, but there may be parts you are looking for:
<?php
# Create some defines in the root of the website if not already done
# This is your url
define('SITE_URL','http://www.example.com');
# This is the root path
define('BASE_DIR',__DIR__);
# This is where everyour files are stored
define('MEDIA_DIR',__DIR__.'/media/');
/*
** #description This is just a link builder, there may be some functionality you could use here
** #param $path [string] Relative path
** #param $pathStr [string] Absolute path
** #param $append [string | empty] This is just append to whatever page processes this script
*/
function createLinks($path,$pathStr,$append = '/index.php')
{
# Used for the link
$url = SITE_URL.$append;
# Explodes relative path
$arr = array_filter(explode('/',$path));
# Loop through to create break crumb
foreach($arr as $dir) {
$pathStr .= '/'.$dir;
$new[] = '/'.$dir.'';
}
# Return final bread crumb
return implode('',$new);
}
# Decodes the path name, you should probably do a more secure encryption / decription method
function getPathFromRequest($path)
{
return base64_decode(urldecode($path));
}
# Set base absolute path
$core = MEDIA_DIR;
# Process the absolute path
if(!empty($_GET['goto'])) {
$base = str_replace('//','/',getPathFromRequest($_GET['goto']));
if(is_dir($base))
$base = $base.'/';
}
else
$base = $core;
# If is a directory, recurse and show the bread crumbs
if(is_dir($base)){
$skip = RecursiveDirectoryIterator::SKIP_DOTS;
$sFirst = RecursiveIteratorIterator::SELF_FIRST;
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($base,$skip),$sFirst);
# Loop through the file paths
foreach($dir as $file) {
$fname = $file->__toString();
if(is_file($fname)) {
$abs = str_replace($base,'',$fname);
$useType = (!empty($_GET['goto']))? $base : $core;
echo createLinks($abs,$useType).'<br />';
}
}
}
else {
# Redirect to file if is a file
if(is_file($base)) {
header('Location: '.SITE_URL.'/'.str_replace(BASE_DIR,'',$base));
exit;
}
}
Base view in the browser gives you something like (this is just from a directory I have):
/css/form.css
/css/styles.css
/images/bkg/bkg_white.png
/images/bkg/row_grad01.png
Then html source would look like:
/css/form.css<br />
/css/styles.css<br />
/images/bkg/bkg_white.png<br />
/images/bkg/row_grad01.png<br />
If you were to click the bkg in the 3rd or 4th link, it would display:
/bkg_white.png
/row_grad01.png
Clicking one of those would open the file in the browser. Anyway, you might be interested in some of this, all of it, or none of it! It's hard to guess with out seeing what you currently have vs what you are trying to achieve.

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 }

ExtJS PHP/MySQL backend connector error

exactly the same problem than on this post
follow carefully the documentation (official)
https://docs.sencha.com/extjs/6.5.3/guides/backend_connectors/direct/mysql_php.html
did not understand how to solve it
edit
here is a screenshot of firefox console
api.php (the file where the error is)
(took from ext js documentation and sdk examples)
<?php
require('config.php');
header('Content-Type: text/javascript');
$API = get_extdirect_api('api');
# convert API config to Ext Direct spec
$actions = array();
foreach($API as $aname=>&$a){
$methods = array();
foreach($a['methods'] as $mname=>&$m){
if (isset($m['len'])) {
$md = array(
'name'=>$mname,
'len'=>$m['len']
);
} else {
$md = array(
'name'=>$mname,
'params'=>$m['params']
);
}
if(isset($m['formHandler']) && $m['formHandler']){
$md['formHandler'] = true;
}
if (isset($m['metadata'])) {
$md['metadata'] = $m['metadata'];
}
$methods[] = $md;
}
$actions[$aname] = $methods;
}
$cfg = array(
'url'=>'data/direct/router.php',
'type'=>'remoting',
'actions'=>$actions
);
echo 'var Ext = Ext || {}; Ext.REMOTING_API = ';
echo json_encode($cfg);
echo ';';
?>
app.json edited part as asked in the tutorial i linked
"js": [
{
"path": "${framework.dir}/build/ext-all-rtl-debug.js"
},
{
"path": "php/api.php",
"remote": true
},
{
"path": "app.js",
"bundle": true
}
],
application.js
/**
* The main application class. An instance of this class is created by app.js when it
* calls Ext.application(). This is the ideal place to handle application launch and
* initialization details.
*/
Ext.define('DirectApp.Application', {
extend: 'Ext.app.Application',
name: 'DirectApp',
quickTips: false,
platformConfig: {
desktop: {
quickTips: true
}
},
launch: function () {
Ext.direct.Manager.addProvider(Ext.REMOTING_API);
},
onAppUpdate: function () {
Ext.Msg.confirm('Application Update', 'This application has an update, reload?',
function (choice) {
if (choice === 'yes') {
window.location.reload();
}
}
);
}
});
index.html
<!DOCTYPE HTML>
<html manifest="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes">
<title>DirectApp</title>
<!-- The line below must be kept intact for Sencha Cmd to build your application -->
<script id="microloader" data-app="70f32dd6-f700-4939-bc96-3af4f1c9798b" type="text/javascript" src="bootstrap.js"></script>
</head>
<body></body>
</html>
here is the router took from sdk examples as i say you can do it in the tutorial
<?php
require('config.php');
class BogusAction {
public $action;
public $method;
public $data;
public $tid;
}
$isForm = false;
$isUpload = false;
if(isset($HTTP_RAW_POST_DATA)){
header('Content-Type: text/javascript');
$data = json_decode($HTTP_RAW_POST_DATA);
}else if(isset($_POST['extAction'])) { // form post
$isForm = true;
$isUpload = $_POST['extUpload'] == 'true';
$data = new BogusAction();
$data->action = $_POST['extAction'];
$data->method = $_POST['extMethod'];
$data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null; // not set for upload
$data->data = array($_POST, $_FILES);
}else if (($data = file_get_contents('php://input')) !== '') {
$data = json_decode($data);
}else{
die('Invalid request.');
}
function doRpc($cdata){
$API = get_extdirect_api('router');
try {
if(!isset($API[$cdata->action])){
throw new Exception('Call to undefined action: ' . $cdata->action);
}
$action = $cdata->action;
$a = $API[$action];
doAroundCalls($a['before'], $cdata);
$method = $cdata->method;
$mdef = $a['methods'][$method];
if(!$mdef){
throw new Exception("Call to undefined method: $method on action $action");
}
doAroundCalls($mdef['before'], $cdata);
$r = array(
'type'=>'rpc',
'tid'=>$cdata->tid,
'action'=>$action,
'method'=>$method
);
require_once("classes/$action.php");
$o = new $action();
if (isset($mdef['len'])) {
$params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
} else {
$params = array($cdata->data);
}
array_push($params, $cdata->metadata);
$r['result'] = call_user_func_array(array($o, $method), $params);
doAroundCalls($mdef['after'], $cdata, $r);
doAroundCalls($a['after'], $cdata, $r);
}
catch(Exception $e){
$r['type'] = 'exception';
$r['message'] = $e->getMessage();
$r['where'] = $e->getTraceAsString();
}
return $r;
}
function doAroundCalls(&$fns, &$cdata, &$returnData=null){
if(!$fns){
return;
}
if(is_array($fns)){
foreach($fns as $f){
$f($cdata, $returnData);
}
}else{
$fns($cdata, $returnData);
}
}
$response = null;
if(is_array($data)){
$response = array();
foreach($data as $d){
$response[] = doRpc($d);
}
}else{
$response = doRpc($data);
}
if($isForm && $isUpload){
echo '<html><body><textarea>';
echo json_encode($response);
echo '</textarea></body></html>';
}else{
echo json_encode($response);
}
?>
QueryDatabase.php (sql request php file)
<?php
class QueryDatabase {
private $_db;
protected $_result;
public $results;
public function __construct() {
$this->_db = new mysqli(MY CREDENTIALS);
$_db = $this->_db;
if ($_db->connect_error) {
die('Connection Error: ' . $_db->connect_error);
}
return $_db;
}
public function getResults($params) {
$_db = $this->_db;
$_result = $_db->query("SELECT name,email,phone FROM heroes") or
die('Connection Error: ' . $_db->connect_error);
$results = array();
while ($row = $_result->fetch_assoc()) {
array_push($results, $row);
}
$this->_db->close();
return $results;
}
}
and finally config.php file
<?php
function get_extdirect_api() {
$API = array(
'QueryDatabase' => array(
'methods' => array(
'getResults' => array(
'len' => 1
)
)
)
);
return $API;
}
edit2
here is full network tab from firefox screenshots
edit 3
here is api.php details from network tab
answer
headers
stack trace
here is the configuration file sencha.cfg which is configuration of the minimal web server provided my sencha CMD
# sencha.cfg
#
# This is the main configuration file for Sencha Cmd. The properties defined in
# this file are used to initialize Sencha Cmd and should be edited with some
# caution.
#
# On previous versions, this file provided a way to specify the cmd.jvm.* properties
# to control the execution of the JVM. To accommodate all possible execution scenarios
# support for these properties has been removed in favor of using the _JAVA_OPTIONS
# environment variable.
#
#------------------------------------------------------------------------------
# This indicates the platform that Cmd is installed on. This is used for
# platform specific package management.
#
# Possible values: windows, osx, linux, linux-x64
#
# cmd.platform=
#------------------------------------------------------------------------------
# This is the Sencha Cmd version.
#
# THIS PROPERTY SHOULD NOT BE MODIFIED.
cmd.version=6.5.3.6
#------------------------------------------------------------------------------
# This indicates the level of backwards compatibility provided. That is to say,
# apps requiring versions between cmd.minver and cmd.version (inclusive) should
# be able to use this version.
#
# THIS PROPERTY SHOULD NOT BE MODIFIED.
cmd.minver=3.0.0.0
#------------------------------------------------------------------------------
# The folder for the local package repository. By default, this folder is shared
# by all versions of Sencha Cmd. In other words, upgrading Sencha Cmd does not
# affect the local repository.
repo.local.dir=${cmd.dir}/../repo
#------------------------------------------------------------------------------
# This is the default port to use for the Sencha Cmd Web Server.
cmd.web.port=1841
#------------------------------------------------------------------------------
# Java System Properties
#
# By setting any "system.*" properties you can set Java System Properties. For
# general information on these, see:
#
# http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
#
#------------------------------------------------------------------------------
# Proxy Settings
#
# The primary reason to set Java System Properties is to handle HTTP Proxies.
# By default, Java uses "http.proxy*" properties to configure HTTP proxies, but
# the "java.net.useSystemProxies" option can be enabled to improve the use of
# system-configured proxy settings based on your platform. If this setting does
# not work for your proxy server setup, try disabling this setting by commenting
# it out and enabling the other settings. See also this information on proxy
# setup:
#
# http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
#
# NOTE: If you find that you need to adjust these settings, you may want to do
# so in a "sencha.cfg" file one folder above this folder. The settings in that
# file override these settings, so be sure to only copy the settings you need
# to that location. The advantage to putting these settings in that location is
# that they will not be "lost" as you upgrade Cmd.
system.java.net.useSystemProxies=true
# These are the legacy options that come in to play when the above is commented
# out:
#system.http.proxyHost=proxy.mycompany.com
#system.http.proxyPort=80
#system.http.proxyUser=username
#system.http.proxyPassword=password
#------------------------------------------------------------------------------
# Merge Tool Settings
#
# To enable use of a visual merge tool to resolve merge conflicts, set the
# following property to the desired merge tool path:
#
# cmd.merge.tool=p4merge
#
# Next, to configure the arguments for the merge tool, set this property:
#
# cmd.merge.tool.args={base} {user} {generated} {out}
#
# Alternatively, the arguments for several merge tools are defined below and can
# be used in your configuration for simplicity/clarity like so:
#
# cmd.merge.tool.args=${cmd.merge.tool.args.sourcegear}
#
# NOTE: the cmd.merge.tool.args property is split on spaces *then* the tokens
# are replaced by actual files names. This avoids the need to quote arguments to
# handle spaces in paths.
#
# NOTE: Some merge tools (like SmartSynchronize) do not accept the output file
# separately so there is no way to know if the merge was completed. In this case,
# the base file is where the result is written so Cmd just copies the content of
# that file back as the result.
#
# You can add the appropriate lines to customize your Cmd configuration. See
# below for details.
# The arguments for p4merge, see below for download:
# http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools
cmd.merge.tool.args.p4merge={base} {user} {generated} {out}
# SourceGear (http://www.sourcegear.com/diffmerge/index.html)
cmd.merge.tool.args.sourcegear=--merge --result={out} {user} {base} {generated}
# kdiff3 (http://sourceforge.net/projects/kdiff3/files/kdiff3/)
cmd.merge.tool.args.kdiff3={base} {user} {generated} -o {out}
# Syntevo SmartSynchronize 3 (http://www.syntevo.com/smartsynchronize/index.html).
cmd.merge.tool.args.smartsync={user} {generated} {base}
# TortoiseMerge (part of TortoiseSVN - see http://tortoisesvn.net).
cmd.merge.tool.args.tortoise=-base:{base} -theirs:{generated} -mine:{user} -merged:{out}
# AraxisMerge (see http://www.araxis.com/merge-overview.html):
cmd.merge.tool.args.araxis=-wait -merge -3 -a1 {base} {user} {generated} {out}
# The address where Sencha Inspector is located
inspector.address=http://localhost:1839/
# this variable references a json file containing unicode code points to be
# printed in escaped form during code generation.
cmd.unicode.escapes=${cmd.dir}/unicode-escapes.json
#------------------------------------------------------------------------------
# Customizing Configuration
#
# Customization can be handled any of these ways:
#
# 1. Place customizations in this file (ideally at the bottom) and they will
# configure this instance of Sencha Cmd.
#
# 2. Create a "sencha.cfg" file in the folder above this instance of Sencha Cmd
# to be shared by all installed versions.
#
# 3. Create a "~/.sencha/cmd/sencha.cfg" file. On Windows, the "~" maps to your
# %HOMEDRIVE%%HOMEPATH% folder (e.g., "C:\Users\Me").
#
# Your personal settings take priority over common settings (item #2) which both
# take priority of instance settings (this file).
thank you
I guess you are also following the guide and using the sencha app watch and getting the php code returning back to you. I found this answer on a Sencha forum that the web server that the sencha cmd provides doesn't support php is just a basic HTTP web server.
I was looking at the exact same thing today and came across the post....
For anyone else looking for the problem this is how i fixed it. Basically you have to get the posted data in a slightly different manner... looks at the first comment in the code below
<?php
require('config.php');
class BogusAction {
public $action;
public $method;
public $data;
public $tid;
}
$isForm = false;
$isUpload = false;
// different way to get the data that is posted to the URL
$postData = file_get_contents('php://input');
if (isset($postData)) {
header('Content-Type: text/javascript');
$data = json_decode($postData);
}
else if (isset($HTTP_RAW_POST_DATA)) {
header('Content-Type: text/javascript');
$data = json_decode($HTTP_RAW_POST_DATA);
}
else if(isset($_POST['extAction'])){ // form post
$isForm = true;
$isUpload = $_POST['extUpload'] == 'true';
$data = new BogusAction();
$data->action = $_POST['extAction'];
$data->method = $_POST['extMethod'];
$data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null;
$data->data = array($_POST, $_FILES);
}
else {
die('Invalid request min .');
}
function doRpc($cdata){
$API = get_extdirect_api('router');
try {
if (!isset($API[$cdata->action])) {
throw new Exception('Call to undefined action: ' . $cdata->action);
}
$action = $cdata->action;
$a = $API[$action];
$method = $cdata->method;
$mdef = $a['methods'][$method];
if (!$mdef){
throw new Exception("Call to undefined method: $method " .
"in action $action");
}
$r = array(
'type'=>'rpc',
'tid'=>$cdata->tid,
'action'=>$action,
'method'=>$method
);
require_once("classes/$action.php");
$o = new $action();
if (isset($mdef['len'])) {
$params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
}
else {
$params = array($cdata->data);
}
$r['result'] = call_user_func_array(array($o, $method), $params);
}
catch(Exception $e){
$r['type'] = 'exception';
$r['message'] = $e->getMessage();
$r['where'] = $e->getTraceAsString();
}
return $r;
}
$response = null;
if (is_array($data)) {
$response = array();
foreach($data as $d){
$response[] = doRpc($d);
}
}
else{
$response = doRpc($data);
}
if ($isForm && $isUpload){
echo '<html><body><textarea>';
echo json_encode($response);
echo '</textarea></body></html>';
}
else{
echo json_encode($response);
}
?>

Php array returns null?

I have php file which reads a file and puts it's contents in specific arrays. This php file is a file on it's own. So I included it on another page. When I want to access one of the arrays on the other site, the output is "array(0) { }". The var_dump on the file below, however returns a full array with all 6 items(as expected).
Here my php file:
<?php
$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();
function extractTranslationsFromFile($file){
$handle = fopen($file, "r");
if ($handle){
while (($line = fgets($handle)) !== false) {
$notelist[] = $line;
$lineContent = substr($line, 3, strlen($line) - 1);
switch(substr($line, 0, 3)):
case "de:": $germanTranslationsList[] = $lineContent; break;
case "en:": $englishTranslationsList[] = $lineContent; break;
case "ts:": $timestampList[] = $lineContent; break;
default: break;
endswitch;
}
fclose($handle);
}else{
echo "<script>alert('ERROR')</script>";
}
echo var_dump($germanTranslationsList);
}
?>
On the site where I included it, I used
<p><?php echo var_dump($germanTranslationsList); ?></p>
Which just shows an empty array as said above...
What have I done wrong? Is there a way to fix it?
You need to bring the global variables into the function's scope using the global keyword:
<?php
$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();
function extractTranslationsFromFile($file) {
global $englishTranslationsList;
global $germanTranslationsList;
global $timestampList;
global $noteList;
// ...
}
Warning
When you include B.php in A.php, you should careful about the file path that you define in B.php.
So, I guess you defined some relative file path.
Example
Directory_stucture
.
├── A.php
└── dir
├── a.txt
└── B.php
A.php
require_once('dir/B.php');
B.php
$handle = fopen("a.txt", "r") or die("Unable to open file!");
echo fread($handle,filesize("a.txt"));
fclose($handle);
a.txt
Hello, world!
Result
Run B.php works fine, print 'Hello, world!'
But if you run A.php ,it print 'Unable to open file!'
Reason
When run B.php, fopen() search 'a.txt' in the dir that B.php live.
But when run A.php, fopen() search 'a.txt' in the dir that A.php live.
Advice
Use absolute file path instead of relative.

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 ;). */
}
}
?>

PHP random file display

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

Categories

Resources