Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Posts
    161
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Check if a text file exists and if not create it

    I want to use a PHP script to check whether a file exists or not and if not to create it.

    Example that is not written in PHP but shows what I want to do:

    if (main.txt exists)
    {
    do nothing
    }
    else
    {
    create main.txt with just one character inserted into it, a 0.
    }

  • #2
    New Coder
    Join Date
    Mar 2003
    Location
    Somewhere far beyond
    Posts
    99
    Thanks
    0
    Thanked 0 Times in 0 Posts
    PHP Code:
    clearstatcache();
    if(!
    file_exists("your_filename_here"))
    {
       
    $fp fopen("your_filename_here","w"); 
       
    fwrite($fp,"0"); 
       
    fclose($fp);

    Don't forget to add error checking.
    WBR, Weirdan.

  • #3
    Senior Coder
    Join Date
    Jun 2002
    Location
    near Oswestry
    Posts
    4,508
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Doesn't fopen automatically create a file if the named file doesn't exist?
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

  • #4
    New Coder
    Join Date
    Mar 2003
    Location
    Somewhere far beyond
    Posts
    99
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Originally posted by brothercake
    Doesn't fopen automatically create a file if the named file doesn't exist?
    Yes, but it also truncate file. It may be not what Dalziel wants.
    WBR, Weirdan.

  • #5
    Regular Coder
    Join Date
    Nov 2002
    Posts
    161
    Thanks
    2
    Thanked 0 Times in 0 Posts

    RE: Doesn't fopen automatically create a file if it doesn't exist

    Yes but it's being used for a hit counter, if I left it for fopen to create it, the first time the page was loaded an error would be displayed.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •