PHP fopen invalide arguments when using dynamic string - php

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

Related

Save timestamp in a text file after run a function in codeigniter

Whenever the function in codeigniter will run,I want to save the timestamp in a text file. How can I achieve that?
public function updateData(){
Running this function each time it will save the timestamp in a text file.
}
you can find more info and examples here -> https://www.w3schools.com/php/php_file_open.asp
public function updateData(){
# Running this function each time it will save the timestamp in a text file.
$path2file = "/docs/";
$fileName = "timestamp.txt";
$data = time()."".PHP_EOL; // PHP_EOL - new line
$fp = fopen($path2file.$filename, 'a');
fwrite($fp, $data);
}

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.

Laravel filesystem and ftp

im having a hard time with the filesystem of Laravel. Im trying to generate, save and transfer a xml-file in a controller.
everything but the ftp-transfer works. I suspect it is because i cant get the right path of the new xml-file in the sendFilToNCS($fileName) function. Im getting this error:
ErrorException ftp_put(/storage/1584533245.xml): failed to open
stream: No such file or directory
Hope to get som help from the laravel-experts. Good day.
class ExportController extends Controller
{
public function __construct(){
$this->middleware('auth:admin');
}
public function index($id){
$foromtale = Foromtale::find($id);
$data = new NCSNote($foromtale);
$xml = View::make('xmlTemplate')->with('view', $data);
$xmlDoc = simplexml_load_string($xml);
return $this->writeXml($xmlDoc);
}
public function writeXml($content){
$fileName = time().".xml";
//$content->saveXML($fileName);
Storage::put($fileName, $content);
Storage::move($fileName, 'storage/'.$fileName);
return $this->sendFilToNCS($fileName);
}
private function sendFilToNCS($fileName)
{
$content = Storage::disk('local')->url($fileName);
$ftp_server = "ftp.host.dk";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "username", "xXxxXX");
// upload file
if (ftp_put($ftp_conn, $fileName, $content, FTP_ASCII))
{
// close connection
ftp_close($ftp_conn);
return true;
}
// close connection
ftp_close($ftp_conn);
return false;
}
}
Storage facade without any changes will put your files in storage/app. I do not see the point in moving the files afterwards. Imaging you would put your files in storage/app/xml for easier overview. This could be obtained like this.
$fileName = '/xml/' . $fileName;
Storage::put($fileName, $content);
When you want to get the file path, the storage facade has a helper for that. Which will return the absolute path, you will need for ftp_put().
$path = Storage::path($fileName)
Seems like you are using ftp_put() wrong. The third parameter is a path to the file, use the newly defined $path property.
ftp_put($ftp_conn, $fileName, $path, FTP_ASCII)
There is a lot of aspects in this code, but this seems like the most obvious errors, I'm not certain it will get you the whole way, but should get you to the next step in the process.

PHP: Stored value in a text file and printed one in view file is not the same

In my controller, there are three methods:
NOTICE: I use Codeigniter v3...
public funtion index(){
$data['code'] = $this->generate_random_string();
$myfile = fopen("C:\wamp\www\write.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data['code']);
fclose($myfile);
$this->load->view('path_to_view/view1', $data);
}
//$param is numeric
public funtion send($param){
$data['code'] = $this->generate_random_string();
$myfile = fopen("C:\wamp\www\write.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data['code']);
fclose($myfile);
$this->load->view('path_to_view/view2', $data);
}
public function generate_random_string(){
$this->load->helper('string');
$date = new DateTime();
return random_string('sha1', 40) . $date->getTimestamp();
}
in the first and second method, I generate a random string, assign it to $data['code'] and also save it in a file (write.txt), and then load a view and echo $data['code'].
The problem is: in first method, stored $data['code'] in file and printed one in view file is the same, but in second method (send) they are different!!!
Another thing to say is: when I add below statement in second method and print value in controller (instead of view), everything will be ok:
var_dump($data['code']);
I could not understand what happened! There is not any special code to affect these, just some loading view, header, footer.
Could anyone help to find possible issues or guess what is ?
thanks.
SOLVED: I check all view file, I couldn't find related code to this issue. But, when I comment below line in header, the problem is solved!
Could anyone explain about this? just a link element cause problem!

Debugging PHP Error: Ajax Chat installation

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.

Categories