exif_imagetype() [function.exif-imagetype]: - php

hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>

You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}

Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}

Related

Get the function result from a class

I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

Return in foreach showing only 1st value

I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players

randomize sub server

I am using a video script and I want to randomize the url thumbs :
there's a common.php that defines global vars for the thumbs dir and url :
define('THUMB_FILES_DIR',' ');
define('THUMB_FILES_URL','');
define('THUMBS_DIR',THUMB_FILES_DIR.'/thumbs');
define('THUMBS_URL',THUMB_FILES_URL.'/thumbs');
and the functions to get the thumbs are :
/**
* FUNCTION USED TO GET THUMBNAIL
* #param ARRAY video_details, or videoid will also work
*/
function get_thumb($vdetails,$num='default',$multi=false,$count=false,$return_full_path=true,$return_big=true,$size=false){
global $db,$Cbucket,$myquery;
$num = $num ? $num : 'default';
#checking what kind of input we have
if(is_array($vdetails))
{
if(empty($vdetails['title']))
{
#check for videoid
if(empty($vdetails['videoid']) && empty($vdetails['vid']) && empty($vdetails['videokey']))
{
if($multi)
return $dthumb[0] = default_thumb();
return default_thumb();
}else{
if(!empty($vdetails['videoid']))
$vid = $vdetails['videoid'];
elseif(!empty($vdetails['vid']))
$vid = $vdetails['vid'];
elseif(!empty($vdetails['videokey']))
$vid = $vdetails['videokey'];
else
{
if($multi)
return $dthumb[0] = default_thumb();
return default_thumb();
}
}
}
}else{
if(is_numeric($vdetails))
$vid = $vdetails;
else
{
if($multi)
return $dthumb[0] = default_thumb();
return default_thumb();
}
}
#checking if we have vid , so fetch the details
if(!empty($vid))
$vdetails = $myquery->get_video_details($vid);
if(empty($vdetails['title']))
{
if($multi)
return default_thumb();
return default_thumb();
}
#Checking if there is any custom function for
if(count($Cbucket->custom_get_thumb_funcs) > 0)
{
foreach($Cbucket->custom_get_thumb_funcs as $funcs)
{
//Merging inputs
$in_array = array(
'num' => $num,
'multi' => $multi,
'count' => $count,
'return_full_path' => $return_full_path,
'return_big' => $return_big
);
if(function_exists($funcs))
{
$func_returned = $funcs($vdetails,$in_array);
if($func_returned)
return $func_returned;
}
}
}
#get all possible thumbs of video
if($vdetails['file_name'])
$vid_thumbs = glob(THUMBS_DIR."/".$vdetails['file_name']."*");
#replace Dir with URL
if(is_array($vid_thumbs))
foreach($vid_thumbs as $thumb)
{
if(file_exists($thumb) && filesize($thumb)>0)
{
$thumb_parts = explode('/',$thumb);
$thumb_file = $thumb_parts[count($thumb_parts)-1];
if(!is_big($thumb_file) || $return_big)
{
if($return_full_path)
$thumbs[] = THUMBS_URL.'/'.$thumb_file;
else
$thumbs[] = $thumb_file;
}
}elseif(file_exists($thumb))
unlink($thumb);
}
if(count($thumbs)==0)
{
if($count)
return count($thumbs);
if($multi)
return $dthumb[0] = default_thumb();
return default_thumb();
}
else
{
if($multi)
return $thumbs;
if($count)
return count($thumbs);
//Now checking for thumb
if($num=='default')
{
$num = $vdetails['default_thumb'];
}
if($num=='big' || $size=='big')
{
$num = 'big-'.$vdetails['default_thumb'];
if(!file_exists(THUMBS_DIR.'/'.$vdetails['file_name'].'-'.$num.'.jpg'))
$num = 'big';
}
$default_thumb = array_find($vdetails['file_name'].'-'.$num,$thumbs);
if(!empty($default_thumb))
return $default_thumb;
return $thumbs[0];
}
}
/**
* Function used to check weaether given thumb is big or not
*/
function is_big($thumb_file)
{
if(strstr($thumb_file,'big'))
return true;
else
return false;
}
function GetThumb($vdetails,$num='default',$multi=false,$count=false)
{
return get_thumb($vdetails,$num,$multi,$count);
}
/**
* function used to get detaulf thumb of ClipBucket
*/
function default_thumb()
{
if(file_exists(TEMPLATEDIR.'/images/thumbs/processing.png'))
{
return TEMPLATEURL.'/images/thumbs/processing.png';
}elseif(file_exists(TEMPLATEDIR.'/images/thumbs/processing.jpg'))
{
return TEMPLATEURL.'/images/thumbs/processing.jpg';
}else
return BASEURL.'/files/thumbs/processing.jpg';
}
I want to randomize the thumbs url from which is serverd the images this way
http://img[random number].domainname
if I create an array with the values of the thumbs url and then shuffle the result to the
define('THUMB_FILES_DIR',' ');
define('THUMB_FILES_URL','');
all the thumbs will have the same url value
how to do to have different values passed to html pages ?
Instead of using global variables for the thumbs url, you need to use a function. Then it can pick a URL at random when it's called.

