Debugging PHP Error: Ajax Chat installation - php

Unable to run install script for Ajax chat. It appears that the function calls can find the appropriate $filename, so I am having trouble determining what the invalid argument is.
in file [ROOT]/phpbb/di/container_builder.php on line 291: file_put_contents(C:/inetpub/wwwroot/phpbb3/chat/../cache/container_C:/inetpub/wwwroot/phpbb3/chatslashdotdotslash.php): failed to open stream: Invalid argument
Here is line 284-291:
protected function dump_container($container_filename)
{
$dumper = new PhpDumper($this->container);
$cached_container_dump = $dumper->dump(array(
'class' => 'phpbb_cache_container',
'base_class' => 'Symfony\Component\DependencyInjection\ContainerBuilder',
));
file_put_contents($container_filename, $cached_container_dump);
}
The function call for $container_filename is
protected function get_container_filename()
{
$filename = str_replace(array('/', '.'), array('slash', 'dot'), $this->phpbb_root_path);
return $this->phpbb_root_path . 'cache/container_' . $filename . '.' . $this->php_ext;
}
The function variable for $cached_container_dump is what I think may be the issue, as shown above in line 2. I'm not sure base_class is being found because it is not in the namespace. Been trying to follow this for a few days... any help will be appreciated.
Results from var_dump($dumper) here: does this mean the array is returning an object?
object(Symfony\Component\DependencyInjection\Dumper\PhpDumper)#13 (7) { ["inlinedDefinitions":"Symfony\Component\DependencyInjection\Dumper\PhpDumper":private]=> object(SplObjectStorage)#3325 (1) { ["storage":"SplObjectStorage":private]=> array(198)

Replace your file_put_contents function with the one below:
file_put_contents($container_filename, $cached_container_dump, FILE_APPEND);
And make sure that $dumper->dump() function returns a string.

You have to replace the colon it the cache file name since it's not a valid file name character on windows.

Related

Problem when I try to delete data and files

I'm new in Laravel, and I'm doing a project for my university, and I've two problems when I try to delete:
First error: When I try to delete the records, only the first one (with ID 1) doesn't delete from the table, but the other if deleted from the table and I've already tried some things to fix the error, but I couldn't:
Controller.php:
public function destroy_int($inst_id)
{
$inst = InstitucionEntidadInt::where('id', $inst_id);
$inst->delete();
return redirect('/activities/cons_instituciones_int');
}
Web.php:
Route::delete('/delete_inst_int/{inst_id}', [InstEntController::class, 'destroy_int'])
->name('institucion_int.destroy');
Second error: In some forms, it's necessary to upload and save files in a database (so I save just the name in the database and the files are saved in the public path). And some of this input files are multiple, so I save the names in the database like a JSON (using the json_encode method):
//This is the way that I save the files
$files = [];
if ($request->hasFile('inst_docsoporteNac')) {
foreach ($request->file('inst_docsoporteNac') as $file) {
$name = time() . "_" . $file->getClientOriginalName();
$file->move(public_path('files/institucionesNac'), $name);
$files[] = $name;
}
}
$instentNact->docSoportes = json_encode($files);
So, I'm trying to implement the delete method and I need to delete the files from both places (from the DB and the public path), I don't know how I can do it and I've already tried some "solutions" that I read from some forums (like this).
Controller.php:
public function destroy_nac($inst_id)
{
$inst = InstEntNac::where('id', $inst_id);
$files = InstEntNac::where('id', $inst_id)->get('docSoportes');
foreach (json_decode($files) as $file) {
Storage::delete(public_path('files/institucionesNac/' . $file));
}
$inst->delete();
return redirect('/activities/cons_instituciones_nac');
}
This is the way that I'm using, but I'm getting an error "Object of class stdClass could not be converted to string".
I'll appreciate your solutions for these errors.
For the first error, you can add error handling using this code:
InstitucionEntidadInt::findOrFail($inst_id)->delete();
For the second error, json_decode returns by default stdClass object instead of array. You can tell the function to return array type with second boolean parameter setting it to true:
json_decode($files, true)
https://www.php.net/manual/en/function.json-decode.php

How to not have tmpfile() be deleted when out of the scope of the method that it was created by?

