How to open a file and display its contents using php? [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a problem while trying to open a file and display its contents using php
My file called hello.txt
Here is my PHP code
<?php
$filename = 'hello.txt';
$filePath = 'c:\\Users\\bheng\\Desktop\\'.$filename;
if(file_exists($filePath)) {
echo "File Found.";
$handle = fopen($filePath, "rb");
$fileContents = fread($handle, filesize($filePath));
fclose($handle);
if(!empty($fileContents)) {
echo "<pre>".$fileContents."</pre>";
}
}
else {
echo "File Not Found.";
}
?>
I got this from
http://php.net/manual/en/function.fread.php
I keep getting error:
fread(): Length parameter must be greater than 0
Can someone help me please?

Although there are good answers here about using file_get_contents() instead, I'll try to explain wht this is not actually working, and how to make it work without changing the method.
filesize() function uses cache. You probably executed this code while still having the file empty.
Use the clearstatcache function each time the file change, or before testing its size :
clearstatcache();
$fileContents = fread($handle, filesize($filePath));
Also obviously make sure that your file is not empty ! Test it :
clearstatcache();
if(file_exists($filePath) && filesize($filePath)) {
// code
}

It needn't be that hard, and it certainly doesn't require you to read a file in binary mode:
if (file_exists($filePath))//call realpath on $filePath BTW
{
echo '<pre>', file_get_contents($filePath), '</pre>';
}
All in all, you really don't want to be doing this kind of stuff too much, though

If you need to read the entire file's content, there is a shortcut function
http://php.net/manual/en/function.file-get-contents.php
So you don't need to bother creating a file handler and closing it afterwards.
$fileContents = file_get_contents($filePath);

using file_get_contents method of php
echo file_get_contents("text.txt");

Related

PHP 'include' file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am working on a project which calls many php files via <?php include 'filename'; ?>
What I want to do is I want a php function or code that replaces all include occurences with the actual file, so that all my 6-7 files are converted into one single PHP file. I have to distribute it to many people, so having a single PHP file would be good in that context. Calling that php file would create a new php file with all the included files.
I want to ship my full project in a single file, just as adminer does !
Any idea how to do it ?
For example :-
...php-code...
<?php
include 'dologin.php';
?>
...php code...
would be converted to :-
...php code...
function dologin();{
...(dologin.php file)...
...php code...
You don't want to use include() here, what you essentially want to do is take a bunch of files and combine them into one. There's no need to actually parse the files as you go, you just need to open them, read until the end, and stick what you got into another file - repeating until done.
Something like this:
<?php
$sources = array('file1.php', 'file2.php', 'file3.php');
$out = fopen('final.php', 'w+');
if ($out === false)
die('Could not open output file');
foreach($sources as $source) {
$buff = file_get_contents($source);
fwrite($out, $buff);
}
fclose($out);
?>
Notes:
I do very little error checking here. What happens if you can't open one of the source files, or the length of what you read is wildly different from what you expect?
I do very little error checking here. What happens if fwrite() fails?
I do very little error checking here. Is it safe to just keep appending as I do? Should newlines be injected after each file is written to the output file? Are you sure you won't end up with a missing ?>
I do very little error checking here. No editor is going to accidentally save an input file with a byte-order-mark at the beginning?
You'll of course need to handle doing something with the generated file, and unlinking it once done (though the flags sent to fopen() will truncate it, which is why I went with that family of functions, aside from the convenience of file_get_contents()). Check the manual for more info on how they work.
Honestly, though - depending on your platform, a simple shell script would probably suffice. I'm pretty sure this is what you're trying to do from the extra info you edited into your question.
This is what I exactly wanted. Please improve this php code if you can.
<?php
$a = file_get_contents("sample file");
$match = "/include '.*';/";
preg_match_all($match, $a, $matches);
foreach($matches['0'] as $b)
{
$c = explode("'", $b);
$c = $c['1'];
$temp = file_get_contents($c);
if(preg_match("/<?php/", $temp))
{
$a = str_replace($b, "?>". file_get_contents($c) . " \n ?>\n<?php \n", $a);
}
else
{
$a = str_replace($b, "?>". file_get_contents($c) . "\n<?php \n", $a);
}
}
file_put_contents("combined.php", $a); ?>
I understood that You want to integrate the included file into a function.
I never thought of this question before because it's useless, but maybe you have some "unknown" reasson behind that, so i have to answer.
Here is how:
dologin.php
<?php
... php code
?>
the function:
function dologin(){
global $variable1;
global $variable2;
// paste php code from the dologin.php file here
}
NOTE:
change $variable1 and $variable2 to the variable that may be included from another file in your main file that you're trying to use the function in, if these variables are getting used in the function ithout doing this you'll face the variables scope problem.
That's it now you have a function instead of a PHP file.
Try this...
Note I haven't had a chance to test this but get_included_files gives you everything thats included then you can just build a new file with the contents of all of them.
<?php
...All the include statements ....
$my_includes = get_included_files ();
$file = "everything.php"
file_put_contents($file, "<?PHP");
foreach($my_includes as $included){
$file_contents = file_get_contents($included);
file_put_contents($file, $file_contents, FILE_APPEND);
}
$this_file = __FILE__;
// put the current file in and close
file_put_contents($file, $this_file, FILE_APPEND);
file_put_contents($file, "?>", FILE_APPEND);
?>

find and fopen a file with random/unknown name with php [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I've searched around google for a way to fopen and read a file with an unknown/random name in a specific folder with a specific extension (it will be the only file in that folder, but it gets updated every hour with a new name), but couldn't find anything. Previously the file had the same name every time unfortunately now it changes...
previously i had to only define it this way:
$file = "/var/uploads/quarter.csv";
$handle = #fopen($file, "r");
but with a random name it doesn't work anymore.
so, I've tried:
function the_file($dir = '/var/uploads/') {
$files = glob($dir . '/*.csv');
$file = $files;
}
$handle = #fopen($file, "r");
script continues...
but it doesn't work. Any help would be appreciated, thanks.
The $file variable doesn't exist outside the function scope and hence you won't be able to use it outside the function. Also, glob() returns an array -- if there is only one file, you can just get the first element of the array and return it, like so:
function the_file($dir = '/var/uploads/') {
$files = glob($dir . '/*.csv');
return $files[0]; // return the first filename
}
Now to store it in a variable, you can do:
$file = the_file(); // or specify a directory
# code ...
A possible solution can be:
If there is only one file in the directory, you can do a scandir to get the contents of the folder. (see PHP ref.)
$dir = 'your_folder_name';
$files1 = scandir($dir);
The content of the $files will be:
Array
(
[0] => .
[1] => ..
[2] => yourfile.csv
)
So you can get the full name of the file with:
$filename = $files1[2];

check if file exist in cPanel directory php [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I got a problem with my code. It's returning false. I have searched and tried some similar questions here but none of them helped. anyway, im using cPanel here. and i'm sure that the file really exists and so with the folder names. Hope you can help me with this. thanks in advance.
<?php
$filename = 'event-01.jpg';
if ( file_exists( $_SERVER{'/home2/user/public_html'} . "/MyProject/events/event-01.jpg")) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
i have also tried
$filename = 'event-01';
if (!file_exists('http://mysite.com/MyProject/events/event-01.jpg')) {
echo "The file $filename doesn't exist";
}
Problem
To put it bluntly; this...
file_exists( $_SERVER{'/home2/user/public_html'} . "/MyProject/events/event-01.jpg")
is not php.
Solution
Check a file exists
Assuming that the file path is actually:
/home2/user/public_html/MyProject/events/event-01.jpg
Then you should just be using that in file_exists:
file_exists("/home2/user/public_html/MyProject/events/event-01.jpg")
Server root
I assume that what you actually meant to do was:
file_exists($_SERVER['DOCUMENT_ROOT']."/MyProject/events/event-01.jpg")
You might also like to try to var_dump($_SERVER) to see all of the information that it stores.
References
file_exists: http://php.net/file_exists
$_SERVER: http://php.net/manual/en/reserved.variables.server.php
In PHP, $_SERVER is a superglobal containing various server related information and unrelated to what you're trying to achieve.
Simply try this instead:
if (file_exists("/home2/user/public_html/MyProject/events/event-01.jpg")) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}

Running hundreds of files through single PHP script [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to run 600 XML files through a script I've made that extracts specific pieces of information and saves each one in JSON format. All 600 XML files are inside a folder ready to be run through the PHP file, I'm now looking for a fast way to do it.
Essentially this is the process the PHP file goes through:
PHP reads single XML file via URL -> locally saves important info in variables -> saves important info into JSON file
Is there a way I can somehow run all 600 XML files through my PHP file?
Thanks
Open the directory containing the XML files and then process them, here are some of the most common way todo that.
opendir()
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
You can also use glob()
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
Inside the foreach loop of whichever you choose you can use file_get_contents() or fread() then you can do your conversion to json.
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Hope it helps
Just go ahead and try! You'll probably run into a timeout error. If you do, try configuring the max timeout settings. http://php.net/manual/en/function.set-time-limit.php
Joel,
Sounds to me like what you need to is to use readdir
http://php.net/manual/en/function.readdir.php
This will allow you to get a list of files in a directory to iterate over.
$dir = opendir('/path/to/files');
while($file = readdir($dir)) {
if ($file !== '.' && $file !== '..' && !is_dir($file)) {
$parthParts = pathinfo($file);
if ($pathParts['extension'] === 'xml') {
runscripton($file);
}
}
}
closedir($dir);
First, write a function that gets an XML file name, and after processing, returns the results in php array or JSON (Based on how you need your code to be).
To write this function, you need to parse XML (http://php.net/manual/en/book.xml.php).
To work with JSON in PHP: http://php.net/manual/en/book.json.php
Then, write your main code. Your main code should enumerate all XML files in the folder, and then call your function for each file, and gather/generate JSON using information returned by the function.
You might need readdir to gather all of XML files in the folder. (http://php.net/manual/en/book.xml.php)
Don't forget to increase time limit as long as there are lots of XML files and the process might take long so a timeout error would occur. (http://php.net/manual/en/function.set-time-limit.php)

Get A Value From Url parameter And Save It in txt file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to save a value from url parameter
into txt file on server.
$id = $_GET['id'];
I am getting value Dont know how to Save It in a Txt File.
All you have to do is open a file and write the contents:
$fd = fopen("FILENAME","w");
fwrite($fd, $id);
fclose($fd);
Look at the PHP manual: PHP Filesystem funcions
$filename = 'test.txt';
if ($handle = fopen($filename, "w")) {
fwrite($handle, $id);
}
fclose($handle);
You can use this way
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $id;
fwrite($fh, $stringData);
fclose($fh);
Okay, you have to open a file:
$datei_handle=fopen("part_of_url.txt",w);
Make Sure you use the right Mode!
Write your stuff if that.
fwrite($datei_handle,$your_url_part);
Close the file.
fclose($datei_handle);
Also check the Manuel. Pretty good explanation there I think.
http://php.net/manual/de/function.fwrite.php
Hope that help.

Categories