Coding Question - Newbie stuck

Hi all,

I’ve been diligently working through the www.homeandlearn.co.uk PHP tutorials, and one of the ways that I learn is to adapt learnings from one section and put it into another. I’m dealing with Chapter 10 at the moment and it’s specifically on dealing with opening and changing files. I looked at trying to include the functions module as well so that the code would do the following;

  1. Check if a file exists, if it exists proceed to 3.
  2. If file doesn’t exist then create the file, and add some random text.
  3. if it exists, open it with the view to append it with another line of text (I was planning on taking this further to loop it so it added sequential lines or something similar).

Could someone please have a look at the code I wrote as it doesn’t seem to be creating or amending the file.

For reference I’m building it using WebMatrix2 and when I did the exact tutorial walk through it worked without a problem.

[php]

<?php if(file_exists("testfile.txt")){ $file_contents = "I wonder what happens"; $file_handle = fopen("testfile.txt","a"); writetofile($file_contents); print "
why oh why"; } else{ print "File doesn't exist"; $file_contents = "Some test text"; $file_handle = fopen("testfile.txt,"w"); writetofile($file_contents); } function writetofile($file_contents, $file_handle){ fwrite($file_handle, $file_contents); fclose($file_handle); print "file updated"; } ?>

[/php]

Thanks
Maudise

are you aware you aren’t passing the file handle into the function?
e.g.

writetofile($file_contents,$file_handle)

Your function writetofile expects two parameters, but you are only passing one. You are not including the file handle. You are also missing a double quote after testfile.txt in the $file_handle assignment line of your else clause.

See if this works for you:[php]<?php
if(file_exists(“testfile.txt”)){
$file_contents = “I wonder what happens”;
$file_handle = fopen(“testfile.txt”,“a”);
writetofile($file_handle,$file_contents);
print “
why oh why”;
} else{
print “File doesn’t exist”;
$file_contents = “Some test text”;
$file_handle = fopen(“testfile.txt”,“w”);
writetofile($file_handle,$file_contents);
}
function writetofile($file_contents, $file_handle){
fwrite($file_handle, $file_contents);
fclose($file_handle);
print “file updated”;
}
?>[/php]

Brilliant, thanks.

I can’t mark as solved because it was done under a guest pass. Works perfectly now thanks, at least it was only a couple of small errors.

Thanks again for the advice.

Maudise

Glad it worked. I’ll mark it solved. Let us know if you run into any other issues.

jay

Sponsor our Newsletter | Privacy Policy | Terms of Service