Look up and access the file

My latest script is designed to search for a specific file in the current directory. If it doesn't find the file, it will move up one directory and try again.

The script functions properly when the file is found. However, if the file is not present, the script continues searching until it eventually times out after 30 seconds, despite implementing a counter to control the number of search attempts.

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

Answer №1

It seems like you are in need of code similar to 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++;
    }
}

UPDATE: If you only want the content of the log.log file, you can simply use file_get_contents($path) like so:

...
if(file_exists($path)) {
    $file_exists = true;
    $contents = file_get_contents($path);
    echo $contents;
}
...

For further details on the file_get_contents function, visit the linkhere.

Answer №2

until($file_exists == 1)

This loop will continue indefinitely because the variable $file_exists is only set to 1 when the file is found.

If the file is not found, the internal loop will only run for three times. However, the external loop will run infinitely without any executable statements.

EDIT:

You can combine the conditions like this:

until($file_exists == 1 || $search_count >= $search_limit) {

//your entire code

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to invoke a different webpage in PHP

I'm experimenting with calling a different php page without them being displayed one after another. Let's say I have pages x and y: x.php contains: <html x page tags> <?php echo "i'm x.php"; ?> </html x page tags> ...

Building an event management system using CodeIgniter and jQuery to create a seamless scheduling calendar

I am in the process of creating an event and scheduling calendar using codeigniter and jquery. It is important for me to be able to have multiple events on the same day while keeping the design clean and user-friendly. If anyone has any recommendations fo ...

Transferring Arrays through Ajax/JSON without the use of JQuery

Currently, I'm in the process of experimenting with Ajax techniques and my main goal is to transmit a 1-dimensional, non-associative array from a PHP function to a JavaScript function. The contents of this array are quite straightforward, such as: $a ...

Is it possible to only show the div element in my AJAX request without displaying the entire page

Is it possible to only show a specific div in my ajax request without displaying the entire page? The entire page is loaded, but I only want to display one div and hide the header and footer. However, I still need the header to be present on the page. jQ ...

Inspect each key of the array to determine if its corresponding value is either null or an empty string

I am trying to echo an array from MySQL with specific conditions. I want any null or empty strings to be replaced with "<null>" for personal reasons. However, I am facing difficulties in achieving the desired result. Any help is appreciated. while ( ...

Listeners are not recognized by the events in Laravel

I have previous experience working with events and listeners, but now I am facing an issue where the event does not recognize the listener in the code below. The event is defined as: <?php namespace App\Events; use Illuminate\Broadcasting& ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

I am facing issues with my submit buttons as they are not functioning

Once I hit the submit buttons, there seems to be an issue with redirecting to another page. Could anyone assist in identifying the error within this code and why my buttons "typ1" and "cod" are not redirecting to the specified location? <?php inc ...

Implementing AJAX mysqli interaction in PHP following the MVC design pattern

Today I'm encountering yet another AJAX-related error. I am in the process of developing a user registration system using AJAX and PHP, following MVC architecture. Previously, I successfully built a login system without AJAX that functions flawlessl ...

I attempted to separate a string containing <br> tags using the explode function, but the method was not successful

In my code, there is a string that looks like this <br> ACCEPT:YES <br> SMMD:tv240245ce <br> This string is stored in a variable called $_session['result'] My task is to extract the following information either as an array or ...

"Can you provide insight on retrieving asset files within a Dart package without any external dependencies

I recently developed a dart package for my flutter application and have encountered an issue with accessing a json file containing static data within the package. I am struggling to find a direct way to access asset files from a dart package code without r ...

Tips for showcasing retrieved JSON with jQuery's ajax functionality

Below is the jquery code I am working with: $.ajax({ type: "POST", url: "Ajax/getTableRecord", data:{ i : id, t: 'mylist'}, dataType: 'json', success: function(data){ alert(data); ...

Utilizing Datamapper ORM in Codeigniter to establish both Many to One and Many to Many relationships between the same objects

My application has specific requirements: Each user can own multiple projects. Each project can only have one owner. Users can work on multiple projects. Projects can have multiple users involved. To accommodate these requirements, I have designed 3 tab ...

Executing Python code through a website using PHP - is there a way to deactivate the button once it has been clicked?

Can you assist with the following issue? <?php if(isset($_POST['MEASURE'])) { shell_exec("sudo python /var/www/html/lab/mkdir.py"); } ?> Here is the HTML part: <form method="post" > <input type="submi ...

How to change static properties in child classes in PHP

<?php class Base { protected static $c = 'base'; public static function getC() { return self::$c; } } class Derived extends Base { protected static $c = 'derived'; } echo Base::getC(); // output "base" echo Derived::ge ...

SQL (MySQL) instructions for merging two tables

I am trying to merge information from two different tables. The desired output would be a combination of data from table A and table B. SELECT date as Date, COUNT(*) as Transaction, SUM(status=0) as Success FROM transfer_tx_201503 WHERE time >=&apos ...

Using Javascript code within functions.php

I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...

The function ajax does not recognize response.forEach as a valid function

When I try to use ajax for fetching data from MySQL using PHP and JavaScript, I encounter a function error stating "response.forEach is not a function". Despite looking through various posts on this issue, none of the suggested solutions have been able to ...

The specified path could not be located by the system. (run php)

This particular issue seems quite straightforward to me. My aim is to change a pdf file into an image in the format of png. Here's what I've attempted using easyphp: $gp = "C:\Program Files (x86)\ImageMagick-6.8.0-Q16\convert.ex ...

Having difficulty passing a variable between two different PHP files

When attempting to modify data in the database for a specific user column, I encountered an issue. The code that I created only alters the data for the last user in the database, rather than the current user. For instance: Let's say I am logged in as ...