Browser Output using fread() - php

I am new to PHP and was just trying to write and then read a html file with following code:
<?php
#Aim: To open , write, save and close a file in PHP
$fileName = "myFile.html";
$filePointer = fopen($fileName,"w+"); // Creating a file resource
$html = '<html>
<style>
h1{color:#ee4e91;}
</style>
<body>
<h1>This is some HTml that was written to the File using the
file pointer $filePointer in the file that is named as myFile</h1>
</body>
</html>
'; // string to be written to the file in write+ mode*/
write($filePointer,$html); // writing the string to the file
fseek($filePointer,0);
$content = fread($filePointer,filesize($fileName));
header("Content-Length:".(string)filesize($fileName));
header("Content-Type:text/html");
echo $content;
fclose($filePointer); // closing the file resource
?>
I can see the out in the console but fail in the browser. file_get_contents($fileName) and readfile($fileName) work fine .
What is the problem.How can I use fread() to output to the browser ?

Related

My fopen function works, but the fwrite function doesn't

So I'm trying to create a file and write code into that file whenever a user submits a register and successfully moves on to the activation stage. I'm doing this so that I can store all of the variables and information in my registration php file into the file I create. This is relevant code of the signup form:
#$file is set in removed code
$filename = '../' . $file;
fopen($filename, "w") or die("<h1 style='text-align: center; color: red;'>There has been an error creating your user files. Try again later.</h1>");
$content = "
<?php
potato
?>
";
fwrite($filename, $content);
Everything works, except for the fwrite() function. I looked at the file I created, and nothing appears in it. What's going on?
fopen() returns a stream resource bound to $filename. When you call fwrite(), the first parameter it takes is the resource returned by fopen(). Not the filename.
So change the relevant part of your program to this:
$handle = fopen($filename, "w") or die("...");
$content = "foobar";
fwrite($handle, $content);
fclose($handle); // Don't forget to close when you're done.

How to get text from txt file

I'm creating a html template with notification under nav bar , and admin can change that notification from the system the text of notification bar will be from notetxt file from the same location path where index.html is located i ave tried
<?php
foreach (glob("note.txt") as $filename) {
readfile($filename);
}
?>
and many other way but nothing happens it still stay blank
You are not echoing out the content of the textfile.
do it like this:
$myFile = "note.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
This will output your content of the file.
i'm using this code in pure html file
You can't use PHP functions in plain HTML file. MUST be written in a PHP file.
You have now in your code:
<span>
<!--?php
foreach (glob("note.txt") as $filename) {
$fileArr = file_get_contents($filename);
}
?-->
</span>
Try with the examples above in a proper PHP file... then must work.
you can use file_get_contents function,
try something like this :
<?php
foreach (glob("note.txt") as $filename) {
$fileArr = file_get_contents($filename);
}
?>
It's very simple use file_get_contents();
<?= file_exists('note.txt') ? file_get_contents("note.txt") : "file doesn't exists"; ?>
That is all what you need. file_get_contents() get the content of file and returns it. I've also checked if file exists because it may be your problem. Also make sure you have proper rights to read the file(CHMOD) and file is not empty.

How to update static HTML files with PHP

We've 700 static HTML files in folder "music". We want to put analytic code in the end of the HTML files.. like before
</body> </html>
tags.
Please anybody let me know, how its possible with PHP code?
Too easy. Find all files, read content, modify content, save content.
<?php
// open directory
if($handle = opendir(__DIR__)) {
// search for
$search = '</body>';
// replace with (</body> gets appended later in the script)
$replace = <<< EOF
<!-- your analytics code here -->
EOF;
// loop through entries
while(false !== ($entry = readdir($handle))) {
if(is_dir($entry)) continue; // ignore entry if it's an directory
$content = file_get_contents($entry); // open file
$content = str_replace($search, $replace . '</body>', $content); // modify contents
file_put_contents($entry, $content); // save file
}
}
echo 'done';
?>

Why when writing html file with PHP stalled at '&'?

I have an issue about writing HTML file with PHP.
I have this function :
function openHTML ($file) {
if (file_exists($file)) {
$handle = fopen($file, "r");
$output = fread($handle, filesize($file));
fclose($handle);
return $output; // output file text
}else{
return "This file is not exists";
}
}
function saveHTML ($file,$string) {
$a = fopen($file, 'w');
fputs($a,stripslashes($string));
fclose($a);
return "success";
}
When I'm using openHTML it's fine. But unfortunately, in file that I opened with openHTML() there are some &, and then I'm saving with saveHTML() but then string or codes that save stalled at char &.
Example : UPDATE !
I open blank file.html with openHTML() and I start to type some string bellow :
<html>
<head>
</head>
<body>
This is my login page & user page
</body>
</html>
After I save with code saveHTML():
<html>
<head>
</head>
<body>
This is my login page
At last code to be missing. Stalled at &.
I have using fputs, utf8_encode, fwrite, file_put_contents. Still not solved.
try
$output = htmlentities($output);
on the string your going to save.
check it out here
It will change all HTML entities to their applicable charactors.
In this case your & will be changed to
&
Lone ampersands are invalid in a PCDATA section. Use & instead.
Try to use fwrite() instaed of fputs()

How to write into a file in PHP?

I have this script on one free PHP-supporting server:
<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>
It creates the file lidn.txt, but it's empty.
How can I create a file and write something into it,
for example the line "Cats chase mice"?
You can use a higher-level function like:
file_put_contents($filename, $content);
which is identical to calling fopen(), fwrite(), and fclose() successively to write data to a file.
Docs: file_put_contents
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);
http://php.net/manual/en/function.fwrite.php
$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);
You use fwrite()
It is easy to write file :
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
Here are the steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in the form action and the target file in fopen() function if you want to use it on your site.
In order to write to a file in PHP you need to go through the following steps:
Open the file
Write to the file
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "a");
fwrite($file , $select->__toString());
fclose($file );
fwrite() is a smidgen faster and file_put_contents() is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename
Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
Write the data into the file and Close the file and release any locks.
This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.

Categories