Sort result alphabetically - php

function printAll($dirName)
{
if (empty($leid)) { $leid = "1"; }
$root = $_SERVER['DOCUMENT_ROOT'];
$site = $_GET['site'];
$user = $_GET['user'];
$tag = "";
$dirs=array($dirName);
$files=array();
while($dir=array_pop($dirs)){
$handle=opendir($dir);
while($file=readdir($handle)){
if($file!='.' && $file!='..'){
$dest=$dir.'/'.$file;
$userid = str_replace("$root/", "", $dir);
$userid = str_replace("dl/$site","",$userid);
$userid = str_replace("/","",$userid);
if(is_file($dest)){
$files[]=$file;
$titrepost = htmlspecialchars($file);
$downloadlink = "$dest";
$downloadlink = str_replace("$root/", "", $downloadlink);
$za = new ZipArchive();
$za->open($downloadlink);
$leid = $leid + 1;
echo "<br>
<b>File = $file</b><br>
Userid = $userid
<br>";
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune = basename( $stat['name'] );
echo "$toune <br>";
}
} else {
$dirs[]=$dest;
}
}
}
}
return $files;
}
$site = $_GET['site'];
$currentdir = getcwd();
$source = "$currentdir/dl/$site";
if (!empty($user)) {
$source = "$currentdir/dl/$site/$user";
}
printAll($source);
This script will list all files inside a ZIP archive then echo the name of each files.
Now i'm having some trouble figuring how to sort the files names ($toune) alphabetically
Here's what i tried:
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$toune_arr[] = basename( $stat['name'] );
}
asort($toune_arr);
print_r($toune_arr);
But it doesn't work for this code, $toune_arr won't empty after each zip file is listed so each time the script output the filelist it contains the files of the previous zip archives.

