find the last created image file with remote or external link - php

HI guys i have some jpeg files with this format:
123-1.jpeg ,123-2.jpeg ,123-3.jpeg ,123-4.jpeg ....
This files located on my VPS and i need to find and show the lasted file by remote (my means external web link ).
i have problem how i can read files with such name format i tried this is not work:
$screnshot_url = "http://8.7.6.5/screenshots/123-*.jpeg ";
$filemtime = filemtime_remote($screnshot_url);
$files = $screnshot_url;
$files = array_combine($files, array_map($filemtime, $files));
arsort($files);
$img = key($files);
function filemtime_remote($uri)
{
$uri = parse_url($uri);
$handle = #fsockopen($uri['host'],80);
if(!$handle)
return 0;
fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
$result = 0;
while(!feof($handle))
{
$line = fgets($handle,1024);
if(!trim($line))
break;
$col = strpos($line,':');
if($col !== false)
{
$header = trim(substr($line,0,$col));
$value = trim(substr($line,$col+1));
if(strtolower($header) == 'last-modified')
{
$result = strtotime($value);
break;
}
}
}
fclose($handle);
return $result;
}

Related

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

ftp_nlist ... how to know if it's a file or a folder?

I'm writing a script for download from FTP..
In the form I need to show files and folders..
With ftp_nlist, they come all togethers but I want to know who's who ..
I can't find an easy way to do this:
$contents = ftp_nlist($connection, $rep);
$dossiers =array();
$fichiers = array();
foreach($contents as $content){
//if folder
if (is_folder($content)) $dossiers[] = $content;
//si file
if(is_filex($content)) $fichiers[] = $content;
}
Of course is_file and is_dir don't work with distant files...
I've find something with ftp_rawlist and the size of each result..
like this:
if($result['size']== 0){ //is dir }
But in case of an empty file???
So what id the way to know what is a folder and what is a file??
Thanks!
I've had the same problem and this was my solution:
$conn = ftp_connect('my_ftp_host');
ftp_login($conn, 'my_user', 'my_password');
$path = '/';
// Get lists
$nlist = ftp_nlist($conn, $path);
$rawlist = ftp_rawlist($conn, $path);
$ftp_dirs = array();
for ($i = 0; $i < count($nlist) - 1; $i++)
{
if($rawlist[$i][0] == 'd')
{
$ftp_dirs[] = $nlist[$i];
}
}
I know the above code could be optimised and do just one FTP request instead of two but for my purposes this did the work.
For anyone looking for a cleaner solution, I've found a script to parse ftp_rawlist in this LINK:
Function
function parse_ftp_rawlist($List, $Win = FALSE)
{
$Output = array();
$i = 0;
if ($Win) {
foreach ($List as $Current) {
ereg('([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)', $Current, $Split);
if (is_array($Split)) {
if ($Split[3] < 70) {
$Split[3] += 2000;
}
else {
$Split[3] += 1900;
}
$Output[$i]['isdir'] = ($Split[7] == '');
$Output[$i]['size'] = $Split[7];
$Output[$i]['month'] = $Split[1];
$Output[$i]['day'] = $Split[2];
$Output[$i]['time/year'] = $Split[3];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : false;
}
else {
foreach ($List as $Current) {
$Split = preg_split('[ ]', $Current, 9, PREG_SPLIT_NO_EMPTY);
if ($Split[0] != 'total') {
$Output[$i]['isdir'] = ($Split[0] {0} === 'd');
$Output[$i]['perms'] = $Split[0];
$Output[$i]['number'] = $Split[1];
$Output[$i]['owner'] = $Split[2];
$Output[$i]['group'] = $Split[3];
$Output[$i]['size'] = $Split[4];
$Output[$i]['month'] = $Split[5];
$Output[$i]['day'] = $Split[6];
$Output[$i]['time/year'] = $Split[7];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : FALSE;
}
}
Usage
// connect to ftp server
$res_ftp_stream = ftp_connect('my_server_ip');
// login with username/password
$login_result = ftp_login($res_ftp_stream, 'my_user_name', 'my_password');
// get the file list for curent directory
$buff = ftp_rawlist($res_ftp_stream, '/');
// parse ftp_rawlist output
$result = parse_ftp_rawlist($buff, false);
// dump result
var_dump($result);
// close ftp connection
ftp_close($res_ftp_stream);

Sphider indexing (pdf, xls, doc,...) strange lambda characters in mysql

im using sphider, to create some kind of fulltext search above shared network drive, im almost done, but i get stucked on this. Im indexing txt,pdf, xls, etc file content, but i noticed, that in mysql DB i have stored some characters called lambda_[number] or some combinations with other words, but always its lambda word. It sounds like some unprintable character, or other little grinch to me.
So i decided to remove this pain by utf8_encode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $fileOutput)); but without succes. My DB collation is utf8_general_ci. Any ideas how to escape this little troll?
and whole file parser code for better understand what am i doing and all parsing functions, but issue will be probably with escaping.
function readTextFile($filePath) {
$fileContent = file_get_contents($filePath);
return $fileContent;
}
// -------------- START PARSE MS OFFICE FILES BLOCK
function parsePPT($filename) {
// This approach uses detection of the string "chr(0f).Hex_value.chr(0x00).chr(0x00).chr(0x00)" to find text strings, which are then terminated by another NUL chr(0x00). [1] Get text between delimiters [2]
$fileHandle = fopen($filename, "r");
$line = #fread($fileHandle, filesize($filename));
$lines = explode(chr(0x0f), $line);
$outtext = '';
foreach ($lines as $thisline) {
if (strpos($thisline, chr(0x00) . chr(0x00) . chr(0x00)) == 1) {
$text_line = substr($thisline, 4);
$end_pos = strpos($text_line, chr(0x00));
$text_line = substr($text_line, 0, $end_pos);
$text_line = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t#\/\_\(\)]/", "", $text_line);
if (strlen($text_line) > 1) {
$outtext.= substr($text_line, 0, $end_pos) . "\n";
}
}
}
return $outtext;
}
function pptx2text($filename) {
$zip = new ZipArchive;
// Open received archive file
if (true === $zip->open($filename)) {
// If done, search for the data file in the archive
$dia = 1;
$data = array();
$output = "";
while (($index = $zip->locateName("ppt/slides/slide$dia.xml") ) !== false) {
$data[$dia] = $zip->getFromIndex($index);
$xml = str_replace("</a:t>", " </a:t>", $data[$dia]);
$output.=$xml;
$dia++;
}
$zip->close();
return strip_tags($output);
} else {
return "";
}
}
function xlsx2text($filename) {
$zip = new ZipArchive;
// Open received archive file
if (true === $zip->open($filename)) {
// If done, search for the data file in the archive
$dia = 1;
$data = array();
$output = "";
while (($index = $zip->locateName("xl/worksheets/sheet$dia.xml") ) !== false) {
$data[$dia] = $zip->getFromIndex($index);
//$pageContent .= $data[$dia];
$xml = str_replace("</a:t>", " </a:t>", $data[$dia]);
$output.=$xml;
$dia++;
}
$zip->close();
return strip_tags($output);
} else {
return "";
}
}
function docx2text($filename) {
return readZippedXML($filename, "word/document.xml");
}
function readZippedXML($archiveFile, $dataFile) {
// Create new ZIP archive
$zip = new ZipArchive;
// Open received archive file
if (true === $zip->open($archiveFile)) {
// If done, search for the data file in the archive
if (($index = $zip->locateName($dataFile)) !== false) {
// If found, read it to the string
$data = $zip->getFromIndex($index);
$data = str_replace("></", "> </", $data);
// Close archive file
$zip->close();
// Load XML from a string
// Skip errors and warnings
$xml = new DOMDocument();
$xml->loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
//$xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
// Return data without XML formatting tags
return strip_tags($xml->saveXML());
return $xml;
}
$zip->close();
}
// In case of failure return empty string
return "";
}
function parsePDF($fileName){
require('tools/pdf2text.php');
$pdfClass = new PDF2Text();
$pdfClass->setFilename($fileName);
$pdfClass->decodePDF();
return $pdfClass->output();
}
// -------------- END PARSE MS OFFICE FILES BLOCK
$fileType = filter_input(INPUT_GET, 'fileType');
$filePath = filter_input(INPUT_GET, 'filePath');
$serverUri = $_SERVER['REQUEST_URI'];
$_SERVER['REQUEST_URI'] = "testval";
$secondUri = $_SERVER['REQUEST_URI'];
$fileTitle = trim(str_replace("\\", " ",$filePath));
$fileOutput = "<html><head><title>".$fileTitle."</title></head><body>";
switch ($fileType) {
case 'txt':
$fileOutput .= readTextFile($filePath);
break;
case 'pptx':
$fileOutput .= pptx2text($filePath);
break;
case 'docx':
$fileOutput .= docx2text($filePath);
break;
case 'xlsx':
$fileOutput .= xlsx2text($filePath);
break;
case 'ppt':
$fileOutput .= parsePPT($filePath);
break;
case 'pdf':
$fileOutput .= parsePDF($filePath);
break;
default:
return false;
}
$fileOutput .= "</body>";
echo utf8_encode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $fileOutput));

Stuck with file_get_contents

guys. Please help me to find out the problem. I have one script on my ftvgirlsbay.com site:
<?php
define('C', 16); // NUMBER OF ROWS
define('D', 6); // NUMBER OF CELLS
$file = #file_get_contents('http://ftvgirlsbay.com/design/tables/gals.txt');
if($file === FALSE) {
echo "<h2>Make file gals.txt with data!</h2>";
return FALSE;
}
$file = explode("\r\n", $file);
$thumbs = array();
while(list(,$el) = each($file)) {
$el = explode('|', $el);
if(isset($el[0]) && isset($el[1]))
$thumbs[] = array($el[0], $el[1]);
}
//print_r($thumbs);
$size = sizeof($thumbs);
if($size < C*D) {
echo "<h2>More data needed. You have $size, you need ".C*D."!</h2>";
return FALSE;
}
$range = range(0, $size - 1);
shuffle($range);
//print_r($range);
?>
<table align=center>
<?php
$num = 0;
for($i = 0; $i < C; $i++) {
echo '<tr align=center>'."\r\n";
for($k = 0; $k < D; $k++) {
echo '<td>FTV '.$thumbs[$range[$num]][0].' Gallery </td>'."\r\n";
$num++;
}
echo '</tr>'."\r\n";
}
?>
</table>
Result of this script:
"More data needed. You have 1, you need 96!"
( http://ftvgirlsbay.com/random_scripts/test.php )
If this part
$file = #file_get_contents('http://ftvgirlsbay.com/design/tables/gals.txt');
change to
$file = #file_get_contents('http://sexsticker.info/ftvgirlsbay.com/pictable/gals.txt');
it works just fine
( http://ftvgirlsbay.com/random_scripts/test2.php )
So if I links to the .txt file on my server's side script reads only 1 line.
If I links to the .txt on the remote server - script works wilh all lines
I figured out your problem and was able to replicate the issue.
The issue is with the \r in
$file = explode("\r\n", $file);
Remove the \r
$file = explode("\n", $file);
Both servers might be different. One may be on a Linux, while the other on a Windows server.

Search and open for file

I have a script that I have made so far which looks for a specified file in the current directory and if it isn't there, it will go up a directory and search again.
If the file exists the script works fine, however if it doesn't it goes on until the script is cancelled for being longer than 30 seconds, even with a counter to limit the executions in place.
$path = 'log.log';
$file_exists = 0;
$search_count = 0;
$search_limit = 3;
while($file_exists == 0) {
while($search_count < $search_limit) {
if(file_exists($path)) {
$file_exists = 1;
$search_count = $search_limit + 1;
$resource = fopen($path, "r");
while (!feof($resource)) {
echo fgetss($resource);
}
fclose($resource);
} else {
$path = '../'.$path;
$search_count++;
}
}
}
I think you're looking for something like this:
$path = 'log.log';
$file_exists = false;
$search_count = 0;
$search_limit = 3;
while (!$file_exists and $search_count < $search_limit) {
if(file_exists($path)) {
$file_exists = true;
$resource = fopen($path, "r");
while (!feof($resource)) {
echo fgetss($resource);
}
fclose($resource);
} else {
$path = '../'.$path;
$search_count++;
}
}
EDIT: if you're just after the content of the log.log-file you can use file_get_contents($path) like this:
...
if(file_exists($path)) {
$file_exists = true;
$contents = file_get_contents($path);
echo $contents;
}
...
Find more info about the file_get_contents method here.
while($file_exists == 0)
will be infinite, because you are only setting $file_exists to 1 when the file is found
suppose the file isnt there, then the internal loop will run only for three times, but the outer loop will run infinitely (although without any executable statements)
EDIT:
you could merge the conditions as
while($file_exists == 0 && $search_count < $search_limit) {
//your entire code
}

Categories