Why does PHP creates wrong files? - php

I'm creating using PHP a file:
$file = fopen(__DIR__ . "/../folder/example_$array[nothing].txt", "w");
Problem is, that there are two files generated:
example_.txt
example_test.txt
I don't know, why there are created these two files. I just wanna have the example_test.txt, the other one is the undesirabled. I checked the directory using var_dump and the two files appear after the code above was executed. The function is also only one time called.
Does anyone know what can be the issue?
EDIT:
$array is read by a file and contains something like ["nothing" => "test", "something more" => "okay"].

Related

Confused about pointing fopen to a specific file (which is using a variable filename) in a specific directory

So I'm basically creating .txt files with unique filenames and then changing the ext. of the file to .mobileconfig. That's the overall goal but I wanted the files in a different directory, that's not my root directory.
So it's basically an HTML form, then it takes the data submitted through that form, figures out what to do with it here:
<?php
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$genfile = fopen('./generated/'$UUID.'.txt', w);
file_put_contents('./generated/'$UUID.'.txt', $txt);
rename('./generated/'$UUID.'.txt', './generated/'$UUID.'.mobileconfig');
?>
I had it working, but it was in the same directory as my other files. I've tried the code above, I've tried it using " instead of '. I've tried without the period before the /, and I've tried without the ./ all together.
Is there anything else that I could try besides just moving the .php file to another directory because I do want to set something up where it deletes all the files inside the generated folder every x amount of time.
You have many syntax errors in your code.
Additionally, using file_put_contents() doesn't require that you open the file first.
Lastly, why create a file with a .TXT extension if you're going to rename it immediately afterwards?
Try this:
$txt = $_POST['content'];
$UUID = $_POST['UUID'];
$fname = "./generated/$UUID.mobileconfig";
file_put_contents($fname, $txt);
See the PHP manual for details on variable expansion in double-quoted strings

