How do I separate and style hit counter digits with php methods? - php

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

Related

PHP file unable to extract and split image from database after made changes to the file

I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.

Count number of files with certain string in it [PHP]

I have a directory with subdirectories in it, I am trying to loop over all of them and also loop on the filenames to count how many time there is a string inside it.
inside of a subdirectory: (i get this output)
../convo/96376/96376-200-2019-03-28-16-15-49.wav
../convo/96376/96376-200-2019-04-01-11-46-52.wav
../convo/96376/96376-200-2019-04-01-11-47-27.wav
../convo/96376/96376-263-2020-01-06-09-40-24.wav
../convo/96376/96376-263-2020-01-06-10-08-16.wav
Here I need to count how many files have (200) or (263) to make a report.
I already isolated the number i need and stored it in a variable ($poste). I just don't know how I am supposed to make a count here since i have nothing to compare. Here is what i got so far
200 and 263 are not hardcoded (I will never know the numbers in advance) and there could be alot more to count
$directory = '../convo/';
$count = 0;
$subDirectories = scandir($directory);
unset($subDirectories[0]);
unset($subDirectories[1]);
foreach ($subDirectories as $subDirectory) {
echo '<h2>' . $subDirectory . '</h2>';
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
}
}
if you just need the count for 200 & 263, try this:
$directory = '../convo/';
$count = 0;
$subDirectories = scandir($directory);
unset($subDirectories[0]);
unset($subDirectories[1]);
foreach ($subDirectories as $subDirectory) {
echo '<h2>' . $subDirectory . '</h2>';
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
if (in_array($poste,["200","263"])) {
$count++;
}
}
}
Just add a test for the values and put a counter here:
$posteCounter = 0;
foreach (glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$poste = $poste_explode[1];
if(200 == $poste || 263 == $poste) {
$posteCounter++;
}
Or you could count each one so that you have separate values which can be totaled:
//set variables outside the loop to hold the values
$_200 = 0;
$_263 = 0;
if(200 == $poste) {
$_200++;
} elseif (263 == $poste) {
$_263++;
}
EDIT Based on comments provided by the OP:
In order to find all of the poste values and then count you will have to loop twice through your directory. The first loop will build an array:
foreach(glob($directory . $subDirectory . '/*') as $file) {
$poste_explode = explode('-', $file);
$postes[] = $poste_explode[1]; // create and populate $postes array
}
Now you can loop through the $postes array and count files with those values, setting up a variable variable (there are likely better ways, but a lack of coffee isn't bringing them to mind) for each of the poste numbers. Here is an EXAMPLE of an experiment in progress
$filenames = ['a-2-foo', 'b-2-bar', 'c-3-glorp'];
foreach($filenames as $filename){
$poste_explode = explode('-', $filename);
$postes[] = $poste_explode[1];
if(!isset(${'poste_' . $poste_explode[1]})){
${'poste_' . $poste_explode[1]} = 0; // set up variable variable
}
}
var_dump( get_defined_vars() );
print_r($postes);
foreach($postes as $poste){
echo $poste . "\n";
foreach($filenames as $filename){
$poste_explode = explode('-', $filename);
if($poste == $poste_explode[1]){
echo ${'poste_' . $poste} . "\n";
${'poste_' . $poste}++; // variable variable
}
}
}

PHP Limit number of results per page

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

Strict standard error in PHP

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)) {

php - get name of current page from url and reformat string

I have the following code that (1) gets the page / section name from the url (2) cleans up the string and then assigns it to a variable.
I was wondering if there are any suggestions to how I can improve this code to be more efficient, possibly less if / else statements.
Also, any suggestion how I can code this so that it accounts for x amount of sub-directories in the url structure. Right now I check up to 3 in a pretty manual way.
I'd like it to handle any url, for example: www.domain.com/level1/level2/level3/level4/levelx/...
Here is my current code:
<?php
$prefixName = 'www : ';
$getPageName = explode("/", $_SERVER['PHP_SELF']);
$cleanUpArray = array("-", ".php");
for($i = 0; $i < sizeof($getPageName); $i++) {
if ($getPageName[1] == 'index.php')
{
$pageName = $prefixName . 'homepage';
}
else
{
if ($getPageName[1] != 'index.php')
{
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', $getPageName[1]));
}
if (isset($getPageName[2]))
{
if ( $getPageName[2] == 'index.php' )
{
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', $getPageName[1]));
}
else
{
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', $getPageName[2]));
}
}
if (isset($getPageName[3]) )
{
if ( $getPageName[3] == 'index.php' )
{
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', $getPageName[2]));
}
else
{
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', $getPageName[3]));
}
}
}
}
?>
You are currently using a for-loop, but not using the $i iterator for anything - so to me, you could drop the loop entirely. From what I can see, you just want the directory-name prior to the file to be the $pageName and if there is no prior directory set it as homepage.
You can pass $_SERVER['PHP_SELF'] to basename() to get the exact file-name instead of checking the indexes, and also split on the / as you're currently doing to get the "last directory". To get the last directory, you can skip indexes and directly use array_pop().
<?php
$prefixName = 'www : ';
$cleanUpArray = array("-", ".php");
$script = basename($_SERVER['PHP_SELF']);
$exploded = explode('/', substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/')));
$count = count($exploded);
if (($count == 1) && ($script == 'index.php')) {
// the current page is "/index.php"
$pageName = $prefixName . 'homepage';
} else if ($count > 1) {
// we are in a sub-directory; use the last directory as the current page
$pageName = $prefixName . trim(str_replace($cleanUpArray, ' ', array_pop($exploded)));
} else {
// there is no sub-directory and the script is not index.php?
}
?>
In the event that you want a more breadcumbs-feel, you may want to keep each individual directory. If this is the case, you can update the middle if else condition to be:
} else if ($count > 1) {
// we are in a sub-directory; "breadcrumb" them all together
$pageName = '';
$separator = ' : ';
foreach ($exploded as $page) {
if ($page == '') continue;
$pageName .= (($pageName != '') ? $separator : '') . trim(str_replace($cleanUpArray, ' ', $page));
}
$pageName = $prefixName . $pageName;
} else {
I found this code very helpful
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') ===
FALSE ? 'http' : 'https'; // Get protocol HTTP/HTTPS
$host = $_SERVER['HTTP_HOST']; // Get www.domain.com
$script = $_SERVER['SCRIPT_NAME']; // Get folder/file.php
$params = $_SERVER['QUERY_STRING'];// Get Parameters occupation=odesk&name=ashik
$currentUrl = $protocol . '://' . $host . $script . '?' . $params; // Adding all
echo $currentUrl;

Categories