PHP require_once fails but require works - php

In an application I am calling require_once $file where I have validated that the $file variable represents an absolute path, the file exists, and is readable. PHP 7.3 is giving me the dreaded: "Fatal error: require_once(): Failed opening required" message.
When I change the code to use "require" instead of "require_once" I get further, till the next "require_once" statement.
I am running PHP 7.2.19 on ubuntu 18.04.
This particular code is embedded deep within an application that has already included and required many different files at different times.
I have checked for obvious things like the particular file being included multiple times (it is not)... and including a different file for testing purposes, and that also consistently fails. I have double checked permissions, etc.
$file = "$destdir/lib/include.php";
$file = realpath($file);
if( is_file($file) && is_readable($file) ) {
require_once $file; // fails
// require $file; // works, but fails when require_once is called within this file.
// include $file; // works, but fails when require_once is called within this file
// include_once $file; // fails
}
I expected of course, that the file is required.

Related

PHP require_once persists in a separate process

EDIT: I need to provide more detail, not sure what is going on.
I seem to be having a problem where PHP treats a require_once in a separate process as a repeat of the require in the outer process.
Suppose I have this file which I will run on the CLI:
<?php
require_once 'includeme.php';
$command = "php runme.php";
$handle = popen($command, 'r');
$read = fread($handle, 2096);
$exit = pclose($handle);
print_r($read);
This does the following:
include a file
run a child process, which will also try to include that file.
The file includeme.php is this:
<?php
print "I was included";
Including it should just cause it to return that string.
The runme.php file is this:
<?php
$result = require_once 'includeme.php';
print $result;
Running the main script produces this output:
I was included
1
What seems to be happening is that the runme.php script is getting a 1 for the require_once statement, which is what require_once returns if the script has already been included.
But runme.php is a separate process. How can PHP be thinking it's already included includeme.php?
From the docs:
Successful includes, unless overridden by the included file, return 1
The 1 in your output does not indicate it was already previously included, just that it was included successfully.
Regardless of the return value, you can use require_once everywhere and trust it's working as expected.
Do note that require_once (like, require, include...) is a construct, not PHP function. So, returned 1 probably means, OK, file is included. No idea why echoed I was included was not caught.

PHP file not found error but it is including the file?

I have the following code to include a file that runs some SQL and other code
if (isset($_GET["vpnadd"])) {
echo "Swapping to VPN<br />";
$filename = '/home153/sub002/sc00083-LGVN/xxx.co.uk/addmyfile.php';
require $filename;
}
However, when I run the code, it gives an error of: error: No such file or directory
But, it does actually run the file and inserts a database record so I am not sure why it gives the file error?

how to make sure a PHP script is loaded one time

