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";
}
Related
I need to refresh modifications after install module.
public function install() {
$this->load->controller('marketplace/modification/refresh');
}
I tried this. Its worked but the page redirected to modification listing. How can i do without redirect. I am using opencart 3.
If you don't want to edit modification.php or clone its refresh function, You can use this:
public function install(){
$data['redirect'] = 'extension/extension/module';
$this->load->controller('marketplace/modification/refresh', $data);
}
You could not controll by this way as you are doing:
You need to do this as
public function install() {
$this->refresh();
}
protected function refresh($data = array()) {
$this->load->language('marketplace/modification');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/modification');
if ($this->validate()) {
// Just before files are deleted, if config settings say maintenance mode is off then turn it on
$maintenance = $this->config->get('config_maintenance');
$this->load->model('setting/setting');
$this->model_setting_setting->editSettingValue('config', 'config_maintenance', true);
//Log
$log = array();
// Clear all modification files
$files = array();
// Make path into an array
$path = array(DIR_MODIFICATION . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
// Clear all modification files
foreach ($files as $file) {
if ($file != DIR_MODIFICATION . 'index.html') {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
// Begin
$xml = array();
// Load the default modification XML
$xml[] = file_get_contents(DIR_SYSTEM . 'modification.xml');
// This is purly for developers so they can run mods directly and have them run without upload after each change.
$files = glob(DIR_SYSTEM . '*.ocmod.xml');
if ($files) {
foreach ($files as $file) {
$xml[] = file_get_contents($file);
}
}
// Get the default modification file
$results = $this->model_setting_modification->getModifications();
foreach ($results as $result) {
if ($result['status']) {
$xml[] = $result['xml'];
}
}
$modification = array();
foreach ($xml as $xml) {
if (empty($xml)){
continue;
}
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXml($xml);
// Log
$log[] = 'MOD: ' . $dom->getElementsByTagName('name')->item(0)->textContent;
// Wipe the past modification store in the backup array
$recovery = array();
// Set the a recovery of the modification code in case we need to use it if an abort attribute is used.
if (isset($modification)) {
$recovery = $modification;
}
$files = $dom->getElementsByTagName('modification')->item(0)->getElementsByTagName('file');
foreach ($files as $file) {
$operations = $file->getElementsByTagName('operation');
$files = explode('|', $file->getAttribute('path'));
foreach ($files as $file) {
$path = '';
// Get the full path of the files that are going to be used for modification
if ((substr($file, 0, 7) == 'catalog')) {
$path = DIR_CATALOG . substr($file, 8);
}
if ((substr($file, 0, 5) == 'admin')) {
$path = DIR_APPLICATION . substr($file, 6);
}
if ((substr($file, 0, 6) == 'system')) {
$path = DIR_SYSTEM . substr($file, 7);
}
if ($path) {
$files = glob($path, GLOB_BRACE);
if ($files) {
foreach ($files as $file) {
// Get the key to be used for the modification cache filename.
if (substr($file, 0, strlen(DIR_CATALOG)) == DIR_CATALOG) {
$key = 'catalog/' . substr($file, strlen(DIR_CATALOG));
}
if (substr($file, 0, strlen(DIR_APPLICATION)) == DIR_APPLICATION) {
$key = 'admin/' . substr($file, strlen(DIR_APPLICATION));
}
if (substr($file, 0, strlen(DIR_SYSTEM)) == DIR_SYSTEM) {
$key = 'system/' . substr($file, strlen(DIR_SYSTEM));
}
// If file contents is not already in the modification array we need to load it.
if (!isset($modification[$key])) {
$content = file_get_contents($file);
$modification[$key] = preg_replace('~\r?\n~', "\n", $content);
$original[$key] = preg_replace('~\r?\n~', "\n", $content);
// Log
$log[] = PHP_EOL . 'FILE: ' . $key;
}
foreach ($operations as $operation) {
$error = $operation->getAttribute('error');
// Ignoreif
$ignoreif = $operation->getElementsByTagName('ignoreif')->item(0);
if ($ignoreif) {
if ($ignoreif->getAttribute('regex') != 'true') {
if (strpos($modification[$key], $ignoreif->textContent) !== false) {
continue;
}
} else {
if (preg_match($ignoreif->textContent, $modification[$key])) {
continue;
}
}
}
$status = false;
// Search and replace
if ($operation->getElementsByTagName('search')->item(0)->getAttribute('regex') != 'true') {
// Search
$search = $operation->getElementsByTagName('search')->item(0)->textContent;
$trim = $operation->getElementsByTagName('search')->item(0)->getAttribute('trim');
$index = $operation->getElementsByTagName('search')->item(0)->getAttribute('index');
// Trim line if no trim attribute is set or is set to true.
if (!$trim || $trim == 'true') {
$search = trim($search);
}
// Add
$add = $operation->getElementsByTagName('add')->item(0)->textContent;
$trim = $operation->getElementsByTagName('add')->item(0)->getAttribute('trim');
$position = $operation->getElementsByTagName('add')->item(0)->getAttribute('position');
$offset = $operation->getElementsByTagName('add')->item(0)->getAttribute('offset');
if ($offset == '') {
$offset = 0;
}
// Trim line if is set to true.
if ($trim == 'true') {
$add = trim($add);
}
// Log
$log[] = 'CODE: ' . $search;
// Check if using indexes
if ($index !== '') {
$indexes = explode(',', $index);
} else {
$indexes = array();
}
// Get all the matches
$i = 0;
$lines = explode("\n", $modification[$key]);
for ($line_id = 0; $line_id < count($lines); $line_id++) {
$line = $lines[$line_id];
// Status
$match = false;
// Check to see if the line matches the search code.
if (stripos($line, $search) !== false) {
// If indexes are not used then just set the found status to true.
if (!$indexes) {
$match = true;
} elseif (in_array($i, $indexes)) {
$match = true;
}
$i++;
}
// Now for replacing or adding to the matched elements
if ($match) {
switch ($position) {
default:
case 'replace':
$new_lines = explode("\n", $add);
if ($offset < 0) {
array_splice($lines, $line_id + $offset, abs($offset) + 1, array(str_replace($search, $add, $line)));
$line_id -= $offset;
} else {
array_splice($lines, $line_id, $offset + 1, array(str_replace($search, $add, $line)));
}
break;
case 'before':
$new_lines = explode("\n", $add);
array_splice($lines, $line_id - $offset, 0, $new_lines);
$line_id += count($new_lines);
break;
case 'after':
$new_lines = explode("\n", $add);
array_splice($lines, ($line_id + 1) + $offset, 0, $new_lines);
$line_id += count($new_lines);
break;
}
// Log
$log[] = 'LINE: ' . $line_id;
$status = true;
}
}
$modification[$key] = implode("\n", $lines);
} else {
$search = trim($operation->getElementsByTagName('search')->item(0)->textContent);
$limit = $operation->getElementsByTagName('search')->item(0)->getAttribute('limit');
$replace = trim($operation->getElementsByTagName('add')->item(0)->textContent);
// Limit
if (!$limit) {
$limit = -1;
}
// Log
$match = array();
preg_match_all($search, $modification[$key], $match, PREG_OFFSET_CAPTURE);
// Remove part of the the result if a limit is set.
if ($limit > 0) {
$match[0] = array_slice($match[0], 0, $limit);
}
if ($match[0]) {
$log[] = 'REGEX: ' . $search;
for ($i = 0; $i < count($match[0]); $i++) {
$log[] = 'LINE: ' . (substr_count(substr($modification[$key], 0, $match[0][$i][1]), "\n") + 1);
}
$status = true;
}
// Make the modification
$modification[$key] = preg_replace($search, $replace, $modification[$key], $limit);
}
if (!$status) {
// Abort applying this modification completely.
if ($error == 'abort') {
$modification = $recovery;
// Log
$log[] = 'NOT FOUND - ABORTING!';
break 5;
}
// Skip current operation or break
elseif ($error == 'skip') {
// Log
$log[] = 'NOT FOUND - OPERATION SKIPPED!';
continue;
}
// Break current operations
else {
// Log
$log[] = 'NOT FOUND - OPERATIONS ABORTED!';
break;
}
}
}
}
}
}
}
}
// Log
$log[] = '----------------------------------------------------------------';
}
// Log
$ocmod = new Log('ocmod.log');
$ocmod->write(implode("\n", $log));
// Write all modification files
foreach ($modification as $key => $value) {
// Only create a file if there are changes
if ($original[$key] != $value) {
$path = '';
$directories = explode('/', dirname($key));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_MODIFICATION . $path)) {
#mkdir(DIR_MODIFICATION . $path, 0777);
}
}
$handle = fopen(DIR_MODIFICATION . $key, 'w');
fwrite($handle, $value);
fclose($handle);
}
}
// Maintance mode back to original settings
$this->model_setting_setting->editSettingValue('config', 'config_maintenance', $maintenance);
// Do not return success message if refresh() was called with $data
$this->session->data['success'] = $this->language->get('text_success');
$url = '';
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
}
}
I hope it shouwl work for you.
This process is used to refresh the modification when your module installing.
if you need globally this then please tell me I will update you process.
I am using this PHP code to get and display the number of visitors to my site (hit counter).
Currently it is set up to display that number in a single block, i.e. - I would like to display each digit in its own html tag in order to style each number differently.
I have experimented with explode, and substr on the $allHits var, but am not getting good results.
Any Ideas?
<?
/*----------------------------
-------- ++ simPHP ++ --------
A simple PHP hit counter.
Description:
simPHP counts both regular and unique views on multiple
webpages. The stats can be displayed on any PHP-enabled
webpage. You MUST have read/write permissions on files.
Script by Ajay: ajay#scyberia.org
http://scyberia.org
----------------------------*/
/*----------CONFIG----------*/
// NOTE: If you change any config after using simphp,
// remove the old files.
// Relative URL of text file that holds hit info:
$lf_name = "hits.txt";
// Save new log file each month
// 0 = No
// 1 = Yes
$monthly = 1;
// Path to store old files:
// Default for June, 2012:
// oldfiles/6-12.txt
$monthly_path = "oldfiles";
// Count unique hits or all hits:
// 0 = All hits
// 1 = Unique hits
// 2 = Both
$type = 2;
// Text to display
// before all hits.
$beforeAllText = "Site Visitors: ";
// Before unique hits.
$beforeUniqueText = "Unique Visits: ";
// Display hits on this page:
// 0 = No
// 1 = Yes
$display = 1;
// Only change this if you are recording both values.
// Separator for unique and all hits display - use HTML tags! (line break is default)
$separator = "<br \>";
// Default would output:
// Visits: 10
// Unique Visits: 10
/*--------------------------*/
/*--------BEGIN CODE--------*/
$log_file = dirname(__FILE__) . '/' . $lf_name;
//Check for "?display=true" in URL.
if ($_GET['display'] == "true") {
//Show include() info.
die("<pre><? include(\"" . dirname(__FILE__) . '/' . basename(__FILE__) . "\"); ?></pre>");
} else {
//Visit or IP.
$uIP = $_SERVER['REMOTE_ADDR'];
//Check for "hits.txt" file.
if (file_exists($log_file)) {
//Check if today is first day of month
if (date('j') == 10) {
//Ensure that monthly dir exists
if (!file_exists($monthly_path)) {
mkdir($monthly_path);
}
//Check if prev month log file exists already
$prev_name = $monthly_path . '/' . date("n-Y", strtotime("-1 month"));
if (!file_exists($prev_name)) {
//If not, move/rename current file
copy($log_file, $prev_name);
//Create new $toWrite based on CONFIG
//Write file according to CONFIG above.
if ($type == 0) {
$toWrite = "1";
$info = $beforeAllText . "1";
} else if ($type == 1) {
$toWrite = "1;" . $uIP . ",";
$info = $beforeUniqueText . "1";
} else if ($type == 2) {
$toWrite = "1;1;" . $uIP . ",";
$info = $beforeAllText . "1" . $separator . $beforeUniqueText . "1";
}
goto write_logfile;
}
}
//Get contents of "hits.txt" file.
$log = file_get_contents($log_file);
//Get type from CONFIG above.
if ($type == 0) {
//Create info to write to log file and info to show.
$toWrite = intval($log) + 1;
$info = $beforeAllText . $toWrite;
} else if ($type == 1) {
//Separate log file into hits and IPs.
$hits = reset(explode(";", $log));
$IPs = end(explode(";", $log));
$IPArray = explode(",", $IPs);
//Check for visitor IP in list of IPs.
if (array_search($uIP, $IPArray, true) === false) {
//If doesnt' exist increase hits and include IP.
$hits = intval($hits) + 1;
$toWrite = $hits . ";" . $IPs . $uIP . ",";
} else {
//Otherwise nothing.
$toWrite = $log;
}
//Info to show.
$info = $beforeUniqueText . $hits;
} else if ($type == 2) {
//Position of separators.
$c1Pos = strpos($log, ";");
$c2Pos = strrpos($log, ";");
//Separate log file into regular hits, unique hits, and IPs.
$pieces = explode(";", $log);
$allHits = $pieces[0];
$uniqueHits = $pieces[1];
$IPs = $pieces[2];
$IPArray = explode(",", $IPs);
//Increase regular hits.
$allHits = intval($allHits) + 1;
//Search for visitor IP in list of IPs.
if (array_search($uIP, $IPArray, true) === false) {
//Increase ONLY unique hits and append IP.
$uniqueHits = intval($uniqueHits) + 1;
$toWrite = $allHits . ";" . $uniqueHits . ";" . $IPs . $uIP . ",";
} else {
//Else just include regular hits.
$toWrite = $allHits . ";" . $uniqueHits . ";" . $IPs;
}
//Info to show.
$info = $beforeAllText . $allHits . $separator . $beforeUniqueText . $uniqueHits;
}
} else {
//If "hits.txt" doesn't exist, create it.
$fp = fopen($log_file ,"w");
fclose($fp);
//Write file according to CONFIG above.
if ($type == 0) {
$toWrite = "1";
$info = $beforeAllText . "1";
} else if ($type == 1) {
$toWrite = "1;" . $uIP . ",";
$info = $beforeUniqueText . "1";
} else if ($type == 2) {
$toWrite = "1;1;" . $uIP . ",";
$info = $beforeAllText . "1" . $separator . $beforeUniqueText . "1";
}
}
write_logfile:
//Put $toWrite in log file
file_put_contents($log_file, $toWrite);
//Display info if is set in CONFIG.
if ($display == 1) {
}
}
Would using a foreach loop work, like this:
$array_allHits = explode(" ",$allHits);
foreach ($array_allHits as $display_digits) {
echo $display_digits[0];
}
You could use a for-loop.
for ($i = 0; $i < strlen((string) $allHits); $i++) {
echo '<span>' . $allHits[$i] . '</span>';
}
The above code will output <span>{number}</span> for every digit in the hit count.
It will loop through every character in the string, similar as to how array indexes are treated.
$totalHits = 125655;
foreach(str_split((string)$totalHits) as $key => $val) {
echo "<span class='position_{$key}'>{$val}</span>";
}
Add styles in you css as below:
.position_0 {
color: red;
}
.position_1 {
color: blue;
}
.position_2 {
color: yellow;
}
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)) {
I am trying to read text from files in a directory and have it be displayed as description text below an image. I have been able to use the STRIPOS function to separate out each part of the text, except am having trouble with the last section. The last section is titled "Description:" and actually runs into multiple lines. I don't know how to display more than just the line that reads "Description:". I want to print from "Description:" to the end of the file. I will post my code and the text file in this message.
$dirname = 'data';
$dirhandle = opendir($dirname);
$housestextarray = array();
if ($dirhandle)
{
while (false !==($file = readdir($dirhandle)))
{
if ($file !='.' && $file !='..')
{
array_push($housestextarray, $file);
}
}
closedir($dirhandle);
}
sort($housestextarray);
foreach ($housestextarray AS $housedescription)
{
$housetext = '';
$description = '';
$pos = stripos($housedescription, 'house_');
if ($pos === false)
{
//nothing
} else {
$lines_in_file = count(file($housedescription));
$fp=fopen($housedescription,"r");
for ($cntr = 1; $cntr <= $lines_in_file; $cntr++)
{
$cityline=fgets($fp);
$priceline=fgets($fp);
$bedroomsline=fgets($fp);
$bathsline=fgets($fp);
$footageline=fgets($fp);
$realtorline=fgets($fp);
$grabberline=fgets($fp);
$descriptionline=fgets($fp);
//print $cityline;
//print $descriptionline;
//$housetext .= $line;
$citypos = stripos($cityline, 'City:');
if ($citypos === false) //found the city line first time
{
//nothing
}
else
{
$city= $cityline."<br />\n";
//print $city;
}
$pricepos = stripos($priceline, 'Price:');
if ($pricepos === false) //found the city line first time
{
//nothing
}
else
{
$price = $priceline."<br />\n";
//print $price;
}
$bedroomspos = stripos($bedroomsline, 'Bedrooms:');
if ($bedroomspos === false) //found the city line first time
{
//nothing
}
else
{
$bedrooms = $bedroomsline."<br />\n";
//print $bedrooms;
}
$bathspos = stripos($bathsline, 'Baths:');
if ($bathspos === false) //found the city line first time
{
//nothing
}
else
{
$baths = $bathsline."<br />\n";
//print $baths;
}
$footagepos = stripos($footageline, 'Footage:');
if ($footagepos === false) //found the city line first time
{
//nothing
}
else
{
$footage = $footageline."<br />\n";
//print $footage;
}
$realtorpos = stripos($realtorline, 'Realtor:');
if ($realtorpos === false) //found the realtor line first time
{
//nothing
}
else
{
$realtor = $realtorline."<br />\n";
//print $realtor;
}
$grabberpos = stripos($grabberline, 'Grabber:');
if ($grabberpos === false) //found the grabber line first time
{
//nothing
}
else
{
$grabber_formatted = str_replace('Grabber:','', $grabberline);
$grabber = "<h3>".$grabber_formatted."</h3><br />\n";
//print $grabber;
}
$descriptionpos = stripos($descriptionline, 'Description: ');
if ($descriptionpos === false) //found the description line first time
{
//nothing
}
else
{
$description .= $descriptionline."<br />";
//print $description;
}
}
$output = $grabber."<br/>".$city.$bedrooms.$baths;
$output .= $price.$footage.$realtor."<br />";
$output .= "<br />".$description."<br />";
print $output;
}
And here is the text file contents example (one of six files):
City: OceanCove
Price: $950,000
Bedrooms: 5
Baths: 3
Footage: 3000 sq. ft.
Realtor: Shirley Urkiddeng
Grabber: Fantastic Home with a Fantastic View!
Description:
You will never get tired of watching the sunset
from your living room sofa or the sunrise
from your back porch with a view overlooking
the gorgeous coral canyon. Once in a lifetime
opportunity!
UPDATED CODE WITH Branden's help:
function houseDescriptions()
{
//$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
//$dirname = $DOCUMENT_ROOT.'data';
$dirname = 'data';
$dirhandle = opendir($dirname);
$housestextarray = array();
if ($dirhandle)
{
while (false !==($file = readdir($dirhandle)))
{
if ($file !='.' && $file !='..')
{
array_push($housestextarray, $file);
}
}
closedir($dirhandle);
}
sort($housestextarray);
foreach ($housestextarray AS $housedescription)
{
$housetext = '';
$description = '';
$data ="";
$pos = stripos($housedescription, 'house_');
if ($pos === false)
{
//nothing
} else {
$file_handle = fopen($housedescription, "r");
$data = "";
while (!feof($file_handle)) {
$filestrings .= fgets($file_handle);
}
fclose($file_handle);
//You'll need to double check the Regex if it doesn't work.
$data = preg_split('#\b(City:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)\b#', $filestrings);
$city = $data[0];
$bedrooms = $data[1];
$baths = $data[2];
$footage = $data[3];
$realtor = $data[4];
$grabber = $data[5];
$description = $data[6];
$output = $grabber."<br />".$city.$bedrooms.$baths;
$output .= $price.$footage.$realtor."<br />";
$output .= "<br />".$description."<br />";
print $output;
}
}
//return $output;
}
Updated with proper regex
fgets can have issues when trying to get a string out of text file, especially a long string, there may be a line break within it that you may not see in your text editing program. A better way to do this is to get all of the information from the text file and store it in a string, then handle all searches with preg_split(). This code below (assuming my regex is correct, you may need to recheck it) will get all of the variables from the text file for you.
//Append the file location to the file name
$housedescription = $dirname."/".$housedescription;
//Get all contents of the file and save them into $filestrings
$file_handle = fopen($housedescription, "r");
$data = "";
while (!feof($file_handle)) {
$filestrings .= fgets($file_handle);
}
fclose($file_handle);
//Remove any pesky \n newlines that were added by the text file
$filestring = preg_replace("/[\n\r]/","",$filestrings);
//Case Sensitive Regex Search, split the string into an array based on the keywords
$data = preg_split('/(City:|Price:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)/', $filestring, -1, PREG_SPLIT_NO_EMPTY);
//Save all the keywords to vars
$city = "City: ".$data[0];
$bedrooms = "Bedrooms: ".$data[1];
$baths = "Baths: ".$data[2];
$footage = "Footage: ".$data[3];
$realtor = "Realtor: ".$data[4];
$grabber = "Grabber: ".$data[5];
$description = "Description: ".$data[6];
Notice the addition of $filestring = preg_replace("/[\n\r]/","",$filestrings); this will remove any extra new lines that were in the text file so there are no 's where you don't want them.
Of course the absolute ideal would be to store all of your data in a mysql database instead of .txt files, as it is more secure and much faster for data access. But if you prefer .txt try not to open the same file more than once.
Some notes to take from this: How to use Regular Expressions, fopen, fgets, preg_replace, preg_split
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";
}
}