how to open a file while inside a foreach(glob....PHP

I have a small number of image files and text files. They have the same file name with different extensions. I need to read the image files and for each image I need to read some (tool top) text from the corresponding text file. The problem is the file open inside the "foreach( glob("inserts/*.png")" loop fails. I have output the filename and the fopen works fine. I thought it may be you are unable to open two file concurrently in PHP but I could find nothing about it when I googled
foreach( glob("inserts/*.png" ) as $filename ) {
$path="public/xml/iweb/".$filename;
$insertpath=substr($filename, 0, -3)."txt";
$myfile = fopen($insertpath, "r");
$rec=fread($myfile,filesize($insertpath));
fclose($myfile);
$name=getInnerSubstring($rec,"-");
$HTML5.="<img class='insertimage' src='".$path."' title='".$name."' onclick='insertcomponent(\"".$insertpath."\")'>";
}
One day I hope I know enough to answer questions instead of just asking them. :(
There's no reason why you shouldn't be able to open multiple files and no reason the foreach should break anything that works. My hunch is that the path you're trying to open is wrong. I suggest either debugging the code to see the variables or add an echo to see their content. You should also check if fopen() and fread() don't return some false because they failed. Good luck :)

file_put_contents stopped working

I have a PHP code that connects to a FTP server, reads a file's content, makes a minor change, and than overrides the original file.
it looks like:
$stream_context = stream_context_create(array('ftp' => array('overwrite' => true)));
$file_content = file_get_contents($ftp_file); // this line works
$file_content = str_replace('some content', 'another content', $file_content); // this also..
file_put_contents($ftp_file, $file_content, 0, $stream_context); // this one doesn't :/
the real issue is that the "file_put_contents" worked for a long time, but now it doesn't.
what it does now is weird: it deletes the original file from the server..
also, if i'm changing it to something like:
file_put_contents($new_ftp_file, $file_content);
from what I know, it should create the new file and put the content in it, but it doesn't create it at all.
the hosting service i'm using has a PHP version change a few days ago. I don't remember the what the previous version was, but the current is: 5.2.17
thanks! :)
some changes
I found this piece: http://www.php.net/manual/en/function.file-put-contents.php#86864
doting the same as "file_put_contents" but with foen, fwrite and fclose (I send his example because of the results..). his functions is returning "false" if it couldn't to "fopen" the file, or the "bytes" if it succeeded. I got "false" :/
which means it couldn't even do the:
#fopen($filename, 'w');
although the "file_get_contents" with the same file address is working.
reading is working (but if you take the $filename and use it yourself on a client FTP - it works):
#fopen($filename, 'r');
the "open base_dir" for my hosting (which makes the action) is set to false, but the target hosting (which has the target-file) is set to be true.
I had an idea to save the new content on a new file, so I tried something like:
$f = #fopen($new_ftp_file, 'w'); //this one seems to work and connect
fwrite($f, $file_content); // this one seems to work either and returning the number of byes..
fclose($f);
the problem is that none of them really works. I logged in to the FTP address, using the same credentials that my script is using, and I haven't found the new file. It wasn't created at all. (as I remind you, "$new_ftp_file" is a path to a file that doesn't exists, so "w" mode on "fopen" should create it).
file_put_contents do erase the file by default if it already exists. You have to ask him to don't.
Look at here:
http://www.php.net/manual/en/function.file-put-contents.php
See: If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
this is not the best solution (definitely), but I managed to figure something..
I used 2 different hosts on them same hosting service, both of the having "open base_dir = On" & "safe mode = Off".
it looks something like:
$ftpstring = "ftp://user:password#anotherhosteddomain.com";
$file = file_get_contents($ftpstring . 'index.html'); // this line works as expected. (yeah, the other hosting has this file);
and then, if you're trying to write something like:
$handler = fopen($ftpstring.'index.html', "w");
it wouldn't work, and tell you it cannot access on writing mode to an existing file.
so if you're doing something like:
$newfile_handler = fopen($ftpstring.'index_new_version.html', "w");
fwrite($newfile, "1122");
so yeah - it works!
but now is a tricky issue.. when i'm adding this line:
fclose($newfile_handler);
the new file is deleted from the hosting!!
I couldn't find any reason why "fclose" is deleting the file after it was create at "fopen" and written in at "fwrite".
so if you're not adding the "fclose" line - it works, but it doesn't close the connection, and also I have to actually delete the existing file before I can override it with a new content, which makes it silly..
although it works, I would really like someone to give me a better solution than mine.

php fopen is not working (always null)

I have the following code in a "function" file [2] in my project. It can be called for multiple types of reports in my project. The $name comes from the reports pages using the $thePDFFileName [1]:
[1] $pdf->Output($thePDFFileName);
...
[2] $f=fopen($name,'wb');
if(!$f)
{
$this->Error('Unable to create output file: '.$name);
}
fwrite($f,$this->buffer,strlen($this->buffer));
fclose($f);
...
[1] FunctionSendFile::sendPDFFile($thePDFFileName );
Example: $thePDFFileName = tmp/[Filename]_19-11-2013.pdf
What's strange is before it was working for all my reports, now all of a sudden it always returns null (empty) for $f=fopen($name,'wb'); and I have no idea why. I tried removing the if condition to force the file being created, and it makes a pdf file of 0 bytes (I'm assuming because fopen() fails).
Has anyone seen this happen before and know how to fix it? I'm not sure what i've done to make all the pdf files stop working...
NOTE: I am trying to create these files and save them in a certain location. I'm not trying to find and open files that already exist!

How do I validate file type in Drupal 6 with file_save_upload?

I am working on a module that takes a user-uploaded CSV file. Code looks like this:
function foo_form_submit($form_id, &$form_state) {
$validators = array();
$dest = 'sites/phoenix.dev/files';
$uploaded_file = file_save_upload('upload', $validators, $dest);
//some other stuff
}
As you can see, I don't pass anything in to validate that the file in the 'upload' field is actually a .csv file. This would cause some nasty things to happen later on in the function. How do I use the validators to check that the extension is .csv, or even better, to check that it actually IS a .csv file?
Edit: and Google search did not turn up anything too helpful.
Drupal documentation on file_validate_extensions suggests you want to change this:
$validators = array();
To this:
$validators = array( 'file_validate_extensions' => array( 'csv' ) );
I don't see how you could check whether it's a valid CSV without actually trying to parse it and seeing if there are any errors.
True, it's not necessarily required to validate the contents of the file since the goal may be to stop (for example) .php scripts from executing, and with the extension being .csv apache wouldn't run this as a php script.

Categories