I have a cronjob system with PHP. I have a file named cron.php and wanna to check if it is not loaded, load it. it is very important to me that this file run only one time and I need the way how define it is already running. I can't use any system functions like exec,system,... do you have any solutions?
NOTE: I run my script trough CURL and include_one and require_once don't work for this case.
You could use flock() to lock the php file itself, like this:
<?php
class Lock{
private $fp;
function __construct(){
$this->fp=fopen(__FILE__,'r');
if (!flock($this->fp,LOCK_EX|LOCK_NB)) {
die('already running !'.PHP_EOL);
}
}
function __destruct(){
flock($this->fp,LOCK_UN);
fclose($this->fp);
}
}
$lock=new Lock();
// simulate some processing
sleep(60);
echo "END";
?>
Can you just use require_once or include_once?
require_once will throw a PHP fatal error (will stop execution) if the file cannot be evaluated.
include_once will throw a PHP warning (execution may continue).
// Require tasks.php to run once
require_once 'path/to/tasks.php';
// Attempt to run tasks.php and only once
include_once 'path/to/tasks.php';
Your problem is essentially equivalent to "Check if a php script is still running"
Please refer this
Check if a php script is still running
if I understand you correctly, you want to prevent your cron.php script from getting started a second time by cron, it is not called from another PHP script? (in that case, require_once would be the right answer)
as I understand it, you need to store a marker that indicates that your script is running and remove that marker at the end of your script.
depending on your environment, you could either create a small file, i.e. .lock or store a status = locked entry in your database.
edit: here is a small code example using the file method:
<?php
// cron.php
$path = '/path/to/your/data/directory/';
if (file_exists($path . '.lock') {
die('cron.php is already running');
}
// if script reaches this point, it is not locked -> create a lock
file_put_contents($path . '.lock', 'lockfile created at ' . now());
//... your code....
//unlocking
unlink($path . '.lock');
?>
If you are using cURL then I believe your are using cURL to request a page such as http://domain.com/cron.php. The machine requesting the script via cURL/wget/browser/etc has no way of knowing if the script is already being executed on the server. However, you can configure your cron.php script to run only once:
<?php
// attempt to obtain a lock
$fp = fopen(basename(__FILE__) . ".lock", "w");
if (flock($fp, LOCK_EX | LOCK_NB) === false) {
echo basename(__FILE__) . ": already running\n";
exit(-1);
}
// code goes here
echo date("Y-m-d H:i:s") . ": cron job started\n";
sleep(30);
echo date("Y-m-d H:i:s") . ": cron job ended\n";
// release the lock
flock($fp, LOCK_UN);
fclose($fp);
The sample code uses PHP flock function. The LOCK_EX flag tells PHP that it needs to obtain an exclusive lock; i.e. no other process is allowed to access the file. The LOCK_NB tells PHP that it should not block (wait for the lock to be released) and return false immediately. Together, the two switches assure that a second process cannot lock the file while the first one has it locked.
you can use require_once or include_once
The general syntax of both the include and require statements are as follows:
include "file_to_load.php";
include_once "file_to_load.php";
When the include_once/require_once statements are used, the file cannot be loaded or executed multiple times. If an attempt is made to load a file twice using one of these two methods, it will be ignored. Because it is unacceptable to define the same function multiple times within a script, these functions allow the developer to include a script as needed without having to check whether it has been previously loaded.
NOTE The capability to return values from external files is limited only to the include_once statements. The require_once statements cannot be used in this fashion.
include_once('class.php');
php.net states
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
You can use either require_once or include_once.
if you are confuse what to use then difference between this two is that
require_once will stop executing preceding code, trwos fatal error, if file mentioned is not found
so if you want preceding code to continue even file is not found then don't use it.
where as the include_once will continue executing preceding code.
You can use Database for this case, make an entry of the page in database and second column for checking whether is it loaded or not (eg. '0' if not loaded yet and '1' it is loaded). Initially keep value of that row as '0' when the page is loaded update that column as '1'.

Deleting files in higher directory

I'm having problems deleting a file from a higher directory, I found this post and tried it but no luck....:
gotdalife at gmail dot com 25-Sep-2008
02:04
To anyone who's had a problem with the
permissions denied error, it's
sometimes caused when you try to
delete a file that's in a folder
higher in the hierarchy to your
working directory (i.e. when trying to
delete a path that starts with "../").
So to work around this problem, you
can use chdir() to change the working
directory to the folder where the file
you want to unlink is located.
<?php
> $old = getcwd(); // Save the current directory
> chdir($path_to_file);
> unlink($filename);
> chdir($old); // Restore the old working directory ?>
here is the code that I currently have:
session_start();
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] !=md5($_SERVER['HTTP_USER_AGENT']))){
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}
$folder = $_GET['folder'];
$filename = $_GET['name'];
$path = "../gallery/photos/$folder";
if (isset($_POST['submitted'])) {
if ($_POST['sure'] == 'Yes') {
$old = getcwd(); // Save the current directory
chdir($path);
unlink($filename);
chdir($old); // Restore the old working directory
}
else{
echo '<p>The photo has NOT been deleted.</p>';
}
}
I'm getting the error message :
Warning: unlink() [function.unlink]:
No error in
J:\xampp\htdocs\bunker\admin\delete_file.php
on line 37
line 37 being:
unlink($filename);
can anybody see what I've done wrong?
I always use absolute filepath names.
I'd define the filedir as a constant in your config, then concatenate so you have an absolute filepath, then make a call to unlink().
Btw: I hope you know your code is highly insecure.
See here:
http://bugs.php.net/bug.php?id=43511
and here
http://php.bigresource.com/Track-php-03TimDKO/
http://www.phpbuilder.com/board/showthread.php?t=10357994
Though I wouldnt recommend doing this, as per the comments above. Is there the option for a different approach?

PHP: Can include a file that file_exists() says doesn't exist

In my script, I set the include path (so another part of the application can include files too), check that a file exists, and include it.
However, after I set the include path, file_exists() reports that the file does not exist, yet I can still include the same file.
<?php
$include_path = realpath('path/to/some/directory');
if(!is_string($include_path) || !is_dir($include_path))
{
return false;
}
set_include_path(
implode(PATH_SEPARATOR, array(
$include_path,
get_include_path()
))
);
// Bootstrap file is located at: "path/to/some/directory/bootstrap.php".
$bootstrap = 'bootstrap.php';
// Returns "bool(true)".
var_dump(file_exists($include_path . '/' . $bootstrap));
// Returns "bool(false)".
var_dump(file_exists($bootstrap));
// This led me to believe that the include path was not being set properly.
// But it is. The next thing is what puzzles me.
require_once $bootstrap;
// Not only are there no errors, but the file is included successfully!
I can edit the include path and include files without providing the absolute filepath, but I cannot check whether they exist or not. This is really annoying as every time a file that does not exist is called, my application results in a fatal error, or at best a warning (using include_once()).
Turning errors and warnings off is not an option, unfortunately.
Can anyone explain what is causing this behaviour?
file_exists does nothing more than say whether a file exists (and the script is allowed to know it exists), resolving the path relative to the cwd. It does not care about the include path.
Yes Here is the Simplest way to implement this
$file_name = //Pass File name
if ( file_exists($file_name) )
{
echo "Exist";
}
else
{
echo "Not Exist";
}

Categories