Stuck with file_get_contents - php

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.

Related

How to apply code on multiple files at once?

I couldn't find a solution to this. I'm sorry if this is a silly question.
I have 4 log files and I need to remove all log except last 10 lines.
I'm able to do it for 1 file but how to apply it on 4 files using once simple php code?
My current code:
<?php
$lines_array = file("log.txt");
$lines = count($lines_array);
$new_output = "";
for ($i=$lines - 10; $i < $lines; $i++) {
$new_output .= $lines_array[$i];
}
$filename = "log.txt";
file_put_contents($filename,$new_output);
What is the best way to achieve this?
Functional programming to the rescue:
function rotate(string $filename)
{
$lines_array = file($filename);
$lines = count($lines_array);
$new_output = "";
for ($i=$lines - 10; $i < $lines; $i++) {
$new_output .= $lines_array[$i];
}
file_put_contents($filename,$new_output);
}
rotate('log1.txt');
rotate('someOtherLog.txt');
rotate('third/log/file.txt);
//etc.
// or,
$logs = [
'log1.txt',
'someOtherLog.txt',
'third/log/file.txt'
];
foreach($logs as $file) {
rotate($file);
}
This allows you to write the code for rotating your logs one time, which makes your code better by being DRY (Don’t Repeat Yourself)
List your logfiles in an array, and loop over it, rewriting the log files as you go:
$logs = [
'log1.txt',
'log2.txt',
'log3.log'
];
foreach($logs as $log) {
// Only do this if we read the file.
if ($logData = file($log)) {
// array_slice takes a portion of the array
file_put_contents($log, array_slice($logData,-10));
}
}
Please try this code:
<?php
$fp = fopen("log.txt","ab+");
$data = fread($fp,filesize("log.txt"));
$data_array = explode("\n",$data);
$new_data = array();
for($i = count($data_array) - 1; $i >= count($data_array) - 10;$i--)
{
array_push($new_data , $data_array[$i]);
}
fclose($fp);
$new_data_array = array_reverse($new_data);
$data = implode("\n",$new_data_array);
$fp = fopen("log.txt","w");
fwrite($fp,$data);
fclose($fp);
?>

PHP Find and delete specific line set in large text file

I am trying to remove certain line set based on ipaddress in large text file having approx. 60,000 lines. Each line set starting from MaxBytes[ipaddress] and ending with </TABLE> and a blank line present between each line set. There is variation in table lines in text file.
Sample line set :
MaxBytes[192.168.1.1]: 10000 <--start line
<TABLE>
<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
<TR><TD>Max Speed:</TD> <TD>300</TD></TR>
</TABLE> <-- end line (Need to delete lines from start to end line)
I am trying to find start line using below codes (supported by Yerke) but unable to find out way to find next line number containing </table> tag. I need to find out start and end line number of line set containing specific ipaddress and delete it.
I am a beginner in coding, so I might need extended guidance.
codes :
<?php
$dir = "example.txt";
$searchstrt = "192.168.1.1";
///// find details
function find_line_number_by_string($dir, $searchstrt, $case_sensitive=false ) {
$line_number = [];
if ($file_handler = fopen($dir, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$searchstrt = strtolower($searchstrt);
$line = strtolower($line);
}
//find the string and store it in an array
if(strpos($line, $searchstrt) !== false){
$line_number[] = $i;
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or dir";
}
return $line_number;
}
$line_number = find_line_number_by_string($dir, $searchstrt);
var_dump($line_number);
?>
Sample example.txt
MaxBytes[192.168.1.1]: 10000
<TABLE>
<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
<TR><TD>Max Speed:</TD> <TD>300</TD></TR>
</TABLE>
MaxBytes[192.168.1.2]: 30000
<TABLE>
<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
<TR><TD>Max Speed:</TD> <TD>300</TD></TR>
<TR><TD>Name:</TD> <TD>ABC</TD></TR>
</TABLE>
MaxBytes[192.168.1.3]: 10000
<TABLE>
<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
<TR><TD>Max Speed:</TD> <TD>200</TD></TR>
<TR><TD>Location:</TD> <TD>INDIA</TD></TR>
</TABLE>
I found some workaround to get line numbers of line set containing desired ip address. Does anyone suggest better way to do it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$dir = "example.txt";
$searchstrt = "192.168.1.2";
$searchend = "</TABLE>";
///// find details
function find_line_number_by_string($dir, $searchstrt, $case_sensitive=false ) {
$line_number = [];
if ($file_handler = fopen($dir, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$searchstrt = strtolower($searchstrt);
$line = strtolower($line);
}
//find the string and store it in an array
if(strpos($line, $searchstrt) !== false){
$line_number[] = $i;
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or dir";
}
return $line_number;
}
$line_number = find_line_number_by_string($dir, $searchstrt);
//var_dump($line_number);
$start = $line_number[0];
////////////////////////
function find_line_number_by_string1($dir, $searchend, $case_sensitive=false, $start) {
$line_number1 = [];
if ($file_handler1 = fopen($dir, "r")) {
$i = $start;
// $i = 0;
while ($line1 = fgets($file_handler1)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$searchend = strtolower($searchend);
$line1 = strtolower($line1);
}
//find the string and store it in an array
if(strpos($line1, $searchend) !== false){
$line_number1[] = $i;
}
}
fclose($file_handler1);
}else{
return "File not exists, Please check the file path or dir";
}
return $line_number1;
}
$line_number1 = find_line_number_by_string1($dir, $searchend, $case_sensitive=false, $start);
$first = $line_number[0];
$last = $line_number1[0];
//var_dump($line_number1);
for ($x = $first; $x <= $last; $x++) {
echo "Line number to be delete : $x <br>";
}
?>
I found solution of my question. I have just added few more line in my existing code. Now its working fine as required.
$lines = file($dir, FILE_IGNORE_NEW_LINES);
for ($x = $first; $x <= $last; $x++) {
echo "Line number to be delete : $x <br>";
$lines[$x] = '';
unset($lines[$x]);
}
//var_dump($lines);
file_put_contents($dir , implode("\n", $lines));

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

php how to get whole line after spicific character from text file?

I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.

Read file lines backwards (fgets) with php

I have a txt file that I want to read backwards, currently I'm using this:
$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
echo $line."<br />";
}
This outputs all the lines in my file.
I want to read the lines from bottom to top.
Is there a way to do it?
First way:
$file = file("test.txt");
$file = array_reverse($file);
foreach($file as $f){
echo $f."<br />";
}
Second Way (a):
To completely reverse a file:
$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
$output .= fgetc($fl);
}
fclose($fl);
print_r($output);
Second Way (b):
Of course, you wanted line-by-line reversal...
$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
$char = fgetc($fl);
if ($char === "\n") {
// analyse completed line $output[$ln] if need be
$ln++;
continue;
}
$output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : '');
}
fclose($fl);
print_r($output);
Try something simpler like this..
print_r(array_reverse(file('myfile.txt')));
Here is my solution for just printing the file backwards. It is quite memory-friendly. And seems more readable (IMO [=in my opinion]).
It goes through the file backwards, count the characters till start of a line or start of the file and then reads and prints that amount of characters as a line, then moves cursor back and reads another line like that...
if( $v = #fopen("PATH_TO_YOUR_FILE", 'r') ){ //open the file
fseek($v, 0, SEEK_END); //move cursor to the end of the file
/* help functions: */
//moves cursor one step back if can - returns true, if can't - returns false
function moveOneStepBack( &$f ){
if( ftell($f) > 0 ){ fseek($f, -1, SEEK_CUR); return true; }
else return false;
}
//reads $length chars but moves cursor back where it was before reading
function readNotSeek( &$f, $length ){
$r = fread($f, $length);
fseek($f, -$length, SEEK_CUR);
return $r;
}
/* THE READING+PRINTING ITSELF: */
while( ftell($v) > 0 ){ //while there is at least 1 character to read
$newLine = false;
$charCounter = 0;
//line counting
while( !$newLine && moveOneStepBack( $v ) ){ //not start of a line / the file
if( readNotSeek($v, 1) == "\n" ) $newLine = true;
$charCounter++;
}
//line reading / printing
if( $charCounter>1 ){ //if there was anything on the line
if( !$newLine ) echo "\n"; //prints missing "\n" before last *printed* line
echo readNotSeek( $v, $charCounter ); //prints current line
}
}
fclose( $v ); //close the file, because we are well-behaved
}
Of course replace PATH_TO_YOUR_FILE with your own path to your file, # is used when opening the file, because when the file is not found or can't be opened - warning is raised - if you want to display this warning - just remove the error surpressor '#'.
If the file is not so big you can use file():
$lines = file($file);
for($i = count($lines) -1; $i >= 0; $i--){
echo $lines[$i] . '<br/>';
}
However, this requires the whole file to be in memory, that's why it is not suited for really large files.
Here's my simple solution without messing up anything or adding more complex code
$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
$result = $line . "<br>" . $result;
}
echo $result // or return $result if you are using it as a function

Categories