show an array() into table - php

My primary task was, to validate that the backlinks of my website is there or not which is validated through a some.txt file. I have done it but now the problem is, I want the urls in table format.
My script is this
$needle = $_GET['utext'];
$file = $_GET['ufile'];
$source = file_get_contents($file);
$new = explode("\n",$source);
foreach ($new as $check)
{
$a = file_get_contents(trim($check));
if (strpos($a,$needle))
{
$found[] = $check;
}
else
{
$notfound[] = $check;
}
}
echo "Matches that were found: \n ".implode("\n",$found)."\n";
echo "Matches that were not found \n". implode("\n",$notfound);

Related

PHP Add or Edit line in text File

I'm trying to search a text file, if a line contains a specific key ID I want to update the entire line, if not add a new line.
So based on this text file :
admin,1234,ID1345,NW
staff,1325,ID1001,NE
staff,2157,ID2003,SW
staff,8519,ID3001,NS
I want to search for ID1345 and then update that line only, the other lines stay exactly as they are. If no lines contain ID1345 then add a new line to the text file.
So far I've got:
$search = 'ID1345';
$result = 'admin,6698,ID1345,OP';
$reading = fopen('myfile', 'r');
$writing = fopen('myfile.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line, $search)) {
$line = "$result\n";
$replaced = true;
}
fputs($writing, $line);
}
if (!$replaced) fputs($writing, "$result\n");
fclose($reading); fclose($writing);
rename('myfile.tmp', 'myfile');
This seems to work for the find and replace, but if the line doesn't exist it keeps adding it not just once.
I know this is due to the if (!$replaced) line, but I'm not sure how to do this.
The example above is small, but there could be a few thousand entries in the file..
Thanks
function file_properties($fileProperties) {
$result = array();
$lines = split("\n", $fileProperties);
$key = "";
$isWaitingOtherLine = false;
foreach($lines as $i=>$line) {
if(empty($line) || (!$isWaitingOtherLine && strpos($line,"#") === 0)) continue;
if(!$isWaitingOtherLine) {
$key = substr($line,0,strpos($line,'='));
$value = substr($line,strpos($line,'=') + 1, strlen($line));
} else {
$value .= $line;
}
/* Check if ends with single '\' */
if(strrpos($value,"\\") === strlen($value)-strlen("\\")) {
$value = substr($value, 0, strlen($value)-1)."\n";
$isWaitingOtherLine = true;
} else {
$isWaitingOtherLine = false;
}
$result[$key] = $value;
unset($lines[$i]);
}
return $result;
}
This will read and write values to file with any extension like .env in Laravel or anything *.properties in Java

Need to change case of a string - PHP

$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);

PHP, listing things twice

I'm using this script to list a few Twitch.tv streams and their status (offline or online).
If there are no online streams found, I want it to display a text saying that all are offline.
Code that checks if the added streams are online:
//get's member names from stream url's and checks for online members
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
//checks if player streams are online
function onlinecheck($online, $viewers)
{
//If the variable online is not equal to null, there is a good change this person is currently streaming
if ($online != null)
{
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
Full code:
<html>
<head>
<title>Streamlist</title>
</head>
<body>
<?php
$members = array("ncl_tv");
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($members as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
$channels = array();
for ($i = 0; $i < count($members); $i++) {
if (isset($json_array[$i])){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
}
unset($value);
unset($i);
function onlinecheck($online, $viewers) {
if ($online != null) {
echo ' <strong>'.$online.'</strong>';
echo '&nbsp <img src="/images/online.png"><strong> Status:</strong> Online! </br>';
echo '<img src="/images/viewers.png"><strong>Viewers:</strong> &nbsp' .$viewers.'</br>';
}
}
$alloffline = "All female user streams are currently offline.";
function signin($person){
if($person != null){
return $person;
}
?>
</body>
</html>
............................................................................................................................................................................
Is it because your $userGrab URL contains usernames twice? This is the URL whose contents you're retrieving:
http://api.justin.tv/api/stream/list.json?channel=painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv,painuser,ZombieGrub,Nathanias,Youbetterknowme,ncl_tv
Having looked at the response, it doesn't look like it's causing the problem. The strange URL is a result of you appending to the $userGrab string in the first foreach loop, after you've already added them with the implode() function call before. I think twitch.tv is rightly ignoring duplicate channels.
If all the values in $checkedOnline are null, everyone is offline. Put this at the end of your first code sample:
$personOnline = false;
foreach($checkedOnline as $person) {
if($person !== null) {
$personOnline = true;
break;
}
}
if(!$personOnline) {
echo 'No one is online';
}
else {
//there is at least someone online
}

How to pick part of text file in directory and print section with STRIPOS in PHP?

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

PHP search function on website. (easy)

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

Categories