0

I am new to PHP and I am currently working on File Handling. I have a text file of which I am attempting to open for reading/appending using a skeleton script. The file is outputting and showing it is successfully opening, but only when I add a include function into the code. I have my code below, can someone look at it and tell me if I am doing it right because it feels right to me at the minute and it does output but i'm not 100% positive.

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
include($location);

if (file_exists($location) && $file = fopen($location, 'r')){
    $file_content = fread($file, filesize($location));
    fclose($file);
} else {
    echo 'File not found';
}

2 Answers 2

2

change your code to read and output file to below:

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
//include($location); remove include

if (file_exists($location) && $file = fopen($location, 'r')){
    $file_content = fread($file, filesize($location));
    echo $file_content; //<----echo here to display content
    fclose($file);
} else {
    echo 'File not found';
}
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to use file_get_contents().
It will also read the text file but it will read the text files full contents to a string.

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';

if (file_exists($location)){
    $file_content = file_get_contents($file);
    Echo $file_content;
    $file_content .= " And some more"; //append string to end of string
    Echo $file_content; // echo with appended string.
    File_put_contetnts($file, $file_content); // save the original text plus the appended.
} else {
    echo 'File not found';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.