I'm on php#8.1.3. When I have one method both creating and reading from a tmpfile, everything works as expected:
class TmpFileReadRightAway
{
public function storeToTempFileAndReadRightAway(string $content): string
{
$fh = tmpfile();
$path = stream_get_meta_data($fh)['uri'];
fwrite($fh, $content);
return file_get_contents($path);
}
}
echo (new TmpFileReadRightAway())->storeToTempFileAndReadRightAway('this works as expected');
Yet when I split the method into multiple methods, the tempfile() is deleted after the method in which it was created returns.
This is not at all what I expected as I wanted to keep the file around. I would expect the tmpfile to be deleted at termination of the php code at the very end, not after it exits the method.
class TmpFileStoreButReadLater
{
public function storeButReadLater(string $content): string
{
$path = $this->getPath($content);
return file_get_contents($path); // file at path doesn't exist anymore here, why?
}
private function getPath($content): string
{
$fh = tmpfile();
$path = stream_get_meta_data($fh)['uri'];
fwrite($fh, $content);
return $path;
}
}
This would throw
PHP Warning: file_get_contents(/tmp/phpQsUdA5): Failed to open stream: No such file or directory
Why is the file being deleted in this case and how do I ensure it exists during the runtime of my code?
Use class property.
The tmpfile() document said.
The file is automatically removed when closed (for example, by calling
fclose(), or when there are no remaining references to the file handle
returned by tmpfile()), or when the script ends.
So, I assume that when method exits, the fclose() is called automatically.
The error about failed to open stream is not just occur in PHP 8.1 but all version since PHP 7.0 to 8.1. (I don't have PHP 5.x to test with.)
To prevent that, set the $fh to class property instead.
class TmpFileStoreButReadLater
{
protected $fh;
public function storeButReadLater(string $content): string
{
$path = $this->getPath($content);
return file_get_contents($path); // file at path doesn't exist anymore here, why?
}
private function getPath($content): string
{
$this->fh = tmpfile();
$path = stream_get_meta_data($this->fh)['uri'];
fwrite($this->fh, $content);
return $path;
}
}
echo (new TmpFileStoreButReadLater())->storeButReadLater('this works as expected');
Tested on PHP 7.0 - 8.1.3 but no errors now.

PHP fopen invalide arguments when using dynamic string

I am trying to dynamically create migration files, and I encounter a problem with the fopen function, whenever I call the function with a dynamic string for the name of the file I get the following error:
"failed to open stream: Invalid Argument.
now the wierd thing is, when I take the file_name string that caused the error, and put it fixed in the fopen function, it works and creates the file.
here is the part of the code that fails:
public function add_tables($from, $to) {
$migration_name = $this->generate_migration_name($from, $to);
$migration_file = fopen($migration_name, "w") or die("Unable to open file!");
$migration_content = "...";
fwrite($migration_file, $migration_content);
}
public function generate_migration_name($from, $to) {
$current_date = Date('Y_m_d_His');
return $current_date."_create_msl_".$from."_to_".$to."_table.php";
}
am I doing anything wrong?
UPDATE: the $to and $from are two strings im reading from a text file using fgets function. example for string that failed:
2017_02_22_154148_create_msl_yeshut_yatzran_to_mimshak_table.php
when I put it fixed in the fopen function the file is created successfully.
You may have spaces in your filename. You can remove them by using trim:
public function generate_migration_name($from, $to) {
$current_date = Date('Y_m_d_His');
return $current_date."_create_msl_".trim($from)."_to_".trim($to)."_table.php";
}
The file you are trying to create is not in your server or check file permissions

How does one define a PECL bbcode extension callback when writing a CodeIgniter library?

I'm writing a CodeIgniter library around PHP's bbcode PECL extension, but I'm having some trouble with callbacks.
I set up the handler in the library constructor:
function __construct() {
$basic = array(
'url' => array(
'type' => BBCODE_TYPE_OPTARG,
'open_tag' => '<a href="{PARAM}" rel="nofollow">',
'close_tag' => '</a>',
'childs'=>'i,b,u,strike,center,img',
'param_handling' => array($this, 'url')
)
);
$this->handler = bbcode_create($basic);
}
public function parse($bbcode_string) {
return bbcode_parse($this->handler, htmlentities($bbcode_string));
}
As you notice, this uses a callback for handling what's allowed to go into the URL. I use this to insert an "exit redirect" page
public static function url($content, $argument) {
if (!$argument) $argument = $content;
$url = parse_url($argument);
if (!isset($url['host'])) {
if (strlen($argument) > 0 && $argument[0] != '/') return false;
$destination = '//'.$_SERVER['HTTP_HOST'].$argument;
} elseif ($url['host'] != $_SERVER['HTTP_HOST']) {
$destination = '//'.$_SERVER['HTTP_HOST'].'/exit?'.urlencode($argument);
} else {
$destination = $argument;
}
return htmlspecialchars($destination);
}
And I also have a little function which helps me test this out as I work:
function test() {
$string = '[url]http://www.google.com[/url]';
echo '<pre>';
die($this->parse($string));
}
This all works fine if the test() method is called from within the library. For example, if I throw $this->test() at the bottom of the constructor, everything works exactly as I would expect. However, calling $this->bbcode->test() from somewhere else (e.g. in a controller), I get the following errors:
**A PHP Error was encountered**
Severity: Warning
Message: Invalid callback , no array or string given
Filename: libraries/bbcode.php
Line Number: 122
**A PHP Error was encountered**
Severity: Warning
Message: bbcode_parse(): function `' is not callable
Filename: libraries/bbcode.php
Line Number: 122
http://www.google.com
The callback does not get executed, and as a result the link's href attribute is empty. Line 122 refers to the single line of code in my parse function:
return bbcode_parse($this->handler, htmlentities($bbcode_string));
How do I address this callback function such that it can be located when $this->bbcode->test() is called from inside a controller?
Now I'm even more confused...
So in the hopes of just putting this all behind me, I put these callback functions in a helper so I can just call them directly. So I now have code like this:
function __construct() {
$basic = array(
'url' => array(
'type' => BBCODE_TYPE_OPTARG,
'open_tag' => '<a href="{PARAM}" rel="nofollow">',
'close_tag' => '</a>',
'childs'=>'i,b,u,strike,center,img',
'param_handling' => 'bbcode_url'
)
);
$this->handler = bbcode_create($basic);
}
With the above, I get the following error:
**A PHP Error was encountered**
Severity: Warning
Message: Invalid callback 6.7949295043945E-5, no array or string given
Filename: libraries/bbcode.php
Line Number: 176
**A PHP Error was encountered**
Severity: Warning
Message: bbcode_parse(): function `6.7949295043945E-5' is not callable
Filename: libraries/bbcode.php
Line Number: 176
(line 176 is the new location of the parse() function)
Um... I don't even know what's going on. The number 6.7949295043945E-5 changes with every attempt.
The only solution I have found to this is quite simply not to set the handler up in a constructor. Instead, the parse() method contains both the bbcode_create() call and the bbcode_parse() call. That is, the bbcode_handler is freshly created for every string of bbcode to be parsed.
This seems needlessly wasteful to me. But, over the course of the lifetime of this project, it is exceedingly unlikely to cost even a tenth of the amount of time that I have spent trying to sort this out "properly", so I'm calling it a day.
I'm posting this "solution" here in case somebody else happens across this question and can thereby save themselves a few hours' pain. That said, I would really like to know what on earth is going on, and how to do this properly.

PHP Get Basename of File Where Function Called

Anyone can help me get the basename of directory where the function called? I mean:
file /root/system/file_class.php
function find_file($dir, $file) {
$all_file = scandir($dir);
....
}
function does_exist($file) {
$pathinfo = pathinfo($file);
$find = find_file($pathinfo["dirname"], $pathinfo["basename"]);
return $find;
}
file /root/app/test.php
$is_exist = does_exist("config.php");
Under /root/app i have file "config.php, system.php". Do you know how to get the directory where does_exist() called? In function find_file() argument $dir is important, since scandir() function need directory path to scaned. I mean, when i want to check file config.php i doesn't need to write /root/app/config.php. If i not provide fullpath in $file argument, the $pathinfo["dirname"] will be ".". I've try to use dirname(__file__) in file_find() function but it's return the directory /root/system not /root/app where it is the directory of does_exist() function called.
I need create those function since i can't use file_exists() function.
Found Solutions:
I'm using debug_backtrace() to get the recent file and line number of where users calling function. For example:
function read_text($file = "") {
if (!$file) {
$last_debug = next(debug_backtrace());
echo "Unable to call 'read_text()' in ".$last_debug['file']." at line ".$last_debug['line'].".";
}
}
/home/index.php
16 $text = read_text();
The sample output: Unable to call 'read_text()' in /home/index.php at line 16.
Thanks.
Use any of PHP magic constants
__DIR__
__FILE__
http://php.net/manual/en/language.constants.predefined.php
Or use realpath("./");
To define your own constant paths:
define("MYPATH", realpath("./") . "/dir/dir/";
You can then call this MYPATH from everywhere this code (file) is included.

Categories