Just reset your array in the begining of your function:
function printAll($dirName)
{
$toune_arr = array();
...

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.

Php code to read multiple file and return the last line

Am trying to read multiple file and display the last line of each file but my code is not working very fine i don't know what am doing wrong.
<?php
if(isset($_GET['fid'], $_GET['timestamp']) && !empty($_GET['fid'])){
$lastmodif = isset( $_GET['timestamp']) ? $_GET['timestamp']: 0 ;
$fl_session = preg_replace("/[^0-9=]+/", "", $_GET['fid']);
if(strpos($fl_session, '==') !== false) {
$fl_session = explode('==', $fl_session);
foreach($fl_session as $fn){
$filename = dirname(__FILE__).'/logs/foo_'.$fn.'.txt';
$currentmodif = filemtime($filename);
while($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
if(file_exists($filename)){
$myfile = fopen($filename, "r") or die("Unable to load readme file!");
if($myfile){
$log = fread($myfile, filesize($filename));
fclose($myfile);
}
$log = explode("\n", trim($log));
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
foreach ($log as $logline) {
$response['id'] = trim($logline['0']);
$response['type'] = trim($logline['3']);
}
}
$response[$fn]['timestamp'] = $currentmodif;
//$response['timestamp'] = $currentmodif;
//var_export($response);
echo json_encode($response);
}
}
}
In my GET['fid'] parameter it contain something like this 12345==09765==87765, so i will explode it and loop on every id to locate the file name foo_12345.txt, foo_09765.txt, foo_87765.txt. This current code returned something like this from one txt file and ignored other files.
{ "id":"58287469", "type":"client", "8942180223":{
"timestamp":1505409432 } } { "id":"53094615", "type":"client",
"8942180223":{ "timestamp":1505409432 }, "4582422934":{
"timestamp":1505409420 } }

Convert PHP script in Powershell script

I have to convert a PHP script in Powershell script.
I have current PHP script:
<?php
// read text file
$File = fopen("file.txt", "r") or die("Unable to open file!");
$typePers = array("Personale Viaggiante","Personale Interno");
$excludeFields = array("IT0006","IT0017","IT0077","Personale Viaggiante","Personale Interno","IT0105");
$emptyValue = "NaN";
$rowfinal = "";
// Output one line until end-of-file
while(!feof($File)) {
$row = explode(";",fgets($File));
$substring = "IT0006;IT0017;";
// left string
$lstr = "";
// right string
$rstr = "";
$type = array_intersect($row, $typePers);
$keys = array_keys($type);
if($keys == null) $type = $emptyValue;
else $type = $row[$keys[0]];
$j = 0;
for($i=0; $i<count($row); $i++){
if(in_array($row[$i],$excludeFields)){
unset($row[$i]);
$j++;
}
}
for($i=0; $i<22;$i++)$lstr .= $row[$i].";";
foreach($row as $k => $v)
if($k > 22)if(!empty($v))$rstr .= $v.";";
$rstr = substr($rstr,0,-1);
$substring .= $type;
$substring .= ";IT0077;NaN;IT0105;";
$rowfinal .= $lstr.$substring.$rstr;
}
$file = 'test.txt';
// Write the contents back to the file
file_put_contents($file, $rowfinal);
fclose($sapFile);
?>
I started writing this script in Powershell, but it is incomplete.
$File = Get-Content "file.txt"
$FilePath = "dump.txt"
$typePers = #("Personale Viaggiante","Personale Interno")
$excludeFields = #("IT0006","IT0017","IT0077","Personale Viaggiante","IT0105","Personale Interno")
$emptyValue = "NaN"
$rowfinal = ""
foreach($line in $File) {
[System.Collections.ArrayList]$row = $line -split ";"
$substring = "IT0006;IT0017;"
$lstr = ""
$rstr = ""
$ityp = -1;
for($i=0; $i -lt $row.Count; $i++){
if($typePers -contains $row[$i] ){
$ityp = $i
}
}
if($ityp -eq "-1"){
$type = "NaN"
}else{
$type = $row[$ityp]
}
$j = 0;
for($i=0; $i -lt $row.Count; $i++){
if($excludeFields -contains $row[$i]){
$row.RemoveAt($i)
$j++;
}
}
for($i=0; $i -lt 22;$i++) {
$lstr += $row[$i]+";"
}
$k = 0;
ForEach($v in $row) {
if($k -gt 22) {
if($v -ne ""){
$rstr += $v+";"
}
}
$k++
}
$rstr = $rstr.Substring(0,$rstr.Length-1)
$substring += $type
$substring += ";IT0077;NaN;IT0105;";
$rowfinal += $lstr+$substring+$rstr+"`r`n"
}
$rowfinal | Out-File -FilePath $FilePath
I have only problem with Remove method.
When I have IT0006 value in array, I have IT0105 duplicated...
To end, I have to add header columns for CSV file.
For example, I would to define an array with header:
$header = #('column1','column2',...,'column_n');
and add header at the file to export in CSV.

Rename the files while uploading

I am trying to rename the files while uploading, but it's not renaming as I expected. Just want to add the date and the time front of the name.
Attaching the code below.
if(isset($_FILES['img_ct_1'])){
$today = date("Ymd");
//prepare url
$temp_path = CDN_URL.'photos/';
$name_array = $_FILES['img_ct_1']['name'];
$tmp_name_array = $_FILES['img_ct_1']['tmp_name'];
$type_array = $_FILES['img_ct_1']['type'];
$size_array = $_FILES['img_ct_1']['size'];
$error_array = $_FILES['img_ct_1']['error'];
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/photos/';
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i],$upload_dir.time().$name_array[$i])){
print_r ($name_array[$i]);
$array['path'] = $temp_path.$newfilename;
$array['success'] = true ;
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
Try this way:
for($i = 0; $i < count($tmp_name_array); $i++){
$file = $today.time().$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $upload_dir . $file)){
print_r ($name_array[$i]);
$array['path'] = $temp_path.$newfilename;
$array['success'] = true ;
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}

Removing the filename extension from a string

I'm creating a breadcrumb script like this:
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
echo ' » '.$dirlist[$i].'';
?>
If form url is http:// domain /school/students.php,
the result is like this: ( home » school » students.php )
Question: How to eliminate the extension .php file students.php,
be like this ( home » school » students ) ??
No matter how long is the extension or its name, this will work :
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++) {
$result = $dirlist[$i];
if ($i == ($count-1)) { // if last element
$lastDot = strripos($result,'.') ;
$result = substr($result,0,$lastDot) ;
}
echo ' » '.$result.'';
}
?>
how about using string replacement?
Here's a bit of code that may point you in the right direction, replacing your for loop.
for ($i = 0; $i < $count; $i++) {
$label = str_replace('.php', '', $dirlist[$i]);
echo ' » '.$label.'';
}
Try deducting string
<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1))
$dirlist = explode('/', $location);
else
$dirlist = array();
$count = array_push($dirlist, basename($_SERVER['PHP_SELF']));
$address = 'http://'.$_SERVER['HTTP_HOST'];
echo 'home';
for ($i = 0; $i < $count; $i++)
if(!isset($dirlist[$i+1]))
{
echo ' » '.substr($dirlist[$i],0,-4).'';
}
else
{
echo ' » '.$dirlist[$i].'';
}
?>
this will work.

Categories