Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the php fopen() correctly

Tags:

php

I am learning php, trying to use the fopen() function. The php file I am coding is in this directory /domains/xxxxx.com.au/public_html/phpfile.php What path do I specify for the file to be opened, the example I am looking at is based on a server on a pc where this is the file path $filename = "c:/newfile.txt"; not an online server.

UPDATE!

This is the whole script, I have the file location correct, now the4 script is returning "couldnt create the file" does this have something to do with ther permission of the folder location of the file?

   <?php
$filename = "/domains/xxxxxxxx.com.au/public_html/newfile.txt";
$newfile = @fopen($filename, "w+") or die ("couldnt create the file");
fclose($newfile);
$msg = "<p>File Created</p>";
?>

<HTML>
<HEAD>
</HEAD>
<BODY>

<? echo "$msg" ?>

</BODY>
</HTML>
like image 505
Jacksta Avatar asked Apr 15 '10 11:04

Jacksta


People also ask

How does fopen work in PHP?

Definition and Usage. The fopen() function opens a file or URL. Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character.

How is fopen () used?

The fopen() function opens the file specified by filename and associates a stream with it. The mode variable is a character string specifying the type of access requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.

When using the fopen () function to open a file in PHP What made should you use for appending data to a file?

One can append some specific data into a specific file just by using a+ or a mode in the fopen() function. The PHP Append to file is done just by using the fwrite() function of PHP Programming Language.

What does fopen () function do in PHP Mcq?

It is used to compare two strings from each other. This function compares two strings and tells whether a string is greater, less, or equal to another string. 17) What is the use of fopen() function in PHP? Description: The sprintf() is an in-built function of PHP which writes a formatted string to a variable.


1 Answers

Assuming that your php file is inside the public_html too, you could use :

$fp = fopen( "newfile.txt", "rt" );

Or, giving the full path :

$fp = fopen( "/domains/xxxxx.com.au/public_html/newfile.txt", "rt" );

This will open it if it already exists.

Refer to this for further details of opening flags.

UPDATE: You can even use the is_writable/is_readable function to check file access before trying to open it.

like image 190
Simone Margaritelli Avatar answered Sep 29 '22 03:09

Simone Margaritelli