Object of class MPRandomText could not be converted to string in [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Object could not be converted to string?
i need to create random title to my images and i got a error
Object of class MPRandomText could not be converted to string in
C:\Program Files (x86)\EasyPHP-5.3.9\www\dir.php on line 42
and how can i include the random text to my html image title ?
class MPRandomText
{
var $filepath;
var $sepstring;
var $fixchar;
var $textfix;
var $contents;
var $random;
var $errors;
// initiate object and start functions
function MPRandomText($filepath, $sepstring, $textfix)
{
$this->filepath = $filepath;
$this->textfix = $textfix;
$this->sepstring = $sepstring;
$this->errors = "";
$this->contents = "";
$this->FileToString();
}
// read file contents into string variable
function FileToString()
{
if (!$this->filepath || !file_exists($this->filepath))
$this->errors = "Could not find text file at ".$this->filepath;
else {
#$filePointer = fopen($this->filepath, "r");
if (!$filePointer) $this->errors = "Text file could not be opened.";
if ($this->errors == "")
{
$this->contents = fread($filePointer, filesize($this->filepath));
fclose($filePointer);
if (!$this->textfix) $this->HTMLContent();
$this->MakeArray();
}
}
}
// if importing an HTML page, drop everything outside of (and including) the <body> tags
function HTMLContent()
{
$test = stristr($this->contents, "<body");
if ($test !== false)
{
$test = stristr($test, ">");
if ($test !== false)
{
$test = str_replace("</BODY>", "</body>", $test);
$test = explode("</body>", substr($test, 1));
if (count($test) > 1) $this->contents = $test[0];
}
}
}
// convert the file text into a list using separation character
function MakeArray()
{
$array = explode($this->sepstring, $this->contents);
if (count($array) > 0)
{
$this->contents = $array;
$this->CleanTextList();
} else $this->errors = "Text file contents are empty or could not be read.";
}
// clean up the list of empty values and extra white space
function CleanTextList()
{
$result = array();
if (is_array($this->contents))
{
for ($n=0; $n<count($this->contents); $n++)
{
$string = trim($this->contents[$n]);
$test = trim($string."test");
if (!empty($string) AND $test != "test") $result[] = $string;
}
if (count($result) > 0)
{
$this->contents = $result;
$this->RandomString();
}
}
}
// get random text string from list
function RandomString()
{
reset($this->contents);
srand((double) microtime() * 1000000);
shuffle($this->contents);
$this->random = $this->contents[0];
}
// send finished results to be printed into HTML page
function GetResults()
{
if ($this->errors != "") return $this->errors;
else
{
if ($this->textfix == true) $this->random = htmlentities($this->random);
return $this->random;
}
}
}
//-------------------------------------------------------------------------------------------------
// FUNCTION AND VARIABLE TO CREATE RANDOM TEXT INSTANCE
//-------------------------------------------------------------------------------------------------
// create variable to store instance references
$MPRandomTextHandles = array();
// function to create new handle and import random text
function MPPrintRandomText($MPTextFile = "random.txt", $MPSepString = "*divider*", $MPTextToHTML = false)
{
global $MPRandomTextHandles;
for ($n=0; $n<250; $n++)
{
if (!isset($MPRandomTextHandles[$n]))
{
$MPRandomTextHandles[$n] = new MPRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
break;
}
}
print($MPRandomTextHandles[$n]->GetResults());
return $MPRandomTextHandles[$n];
}
/* Начало конфигурации */
$thumb_directory = 'img/thumbs';
$orig_directory = 'img/imag';
/* Конец конфигурации */
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$title1='גילוף פסלים בעץ';
$i=0;
/* Открываем папку с миниатюрами и пролистываем каждую из них */
$dir_handle = #opendir($thumb_directory) or die("There is an error with your
image directory!");
$i=1;
while ($file = readdir($dir_handle))
{
/* Пропускаем системные файлы: */
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
/* Используем название файла (без расширения) в качестве названия изображения: */
// $title = implode('.',$file_parts);
// $title = htmlspecialchars($title);
include_once("GetRandomText.php");
$MPTextFile = "random.txt";
$MPSepString = "*divider*";
$MPTextToHTML = false;
$title = MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
/* Если расширение разрешено: */
if(in_array($ext,$allowed_types))
{
/* Выдаем каждое фото: */
echo '<li>
<a href="'.$orig_directory.'/'.$file.'" rel="lightbox[pasel]">
<img title="'.$title.'" src="'.$thumb_directory.'/'.$file.'" width="72" height="72" alt="גילוף פסלים בעץ" />
</a>
</li>';
}
}
/* Закрываем папку */
closedir($dir_handle);
$title is an instance of MPRandomText. You concatenate $title in the output but MPRandomText does not implement __toString(), so it can not be converted into a string.
<?php
$title = MPPrintRandomText($MPTextFile, $MPSepString, $MPTextToHTML);
// MPPrintRandomText returns an instance of MPRandomText
/* Если расширение разрешено: */
if(in_array($ext,$allowed_types))
{
/* Выдаем каждое фото: */
echo '<li>
<a href="'.$orig_directory.'/'.$file.'" rel="lightbox[pasel]">
<img title="'.$title.'" src="'.$thumb_directory.'/'.$file.'" width="72" height="72" alt="גילוף פסלים בעץ" />
</a>
</li>';
// concatenating $title here will fail because MPRandomText does not implement __toString()
}
}
?>

Categories