I've looked at similar posts here but couldn't crack a solution. I'm getting the Strict Standards: Only variables should be passed by reference error here on the strtolower($file['name']))), line. Tried hours now looking for a solution but couldn't figure out how to correct. Can you highlight where I've gone wrong?
Note: Code Edited as per #Kolink's suggestion below:
<?php
require_once 'upload_config.php';
$mydirectory = myUploadDir();
$uploaded_file_counter = 0;
$UploadLimit = $_POST['counter'];
for ($i = 0; $i <= $UploadLimit; $i++) {
$file_tag = 'filename' . $i;
$filename = $_FILES[$file_tag]['name'];
if ($filename != null) {
$rand = time();
$str = "$rand$filename";
// set folder name in here.
$filedir = myUploadDir();
//change the string format.
$string = $filedir . $str;
$patterns[0] = "/ /";
$patterns[1] = "/ /";
$patterns[1] = "/ /";
$replacements[1] = "_";
$dirname = strtolower(preg_replace($patterns, $replacements, $string));
//end of changing string format
//checking the permitted file types
if ($check_file_extentions) {
$allowedExtensions = allowedfiles();
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
/*if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) */
if (!in_array(array_reverse(explode(".", strtolower($file['name'])))[0], $allowedExtensions)) {
$fileUploadPermission = 0;
} else {
$fileUploadPermission = 1;
}
}
}
} else {
$fileUploadPermission = 1;
}
//end of checking the permitted file types
if ($fileUploadPermission) {
if (move_uploaded_file($_FILES[$file_tag]['tmp_name'], $dirname)) {
echo "<p>"; ?>
<div><?php echo "<img style='height:100px;width:200px' src='$dirname'>"; ?></div> <?php
echo "</p>";
$uploaded_file_counter += 1;
}
}
}
}
if ($uploaded_file_counter == 0) {
echo "<br /> <b style='font-weight:bold;color:red'>Opss! Please select an image file<b>";
} else {
echo "<br /> <b>You request " . $i . " image files to upload and " . $uploaded_file_counter . " files uploaded sucessfully</b>";
}
?>
end takes its argument by reference, since it modifies the original array by moving its internal pointer.
Since you appear to be using PHP 5.4, you can do this instead to get the last one:
if( !in_array(array_reverse(explode(".",strtolower($file['name'])))[0],$allowedExtensions))
That said, it's probably better to do it in several steps for readability:
$parts = explode(".",strtolower($file['name']));
$extension = $parts[count($parts)-1];
if( !in_array($extension,$allowedExtensions)) {
Related
I have a php search code that returns the results in the page. What I wanna do is limit the number of results per page to 10, and echo a link for more results.
My code is:
$dir = 'www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
if (!empty($q)) {
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/'.$file;
if (file_exists($fpath)) {
echo "<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date ("d F Y ", filemtime($fpath)) ;
echo "<br>";
}
}
}
closedir($res);
}
else {
echo "";
}
I tried the $q->limit(10); but it doesnt work. Please help me write a working code.
<?php
$dir = 'www/posts';
$exclude = array(
'.',
'..',
'.htaccess'
);
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$results=[];
if (! empty($q)) {
$res = opendir($dir);
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && ! in_array($file, $exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/' . $file;
if (file_exists($fpath)) {
$results[]="<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date("d F Y ", filemtime($fpath));
}
}
}
closedir($res);
}
foreach ($results as $result) {
echo $result;
echo "<br>";
}
if (count($results) > 10 ) {
echo 'results is more than 10, but only 10 results is shown';
}
Here is a completely untested suggestion... I am happy to have a bit of back and forth to iron it out.
if(!empty($_GET['q'])){
// perform some logical validation/sanitization on `$_GET['q']` for stability/security
$path = '../posts'; // this relative path may need some adjusting
$files=glob("$path/*.txt"); // collect all .txt files from the directory
var_export($files);
$filtered=preg_grep('~.*'.preg_quote($q,'/').'.*\.txt$~i',$files); // case-insensitive filename search
var_export($filtered);
if(!empty($filtered)){
$batches=array_chunk($filtered,10); // store in groups of 10
var_export($batches); // check the data
if(!isset($_GET['page'],$batches[--$page])){ // a page has been submitted and that page exists in the batches array (subtract one to sync the page with the index)
$page=0;
}
$leftovers=array_keys(array_diff_key($batches,[$page=>'']));
foreach($batches[$page] as $filename){
$withoutExt=substr($filename,0,strrpos($filename,"."));
$fpath="posts/$filename";
echo "<div><a href='/search.php?post=$withoutExt'>$withoutExt</a> on ",date("d F Y",filemtime($fpath)),"</div>";
}
// here you can list the other pages available from this search
if($leftovers){
echo "Additional pages:";
foreach($leftovers as $offset){
echo " <a href='/search.php?q={$_GET['q']}&page=",++$offset,"'>$offset</a>";
}
}
}
}else {
echo "No Search Terms found";
}
I'm taking data from an excel using phpexcel, like this:
$number = $objPHPExcel->getActiveSheet()->getCell('A3')->getValue();
number is clearly a number, okay? so, after that I want to know if $number exists on the word $elem:
if(strpos($elem,$number) !== false) //está?
{
$answer = true;
}
the problem is that when I test it with this data, the $answer is true, and it shouldn't be:
$number = 11001456
$elem = '10001033.jpg'
So... what's wrong here?
PD: I'm going to post the entire code so you can see it, If I try to do (string)$number then the code crashes, it exceeds time execution.... (using cakephp)
The important thing is located at the function SearchPhoto... you will see the strpos there...
public function admin_load() //esto sirve para cargar un excel...
{
if($this->request->is('post'))
{
$data = $this->request->data;
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
require_once WWW_ROOT . '/excelWorker/Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);
$objPHPExcel = PHPExcel_IOFactory::load($data['People']['excel']['tmp_name']);
$dir = WWW_ROOT . "img/photos";
$files = scandir($dir);
$batchPeople = array();
for($i = 2; $i <= $data['People']['num']; $i++)
{
$batchPeople[$i-2]['People']['fullname'] = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
$batchPeople[$i-2]['People']['floor'] = $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getValue();
$batchPeople[$i-2]['People']['country'] = $objPHPExcel->getActiveSheet()->getCell('D'.$i)->getValue();
$batchPeople[$i-2]['People']['day'] = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();
$batchPeople[$i-2]['People']['month'] = $objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue();
$batchPeople[$i-2]['People']['photo'] = $this->SearchPhoto($objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue(),$files);
}
// $this->People->saveMany($batchPeople);
}
}
function SearchPhoto($number, $array)
{
$answer = '';
$getOut = false;
foreach($array as $elem)
{
if(strcmp($elem,'.') != 0 && strcmp($elem,'..') != 0)
if(strpos($elem,$number) !== false) //está?
{
echo 'coinciden--> '. $number . ',' . $elem;
echo '<br>';
$answer = $elem;
$getOut = true;
}
if($getOut)
break;
}
return $answer;
}
This should work for you:
(BTW: You use $number in the code and not $num)
<?php
$num = 11001456;
$elem = "10001033.jpg";
if(strpos($elem, (string)$num) !== false) {
echo "yes";
}
?>
For more information about strpos() look into the manual: http://php.net/manual/en/function.strpos.php
And a quote from there:
needle:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
echo chr($number); // p
echo strpos($elem, 'p'); // 10 (which is p in $elem)
I ended up using preg_match to solve my problem... I still don't know what's wrong with using strpos... because it works on all the sites I made expect this particular case!
In case anyone wondering what's the exact solution:
$text = $B;
$pattern = '/'.$A.'/';
preg_match($pattern,$text,$matches);
if(isset($matches[0]))
$answer = true;
I have a little problem with a script I wrote.
It basically combines permutations of text in every possible order.
For some reason it is adding a space in between every character - can anyone figure out why?
Thanks in advance.
<?php
if(isset($_POST['submit']))
{
//pull in the perms
$perms = "{#A#B#C|#A#B#D|#A#B#E|#A#B#F|#A#C#D|#A#C#E|#A#C#F|#A#D#E|#A#D#F|#A#E#F|#B#C#D|#B#C#E|#B#C#F|#B#D#E|#B#D#F|#B#E#F|#C#D#E|#C#D#F|#C#E#F|#D#E#F}";
//open the box's
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
//this is the output
$tulis = fopen("output.txt","w+");
//read the box's
$box1 = fread($box1, filesize("box1.txt"));
$box2 = fread($box2, filesize("box2.txt"));
$box3 = fread($box3, filesize("box3.txt"));
$box4 = fread($box4, filesize("box4.txt"));
$box5 = fread($box5, filesize("box5.txt"));
$box6 = fread($box6, filesize("box6.txt"));
$perms = str_replace("#A","$box1",$perms);
$perms = str_replace("#B","$box2",$perms);
$perms = str_replace("#C","$box3",$perms);
$perms = str_replace("#D","$box4",$perms);
$perms = str_replace("#E","$box5",$perms);
$perms = str_replace("#F","$box6",$perms);
echo $text;
fwrite($tulis,$perms);
//close them properly
$box1= fopen("box1.txt","r");
$box2= fopen("box2.txt","r");
$box3= fopen("box3.txt","r");
$box4= fopen("box4.txt","r");
$box5= fopen("box5.txt","r");
$box6= fopen("box6.txt","r");
fclose($box1);
fclose($box2);
fclose($box3);
fclose($box4);
fclose($box5);
fclose($box6);
fclose($tulis);
}
//this means that if the submit button hasn't been pressed, print the form!
else
{
print '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="submit" name="submit"></input>
</form>
';
}
?>
Unless I am mistaking and I missed what you are trying to do, this script is doing pretty much like what you wrote, except that there are no str_replace and it creates permuations automatically for the number of files you provide (at least 3 for it to work properly) :
$files = array(
"box1.txt",
"box2.txt",
"box3.txt",
"box4.txt",
"box5.txt",
"box6.txt"
);
$contents = array();
foreach ($files as $index => $filename) {
$contents[$index] = trim(file_get_contents($filename), " \n\r");
}
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
file_put_contents('output.txt', $text);
Note that this version does not use fopen and trim the text read from the files to remove any whitespaces (CR and CL characters too) from the content.
** Edit **
This is the actual test program that I have made :
header('Content-type: text/plain; charset=utf-8');
$contents = array(
'A', 'B', 'C', 'D', 'E', 'F'
);
// fixed embedded loops method
$perms = array();
$len = count($contents);
for ($i=0; $i<$len-2; $i++) {
for ($j=$i+1; $j<$len-1; $j++) {
for ($k=$j+1; $k<$len; $k++) {
$perms[] = $contents[$i] . $contents[$j] . $contents[$k];
}
}
}
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";
// Recursive method
function permutationRecursive( & $perms, $maxDepth, $contents = array(), $values = array(), $startIndex = 0) {
for ($i=$startIndex, $count=count($contents)-($maxDepth-1); $i<$count; $i++) {
array_push($values, $contents[$i]);
if ($maxDepth > 1) {
permutationRecursive( $perms, $maxDepth - 1, $contents, $values, $i + 1);
} else {
$perms[] = implode($values);
}
array_pop($values);
}
}
$perms = array();
permutationRecursive($perms, 3, $contents);
$text = '{' . implode('|', $perms) . '}';
echo $text . "\n";;
The output of this script is
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}
{ABC|ABD|ABE|ABF|ACD|ACE|ACF|ADE|ADF|AEF|BCD|BCE|BCF|BDE|BDF|BEF|CDE|CDF|CEF|DEF}
I have implemented a php search function on a clients website. What I would like it to do is search for files within the website directory for specific pdf files.
However I can't seem to get it to work. If I type in "pdf" into the search box it returns all the files in the directory but if I put in a specific file name then it returns nothing.
Below is the php script I am using:
<?php
$my_server = "http://www.gwent.org".":".getenv("http://www.gwent.org_80");
$my_root = getenv("docroot/");
$s_dirs = array("");
$hits = null;
$full_url = $_SERVER['PHP_SELF'];
$site_url = eregi_replace('customer_information.php', '', $full_url);
$directory_list = array('sold_msds');
$s_files = ".pdf";
foreach($directory_list as $dirlist)
{
$directory_url = $site_url.$dirlist."/";
$getDirectory = opendir($dirlist);
while($dirName = readdir($getDirectory))
$getdirArray[] = $dirName;
closedir($getDirectory);
$dirCount = count($getdirArray);
sort($getdirArray);
for($dir=0; $dir < $dirCount; $dir++)
{
if (substr($getdirArray[$dir], 0, 1) != ".")
{
$label = eregi_replace('_', ' ', $getdirArray[$dir]);
$directory = $dirlist.'/'.$getdirArray[$dir]."/";
$complete_url = $site_url.$directory;
if(is_dir($directory))
{
$myDirectory = opendir($directory);
$dirArray = null;
while($entryName = readdir($myDirectory))
$dirArray[] = $entryName;
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
}
else
{
$hits++;
if(file_exists($dirlist."/".$label))
{
$fd=fopen($dirlist."/".$label, "r");
$text=fread($fd, 50000);
$keyword_html = htmlentities($keyword);
if(!empty($keyword))
{
$do=stristr($text, $keyword) || stristr($text, $keyword_pdf);
}
if($do)
{
$strip = strip_tags($text);
$keyword = preg_quote($keyword);
$keyword = str_replace("/","\/","$keyword");
$keyword_html = preg_quote($keyword_html);
$keyword_html = str_replace("/","\/","$keyword_html");
echo "<span>";
if(preg_match_all("/((\s\S*){0,3})($keyword|$keyword_html)((\s?\S*){0,3})/i", $strip, $match, PREG_SET_ORDER));
{
$number=count($match);
if($number > 0)
{
echo "<a href='".$dirlist."/".$label."'>".$label."</a> (".$number.")";
echo "<br />";
}
for ($h=0;$h<$number;$h++)
{
if (!empty($match[$h][3]))
{
printf("<i><b>..</b> %s<b>%s</b>%s <b>..</b></i>", $match[$h][1], $match[$h][3], $match[$h][4]);
}
}
echo "</span><br /><br />";
if($number > 0):
echo "<hr />";
endif;
}
}
}
}
}
}
}
?>
Many thanks In advance
Look up the glob function http://php.net/manual/en/function.glob.php
$found = glob("/path/to/dir/*.pdf");
Edit: Nevermind your question makes it sound completely different to what your code is doing. Im guessing what i posted is incorrect
Simple search, this is not recursive. Give it a directory and it will spit out the found files
$files = glob("c:/xampp/htdocs/*.php");
if(empty($files)) {
echo "No PHP Files Found";
}
else {
foreach($files as $f) {
echo "PHP File Found: ".$f."\n";
}
}
i need help with disk_total_space function..
i have this on my code
<?php
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
?>
Name : <?php echo $row['name']; ?>
Email : <?php echo $row['email']; ?>
Diskspace Available : <?php
$dir = "C:/xampp/htdocs/freehosting/".$row['name'];
disk_total_space($dir);
} ?>
However this return me same disk space for every users ..
Anyone can shed me some light?
thanks :)
http://us2.php.net/disk_total_space says,
"Given a string containing a directory, this function will return the total number of bytes on the corresponding filesystem or disk partition."
You're likely seeing the total_space of C:
Alternative solutions do exist for both Windows and Linux.
I think what you want is something like this:
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
foreach($files as $t) {
if (is_dir(rtrim($path, '/') . '/' . $t)) {
if ($t<>"." && $t<>"..") {
$size = foldersize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
} else {
$size = filesize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
}
return $total_size;
}
function format_size($size) {
$mod = 1024;
$units = explode(' ','B KB MB GB TB PB');
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
return round($size, 2) . ' ' . $units[$i];
}
$SIZE_LIMIT = 5368709120; // 5 GB
$sql="select * from users order by id";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$disk_used = foldersize("C:/xampp/htdocs/freehosting/".$row['name']);
$disk_remaining = $SIZE_LIMIT - $disk_used;
print 'Name: ' . $row['name'] . '<br>';
print 'diskspace used: ' . format_size($disk_used) . '<br>';
print 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>';
}
edit: the recursive function had a bug in it originally. Now it should also read folders inside the original folders, and folders inside those folders, and so on.
The comments on the function on PHP.net appear to indicate that this gives the space of the drive/partition $dir is in, not the size of $dir itself.
I think that method will only tell you information about the filesystem or partition the given directory is on. You could try simply shelling out to du though:
$space_used=`du -sh $dir`;
-s summarizes the entire dir, -h returns the result in "human" units like MB and GB.
Edit: apologies, I missed that this was on WIndows. WIll leave the answer in case it helps someone searching for a similar problem. For windows, try this suggestion in the PHP manual
According to the docs for disk_total_space(), the value returned is for the filesystem the directory is located on. It doesn't count the space used in a directory + its subdirectories.
You could shell out to du or for a more portable solution:
$total = 0;
foreach (new RecursiveDirectoryIterator($dir) as $entry)
{
if ($entry->isFile())
$total += $entry->getSize();
}
You could use the function:
function size_directory($ruta)
{
$gestor = opendir($ruta);
$total = 0;
while (($archivo = readdir($gestor)) !== false) {
$ruta_completa = $ruta . "/" . $archivo;
if ($archivo != "." && $archivo != "..") {
$total += filesize($ruta_completa);
}
}
return round($total / 1024, 0);
}