This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I try many solution but it does help.i try even to switch on short_tags_on but no solution.
I am getting this error:
Parse error: syntax error, unexpected end of file in
C:\xampp\htdocs\photo_gallery\includes\functions.php on line 76
Here is my code, what is wrong?
<?php
function strip_zeros_from_date( $marked_string="" ) {
// first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
// then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location = NULL ) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message="") {
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)) {
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
function include_layout( $names, $args ){
// allow for single file names
if ( !is_array( $names ) ) {
$names = array( $names );
}
$found = false;
foreach ( $names as $name ) {
$file = siteroot.'/public/layouts/'.$name.'.php';
if ( file_exists( $file ) ) {
$found = $file;
break;
}
}
if ( ! $found ) {
return '';
}
function log_action($action, $message="") {
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { // append
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle, $content);
fclose($handle);
if($new) { chmod($logfile, 0755); }
} else {
echo "Could not open log file for writing.";
}
}
function datetime_to_text($datetime="") {
$unixdatetime = strtotime($datetime);
return strftime("%B %d, %Y at %I:%M %p", $unixdatetime);
}
?>
I am using xampp on Windows 7. I have been trying to find a solution but I dont know what wrong. Since I added the function method of including the header.php and footer.php it start giving me that error. Here is the method that I add:
function include_layout( $names, $args ){
// allow for single file names
if ( !is_array( $names ) ) {
$names = array( $names );
}
$found = false;
foreach ( $names as $name ) {
$file = siteroot.'/public/layouts/'.$name.'.php';
if ( file_exists( $file ) ) {
$found = $file;
break;
}
}
if ( ! $found ) {
return '';
}
You're not closing the include_layout function, it's missing a final }.
function include_layout( $names, $args ){
// allow for single file names
if ( !is_array( $names ) ) {
$names = array( $names );
}
$found = false;
foreach ( $names as $name ) {
$file = siteroot.'/public/layouts/'.$name.'.php';
if ( file_exists( $file ) ) {
$found = $file;
break;
}
}
if ( ! $found ) {
return '';
}
} // << missing from your code
Related
So I have seen solutions of this, however my question is slightly different.
I want the file to have a character at the end.
So, for example, there is a directory called imgs:
imgs
contents: div.png, div2.png, divb.png, divab.png
I need to randomly select a file from this folder, but I need it to have a b at the end. So I could only get on either divb.png or divab.png.
If I get one that doesn't end in b, I need to reselect.
I currently have some code that gives me a timeout and doesn't reselect.
function random_pic($dir = 'imgs'){
$files = glob($dir . '/*.png');
$file = array_rand($files);
if(substr($files[$file], -5)==$shortparam.".png"){
return $files[$file];
} else {
return null;
}
}
EDIT -----------------
<?php
function random_pic() {
$files = glob('imgs/*.png' );
do {
if ( isset( $file ) ) {
unset( $files[$file] );
}
$file = array_rand( $files );
} while ( ( substr( $files[ $file ], -5 != ( $shortparam . ".png" ) ) ) AND ( count( $files) > 0 ) );
if ( count( $files ) > 0 ) {
return $files[ $file ];
} else {
echo $file;
return false;
}
}
for ($i = 0 ; $i < 20; $k++){
$image = random_pic();
if($image == false){
} else {
// display image
This times out for some reason.
(Fatal error: Maximum execution time of 10 seconds exceeded in file.php on line 84)
Thanks for any help you can give!
You could achieve that with a blend of glob, array_walk(), array_rand() and preg_match().
<?php
function random_pic($dir='imgs', $extension=".png", $endChar="b"){
$files = glob($dir . "/*{$extension}");
$matches = array();
array_walk($files, function($imgFile, $index) use ($extension, $endChar, &$matches) {
$pixName = preg_replace("#" . preg_quote($extension) . "#", "", basename($imgFile));
if( preg_match("#" . preg_quote($endChar) . "$#", $pixName)){
$matches[] = $imgFile;
}
});
return (count($matches))? $matches[array_rand($matches)] : null;
}
$randomPic = random_pic(__DIR__. "/imgs", ".png", "b");
// OR JUST USE THE DEFAULTS SINCE THEY ARE JUST THE SAME IN YOUR CASE:
// $randomPic = random_pic();
var_dump($randomPic);
I obviously don't have your files and your directory structure to try this code against, but I'm pretty confident it will solve your problem.
function random_pic( $dir = 'imgs' ) {
if ( $files = glob( $dir . '/*.png' ) ) {
do {
if ( isset( $file ) ) {
unset( $files[$file] );
}
if ( count( $files ) > 0 ) {
$file = array_rand( $files );
}
} while ( ( substr( $files[ $file ], -5 != ( $shortparam . ".png" ) ) ) AND ( count( $files ) > 0 ) );
if ( count( $files ) > 0 ) {
return $files[ $file ];
} else {
return NULL;
}
} else {
return NULL;
}
}
You may want to consider returning FALSE instead of NULL if nothing is found since it's more versatile on the parent end.
I've looked thru the questions already with the system, but couldn't find the answer to my problem. I want to try a counter in a php recursive function, which looks for and deletes empty folders. I paste below a way to echo non-empties as "–" and empties as "|". It looks ok after all, but in case there's a lot to purge, it all grows into gibberish on the screen. Instead I'd like to see the numbers of folders checked vs deleted. Here's the code compiled so far using StackOverflow too. Any help pls?
function RemoveEmptySubFolders($path) {
echo "–";
$empty = true;
foreach ( glob ( $path . DIRECTORY_SEPARATOR . "*" ) as $file ) {
if (is_dir ( $file )) {
if (! RemoveEmptySubFolders ( $file ))
$empty = false;
} else {
$empty = false;
}
}
if ($empty) {
if (is_dir ( $path )) {
// echo "Removing $path...<br>";
rmdir ( $path );
echo "|";
}
}
return $empty;
}
Just pass the variables as reference:
function recursive($path, &$directories, &$removed) {
echo "-";
$directories ++;
$empty = true;
foreach ( glob ( $path . DIRECTORY_SEPARATOR . "*" ) as $file ) {
if (is_dir ( $file )) {
if (! recursive ( $file, $directories, $removed ))
$empty = false;
} else {
$empty = false;
}
}
if ($empty) {
if (is_dir ( $path )) {
$removed++;
echo "|";
}
}
return $empty;
}
$path = "c:\exampledir";
$directories = 0;
$removed = 0;
recursive($path, $directories, $removed);
echo("<br>$directories, $removed");
You could also use global variables, but that's very ugly, and every time you use a global variable othen than the standard ones, a kitty dies.
Object-Oriented variant:
Put everything in a class and add the instance attributes $checked and $deleted, then increment them with a selfmade procedure or (nasty code) just with += 1 or $var ++.
I am writing a code for Bayesian Filter. For a particular word, I want to check if the word is in the stop words list or not, I populate from stop word list from a file on my pc.
Because I have to do this for many words I don't want to read the StopWord file from my pc again and again.
I want to do something like this
function isStopWord( $word ){
if(!isset($stopWordDict))
{
$stopWords = array();
$handle = fopen("StopWords.txt", "r");
if( $handle )
{
while( ( $buffer = fgets( $handle ) ) != false )
{
$stopWords[] = trim( $buffer );
}
}
echo "StopWord opened";
static $stopWordDict = array();
foreach( $stopWords as $stopWord )
$stopWordDict[$stopWord] = 1;
}
if( array_key_exists( $word, $stopWordDict ) )
return true;
else
return false;
}
I thought by using a static variable it will solve the issue, but it doesn't. Kindly help.
Put the static declaration at the beginning of the function:
function isStopWord( $word ){
static $stopWordDict = array();
if(!$stopWordDict)
{
$stopWords = file("StopWords.txt");
echo "StopWord opened";
foreach( $stopWords as $stopWord ) {
$stopWordDict[trim($stopWord)] = 1;
}
}
if( array_key_exists( $word, $stopWordDict ) )
return true;
else
return false;
}
This will work since an empty array is considered falsy.
I have created a script that generates information about a torrent file! But I'm lacking in creating a seeds and peers displaying function! Someone told me that they are in the completed field defined in the torrent. Please my class function codes from which I display the generated information using a bencode.php which takes out the data and this script ,named torrent.php converts it in readable form!
<?php
include_once('bencode.php');
class Torrent
{
// Private class members
private $torrent;
private $info;
// Public error message, $error is set if load() returns false
public $error;
// Load torrent file data
// $data - raw torrent file contents
public function load( &$data )
{
$this->torrent = BEncode::decode( $data );
if ( $this->torrent->get_type() == 'error' )
{
$this->error = $this->torrent->get_plain();
return false;
}
else if ( $this->torrent->get_type() != 'dictionary' )
{
$this->error = 'The file was not a valid torrent file.';
return false;
}
$this->info = $this->torrent->get_value('info');
if ( !$this->info )
{
$this->error = 'Could not find info dictionary.';
return false;
}
return true;
}
// Get comment
// return - string
public function getComment() {
return $this->torrent->get_value('comment') ? $this->torrent->get_value('comment')->get_plain() : null;
}
// Get creatuion date
// return - php date
public function getCreationDate() {
return $this->torrent->get_value('creation date') ? $this->torrent->get_value('creation date')->get_plain() : null;
}
// Get created by
// return - string
public function getCreatedBy() {
return $this->torrent->get_value('created by') ? $this->torrent->get_value('created by')->get_plain() : null;
}
// Get name
// return - filename (single file torrent)
// directory (multi-file torrent)
// see also - getFiles()
public function getName() {
return $this->info->get_value('name')->get_plain();
}
// Get piece length
// return - int
public function getPieceLength() {
return $this->info->get_value('piece length')->get_plain();
}
// Get pieces
// return - raw binary of peice hashes
public function getPieces() {
return $this->info->get_value('pieces')->get_plain();
}
// Get private flag
// return - -1 public, implicit
// 0 public, explicit
// 1 private
public function getPrivate() {
if ( $this->info->get_value('private') )
{
return $this->info->get_value('private')->get_plain();
}
return -1;
}
// Get a list of files
// return - array of Torrent_File
public function getFiles() {
// Load files
$filelist = array();
$length = $this->info->get_value('length');
if ( $length )
{
$file = new Torrent_File();
$file->name = $this->info->get_value('name')->get_plain();
$file->length = $this->info->get_value('length')->get_plain();
array_push( $filelist, $file );
}
else if ( $this->info->get_value('files') )
{
$files = $this->info->get_value('files')->get_plain();
while ( list( $key, $value ) = each( $files ) )
{
$file = new Torrent_File();
$path = $value->get_value('path')->get_plain();
while ( list( $key, $value2 ) = each( $path ) )
{
$file->name .= "/" . $value2->get_plain();
}
$file->name = ltrim( $file->name, '/' );
$file->length = $value->get_value('length')->get_plain();
array_push( $filelist, $file );
}
}
return $filelist;
}
// Get a list of trackers
// return - array of strings
public function getTrackers() {
// Load tracker list
$trackerlist = array();
if ( $this->torrent->get_value('announce-list') )
{
$trackers = $this->torrent->get_value('announce-list')->get_plain();
while ( list( $key, $value ) = each( $trackers ) )
{
if ( is_array( $value->get_plain() ) ) {
while ( list( $key, $value2 ) = each( $value ) )
{
while ( list( $key, $value3 ) = each( $value2 ) )
{
array_push( $trackerlist, $value3->get_plain() );
}
}
} else {
array_push( $trackerlist, $value->get_plain() );
}
}
}
else if ( $this->torrent->get_value('announce') )
{
array_push( $trackerlist, $this->torrent->get_value('announce')->get_plain() );
}
return $trackerlist;
}
// Helper function to make adding a tracker easier
// $tracker_url - string
public function addTracker( $tracker_url )
{
$trackers = $this->getTrackers();
$trackers[] = $tracker_url;
$this->setTrackers( $trackers );
}
// Replace the current trackers with the supplied list
// $trackerlist - array of strings
public function setTrackers( $trackerlist )
{
if ( count( $trackerlist ) >= 1 )
{
$this->torrent->remove('announce-list');
$string = new BEncode_String( $trackerlist[0] );
$this->torrent->set( 'announce', $string );
}
if ( count( $trackerlist ) > 1 )
{
$list = new BEncode_List();
while ( list( $key, $value ) = each( $trackerlist ) )
{
$list2 = new BEncode_List();
$string = new BEncode_String( $value );
$list2->add( $string );
$list->add( $list2 );
}
$this->torrent->set( 'announce-list', $list );
}
}
// Update the list of files
// $filelist - array of Torrent_File
public function setFiles( $filelist )
{
// Load files
$length = $this->info->get_value('length');
if ( $length )
{
$filelist[0] = str_replace( '\\', '/', $filelist[0] );
$string = new BEncode_String( $filelist[0] );
$this->info->set( 'name', $string );
}
else if ( $this->info->get_value('files') )
{
$files = $this->info->get_value('files')->get_plain();
for ( $i = 0; $i < count( $files ); ++$i )
{
$file_parts = split( '/', $filelist[$i] );
$path = new BEncode_List();
foreach ( $file_parts as $part )
{
$string = new BEncode_String( $part );
$path->add( $string );
}
$files[$i]->set( 'path', $path );
}
}
}
// Set the comment field
// $value - string
public function setComment( $value )
{
$type = 'comment';
$key = $this->torrent->get_value( $type );
if ( $value == '' ) {
$this->torrent->remove( $type );
} elseif ( $key ) {
$key->set( $value );
} else {
$string = new BEncode_String( $value );
$this->torrent->set( $type, $string );
}
}
// Set the created by field
// $value - string
public function setCreatedBy( $value )
{
$type = 'created by';
$key = $this->torrent->get_value( $type );
if ( $value == '' ) {
$this->torrent->remove( $type );
} elseif ( $key ) {
$key->set( $value );
} else {
$string = new BEncode_String( $value );
$this->torrent->set( $type, $string );
}
}
// Set the creation date
// $value - php date
public function setCreationDate( $value )
{
$type = 'creation date';
$key = $this->torrent->get_value( $type );
if ( $value == '' ) {
$this->torrent->remove( $type );
} elseif ( $key ) {
$key->set( $value );
} else {
$int = new BEncode_Int( $value );
$this->torrent->set( $type, $int );
}
}
// Change the private flag
// $value - -1 public, implicit
// 0 public, explicit
// 1 private
public function setPrivate( $value )
{
if ( $value == -1 ) {
$this->info->remove( 'private' );
} else {
$int = new BEncode_Int( $value );
$this->info->set( 'private', $int );
}
}
// Bencode the torrent
public function bencode()
{
return $this->torrent->encode();
}
// Return the torrent's hash
public function getHash()
{
return strtoupper( sha1( $this->info->encode() ) );
}
}
// Simple class to encapsulate filename and length
class Torrent_File
{
public $name;
public $length;
}
?>
Please help me out!
Thanks in advance!
Little late but the class you say to have created comes from:
https://github.com/torrage/Torrage
It's original purpose was not intended to retrieve that kind of data.
A class that gets you seeds and peers for torrent inclusive the rest of the data see:
https://github.com/adriengibrat/torrent-rw
That information's not stored in the .torrent file. It's highly dynamic data, which can change every microsecond on a 'busy' torrent. The server's not going to build a custom .torrent file with up-to-the-minute statistics every time someone downloads it.
Think about it for a second. You download a .torrent file on Monday, but only look at it next Friday. The stats are now a week old and stale.
You can, however, take the tracker information in the .torrent and query those trackers for the stats.
I'm trying to find all the files and folders under a specified directory
For example I have /home/user/stuff
I want to return
/home/user/stuff/folder1/image1.jpg
/home/user/stuff/folder1/image2.jpg
/home/user/stuff/folder2/subfolder1/image1.jpg
/home/user/stuff/image1.jpg
Hopefully that makes sense!
function dir_contents_recursive($dir) {
// open handler for the directory
$iter = new DirectoryIterator($dir);
foreach( $iter as $item ) {
// make sure you don't try to access the current dir or the parent
if ($item != '.' && $item != '..') {
if( $item->isDir() ) {
// call the function on the folder
dir_contents_recursive("$dir/$item");
} else {
// print files
echo $dir . "/" .$item->getFilename() . "<br>";
}
}
}
}
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $f) {
echo "$f \r\n";
}
The working solution (change with your folder name)
<?php
$path = realpath('yourfolder/subfolder');
## or use like this
## $path = '/home/user/stuff/folder1';
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename\n";
}
?>
$dir = "/home/user/stuff/";
$scan = scandir($dir);
foreach ($scan as $output) {
echo "$output" . "<br />";
}
Find all the files and folders under a specified directory.
function getDirRecursive($dir, &$output = []) {
$scandir = scandir($dir);
foreach ($scandir as $a => $name) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $name);
if (!is_dir($path)) {
$output[] = $path;
} else if ($name != "." && $name != "..") {
getDirRecursive($path, $output);
$output[] = $path;
}
}
return $output;
}
var_dump(getDirRecursive('/home/user/stuff'));
Output (example) :
array (size=4)
0 => string '/home/user/stuff/folder1/image1.jpg' (length=35)
1 => string '/home/user/stuff/folder1/image2.jpg' (length=35)
2 => string '/home/user/stuff/folder2/subfolder1/image1.jpg' (length=46)
3 => string '/home/user/stuff/image1.jpg' (length=27)
listAllFiles( '../cooktail/' ); //send directory path to get the all files and floder of root dir
function listAllFiles( $strDir ) {
$dir = new DirectoryIterator( $strDir );
foreach( $dir as $fileinfo ) {
if( $fileinfo == '.' || $fileinfo == '..' ) continue;
if( $fileinfo->isDir() ) {
listAllFiles( "$strDir/$fileinfo" );
}
echo $fileinfo->getFilename() . "<br/>";
}
}
Beside RecursiveDirectoryIterator solution there is also glob() solution:
// do some extra filtering here, if necessary
function recurse( $item ) {
return is_dir( $item ) ? array_map( 'recurse', glob( "$item/*" ) ) : $item;
};
// array_walk_recursive: any key that holds an array will not be passed to the function.
array_walk_recursive( ( recurse( 'home/user/stuff' ) ), function( $item ) { print_r( $item ); } );
You can use the RecursiveDirectoryIterator or even the glob function.
Alternatively, the scandir function will do the job.