|
|
|
|
| file |
 |
|
|
| ±Û¾´ÀÌ : ¼Õ´Ô
³¯Â¥ : 06-01-03 08:06
Á¶È¸ : 880
|
|
http://cafe.naver.com/q69/10064 (182) | |
|
|
|
file
(PHP 3, PHP 4 , PHP 5) file -- ÆÄÀÏÀüü¸¦ ¹è¿·Î ÀоîµéÀÓ
Descript-xionarray file ( string filename [, int use_include_path])
file()ÀÌ ÆÄÀÏÀ» ¹è¿·Î ¹ÝȯÇÏ´Â °ÍÀ» Á¦¿ÜÇϰí´Â readfile()°ú °°½À´Ï´Ù. »õ·Î¿î ¶óÀÎÀÌ ¿¬°áµÇ´Â °ÍÀ» Æ÷ÇÔÇØ¼ ¹è¿ÀÇ ¸Å ¿ä¼Ò´Â ÆÄÀÏÀÇ ¶óÀΰú ºñ½ÁÇÕ´Ï´Ù.
ÆÄÀÏ¿¡¼ include_path¿¡¼ ÆÄÀÏÀ» ã°í ½Í´Ù¸é µÎ¹øÂ° ¸Å°³º¯¼ö·Î "1"À» »ç¿ëÇÏ¸é µË´Ï´Ù.
ÂüÁ¶: readfile(), fopen(), fsockopen(), ±×¸®°í popen().
brunosermeus at gmail dot com25-Dec-2005 06:08
I've creates this function to have my own hitcounter on my site; the function writes to a file and returns the value.
Created by Mr.B
<?php function hitcount() { $file = "counter.txt"; if ( !file_exists($file)){ touch ($file); $handle = fopen ($file, 'r+'); $count = 0;
} else{ $handle = fopen ($file, 'r+'); $count = fread ($handle, filesize ($file)); settype ($count,"integer"); } rewind ($handle); fwrite ($handle, ++$count); fclose ($handle); return $count; } ?>
com dot gmail at trucex [reverse order]02-Nov-2005 01:37
I used the config file reader written by mvanbeek at supporting-role dot co dot uk for one of my own script-xs. I have made some modifications, and turned it into a class.
<?
class config_reader { var $filename; var $databaseHost; var $databaseName; var $databaseUser; var $databasePassword;
function config_reader () { $this->filename = './settings.conf'; $this->getSettings(); } function getSettings () { $config = file($this->filename); reset($config); foreach ($config as $line) { $line = rtrim($line); $line = ltrim($line); if ($line == "" || $line == "\n" || strstr($line,"#") == 1) { next($config); } else { list($key, $value) = preg_split("/\s*=\s*/", $line, 2); $this->$key = $value; } } } }
?>
Changes: - I have cleaned up the layout of the code for readability and faster execution. - I have moved the rtrim and ltrim functions to execute before the line check, to make sure the line wasn't just a space, or a comment after a space. - I changed strstr($line, "#") to strstr($line, "#") == 1 to make sure that lines with a comment after the values are not left behind. - I also changed the way preg_split assigns the results, primarily to clean up the code. - I changed the way values are assigned to the variables. For me, this works better because I only needed to get the database information from the user. If you would like a dynamic listing of variables, do the following:
Remove the following lines: <? var $databaseHost; var $databaseName; var $databaseUser; var $databasePassword; ?>
Add this line: (commented lines are only to provide location for new line) <? var $settings; ?>
Then change this line: <? $this->$key = $value; ?>
to this: <? $this->settings[$key] = $value; ?>
NOTE: This has not actually been executed, so their might be a small error. I don't recommend use of this script-x by those new to PHP, as you will need an understanding of file permissions and setting the variables in classes.
rohan (dot) mk1 (at) gmail (dot) com11-Sep-2005 01:59
This code will help you if you want to pass the URL to the script-x by GET and the URL includes "&", so the address bar looks like "http://www.example.com/script-x.php ?url=http://www.example.com/script-x2.php ?var1=value1&var2=value2&var3=value3" and the effect of echo $_GET['url']; is "url=http://www.example.com/script-x2.php?var1=value1" because everything after the "&" is stored in other variables, so the $_GET array contains the foollowing key/value pairs:
$_GET ( [url] => url=http://www.example.com/script-x2.php?var1=value1 [var2] => value2 [var3] => value3 )
This will give the file() function the proper url:
<?php $url = $_GET['url']; $array = array(); $count = 1; if (array_key_exists('customvar1', $_GET)) { $count += 1; } while (list($key, $val) = each($_GET)) { if ($count) { $count -= 1; } else { $array[] = $key . "=" . $val; } } $urlending = "&" . implode("&", $array); $url .= $urlending; ?> the counter may be removed, but $array will also contain $url, so be careful and use only: $url = implode("&", $array);
If you can't use the following code for any reason, pass to the script-x the address with additional "anything=" after every "&" and then use $url .= implode ('&', $_GET); NOTE: The 'anythings' must be different after each '&'.
Hope thet helps someone
undejj28-Jul-2005 03:11
I created a function to grab the title of a file from another central file that associates filenames to titles, one per line.
Format of the titles.ini file is: "filename.ext","This is my title" "filename2.ext","This is another title"
<?php function filetitle($file) { $lines = file("files/titles.ini"); foreach ($lines as $key => $value) { if(strpos($value, $file) > 0) { $s = strpos($value, ",")+2; $title = substr($value, $s, -2); break; } else { $title = $file; break; } } return $title; } ?>
I use this for directory listings where the filenames are not very descript-xive.
camilokawerin(at)ciudad(dot)com(dot)ar21-Mar-2005 12:46
This function allows to read configuration files like this:
[level_0] total=>8 [level_1] 1=3 [/level_1] [level_1] [level_2] 1=something [/level_2] [/level_1] [/level_0]
where 'level_n' may be replaced by any label to create a tree structure. This is usefull to fill an array with all the values you need in one script-x.
$archivo="configuration.txt"; $resultado=file($archivo); reset($resultado); $n=0; foreach ($resultado as $linea) { if (ereg("^\[\/.*\]$", rtrim($linea))) { //close labels $n=$n-1; } elseif (ereg("^\[.*\]$", trim($linea), $nombre)) { //open labels $n+=1; $nivel[$n]=ereg_replace("(\[|\])", "", $nombre[0]); } elseif (($linea!="") and ($linea!="\n") and !ereg("(\/\*|\*\/)", $linea)) { //ignore empty lines and comments in '/* */' format $pares=explode("=", trim($linea)); //separate key and value for($i=$n; $i>0; $i--) { //fill the array if ($i==$n) {${$nivel[$i]}[$pares[0]]=$pares[1]; } else {${$nivel[$i]}[$nivel[$i+1]]=${$nivel[$i+1]}; } } $propiedades[$nivel[1]]=${$nivel[1]}; } }
redzia08-Feb-2005 03:55
Example usage of file to remove line containing a key string <?
$key = "w3ty8l";
$fc=file("some.txt");
$f=fopen("some.txt","w");
foreach($fc as $line) { if (!strstr($line,$key)) fputs($f,$line); } fclose($f);
?>
Jason dot haymer at Haymer dot co dot uk14-Jan-2005 04:58
Beware of using file() to call a URL from a remote server on a live Web site, as there is no way to set a maximum connection time.
To exemplify this I cite the circumstance of a Web site which receives content from a remote server in the form of an XML feed. If the remote server does not respond, the Web page will hang and if this is a regular occurance, the parts of the Web site which use the feed may often prove inaccessible to search engine robots, possibly resulting in their removal from the search engine indices.
Here is an alternative function which like file() can be used to retrieve a remote feed, but which imposes a maximum connection time, after which the page will be displayed without the feed.
<?
function fetchUrlWithoutHanging($url) { $numberOfSeconds=4;
error_reporting(0);
$url = str_replace("http://","",$url); $urlComponents = explode("/",$url); $domain = $urlComponents[0]; $resourcePath = str_replace($domain,"",$url);
$socketConnection = fsockopen($domain, 80, $errno, $errstr, $numberOfSeconds);
if (!$socketConnection) { print("<!-- Network error: $errstr ($errno) -->"); } else { $xml = ''; fputs($socketConnection, "GET /$resourcePath HTTP/1.0\r\nHost: $domain\r\n\r\n"); while (!feof($socketConnection)) { $xml .= fgets($socketConnection, 128); } fclose ($socketConnection);
} return($xml);
} ?>
rpanning at hotmail dot com10-Jan-2005 08:50
A quick way to trim the array: <?php function file_trim(&$value, $key) { $value = trim($value); }
$file = file('name.txt'); @array_walk($file, 'file_trim'); ?>
corychristison[-At]lavacube(dot.)com04-Jan-2005 02:56
Just realized that the function I posted above should have one small modification:
The line: <?php $open_data[$line] = rtrim(fgets($open, $buffer_size)); ?>
Should probably be: <?php $open_data[$line] = rtrim(fgets($open, $buffer_size), "\n"); ?>
corychristison[-At]lavacube(dot.)com23-Dec-2004 01:52
The file function will load the entire file before you can do anything to it [remove lines, explode() each line, and so on...]
I wrote a function [ file_v2() ] to help eliminate the restrictions of file(). Below are a few features/abilites file_v2() has over file().
file_v2() features: - uses an editable buffer size, for performance tweaking. - ability set maximum lines returned[from beginning] - optional automatically rtrim the line - optional ability to provide a callback function for each array element
Here is the code:
<?php
function file_v2 ( $filename, $return_max_lines=0, $callback_func=null, $do_rtrim=true, $buffer_size=1024 ) {
$open = fopen( $filename, 'rb' );
$open_data = array();
$line=0;
while( !feof($open) ) { if( $do_rtrim ) { $open_data[$line] = rtrim(fgets($open, $buffer_size)); } else { $open_data[$line] = fgets($open, $buffer_size); }
if( $callback_func != null && function_exists( $callback_func ) ) { eval($callback_func . '($open_data[$line]);'); }
$line++; if( $return_max_lines > 0 ) { if( $line >= $return_max_lines ) { break; } } }
fclose($open);
return $open_data; }
?>
Example usage:
========= file_test.txt ========= 01 firstname_1 lastname_1 fake_email@fake_addr1.fk 02 firstname_2 lastname_2 fake_email@fake_addr2.fk 03 firstname_3 lastname_3 fake_email@fake_addr3.fk 04 firstname_4 lastname_4 fake_email@fake_addr4.fk 05 firstname_5 lastname_5 fake_email@fake_addr5.fk 06 firstname_6 lastname_6 fake_email@fake_addr6.fk 07 firstname_7 lastname_7 fake_email@fake_addr7.fk 08 firstname_8 lastname_8 fake_email@fake_addr8.fk 09 firstname_9 lastname_9 fake_email@fake_addr9.fk 10 firstname_10 lastname_10 fake_email@fake_addr10.fk 11 firstname_11 lastname_11 fake_email@fake_addr11.fk 12 firstname_12 lastname_12 fake_email@fake_addr12.fk
========= test.php ========= <?php
function mk_callback( &$input ) { $input = explode("\t", $input); }
$open = file_v2('file_test.txt', 3, 'mk_callback');
print_r($open);
?>
Example will output: Array ( [0] => Array ( [0] => 01 [1] => firstname_1 [2] => lastname_1 [3] => fake_email@fake_addr1.fk )
[1] => Array ( [0] => 02 [1] => firstname_2 [2] => lastname_2 [3] => fake_email@fake_addr2.fk )
[2] => Array ( [0] => 03 [1] => firstname_3 [2] => lastname_3 [3] => fake_email@fake_addr3.fk )
)
This is one of my few contributions to this fine world. Happy coding everybody!
- Cory Christison
thecelestialcelebi^hotmail$com03-Oct-2004 07:33
<?php $textfile = "Includes/Quotes.txt"; if ($quotes = @file("$textfile")) { $quote = rand(0, sizeof($quotes)-1); echo $quotes[$quote]; }else{ echo ("default quote"); } ?>
Why all those variables? :x
<?php $sTextfile = "Includes/Quotes.txt"; if ($aQuotes = @file($sTextfile)) { echo $aQuotes[array_rand($aQuotes)]; } else { echo 'blaat'; } ?>
andyg at stingrayboats dot com21-Jul-2004 08:27
i tried for quite sometime to get my pdf to attach right some of you may want to try reading it as binary first then base 64 it.
//this did not work for me with a pdf file it came in garbled $data = chunk_split(base64_encode(implode("", file($filelocation)))); //but tis seemed to make it work correctly $data = fread($file,filesize($filelocation)); fclose($file); $data = chunk_split(base64_encode($data));
kangaroo232002 at yahoo dot co dot uk18-Jun-2004 12:03
Instead of using file() for parsing ini / conf files, as shown in mvanbeek at supporting-role dot co dot uk's example below (above?), a great function that puts all your conf info into an associative array is parse_ini_file($filename); very useful !
ian.
J at TIPPELL dot com12-Jun-2004 02:18
heres a little script-x to return a random quote from a quotes file.
<?php $textfile = "Includes/Quotes.txt"; if ($quotes = @file("$textfile")) { $quote = rand(0, sizeof($quotes)-1); echo $quotes[$quote]; }else{ echo ("default quote"); } ?>
lance at lancemiller dot org14-Apr-2004 05:55
This is just a presentation idea extending the php example. Anchor links as line numbers and the document in a table data field of it's own so it can be easily copy/pasted. <?php $lines=file("http://www.example.com"); echo "<table border=1><tr><td>\n"; foreach ($lines as $line_num => $line) { echo "<a name=".$line_num."><a href=\"#".$line_num."\">".$line_num."</a><br>\n"; } echo "</td><td>\n"; foreach ($lines as $line_num => $line) { echo htmlspecialchars($line)."<br />\n"; } echo "</td></tr></table>\n"; ?>
http://iubito.free.fr29-Feb-2004 08:09
Another way to do mvanbeek at supporting-role dot co dot uk (31 december) config reader.
I've an array $config <?php $array_tmp = file('configfile.txt'); foreach($array_tmp as $v) { if ((substr(trim($v),0,1)!=';') && (substr_count($v,'=')>=1)) {$pos = strpos($v, '='); $config[trim(substr($v,0,$pos))] = trim(substr($v, $pos+1)); } } unset($array_tmp); ?>
The configfile : variable = value will be loaded into $config['variable'] = 'value'; it trims spaces near the '=', don't read lines starting with a ';' (it can have spaces and tabs before the ';' ).
Have a nice day :)
skipjack at skipjack dot info12-Feb-2004 10:45
this a little function I wrote that checks if two ascii files are the same. it opens the file then removes the spaces then coverts the crc32 to base 10 and compares the results. function fcheck($tool) { if(fopen("file.01", "r") != FALSE){ $fp1 = 'file.02'; $fp = 'semcond.01';
$data = implode(" ", file($fp)); $data1 = implode(" ", file($fp1)); $test1 = (dechex(crc32($data))); $test2 = (dechex(crc32($data1))); if($test1 == $test2) $sfv_checksum = 'TRUE'; else $sfv_checksum = 'FALSE'; return $sfv_checksum; }
}
mvanbeek at supporting-role dot co dot uk31-Dec-2003 05:39
I needed a cross platform config file for a project using both perl and php, so I used the perl script-x in the Perl Cookbook, and wrote the following PHP script-x. This going in an include file that all the PHP files reference, so the only thing that needs to be do for set up, is to set the location of the config file.
$filename = "/opt/ssis/includes/ssis-config"; $config = file($filename); reset ($config); foreach ($config as $line) { if ( $line == "" ) next($config); # Ignore blankline elseif ( $line == "\n" ) next($config); # Ignore newline elseif ( strstr($line,"#")) next($config); # Ignore comments else { $line = rtrim($line); # Get rid of newline characters $line = ltrim($line); # Get rid of any leading spaces $value = preg_split("/\s*=\s*/", $line, 2); # split by "=" and removing blank space either side of it. ${Settings}["$value[0]"] = $value[1]; # Create a new array with all the values. } }
I am sure there is a neater way of doing it, but all the Config libaries floating arround seemed very complicated. All the config file needs is a series of lines ( key = value ) in plain text.
dir @ badblue com12-Sep-2003 09:48
Jeff's array2file function is a good start; here are a couple of improvements (no possibility of handle leak when fwrite fails, additional capability of both string2file and array2file; presumably faster performance through use of implode).
function String2File($sIn, $sFileOut) { $rc = false; do { if (!($f = fopen($sFileOut, "wa+"))) { $rc = 1; break; } if (!fwrite($f, $sIn)) { $rc = 2; break; } $rc = true; } while (0); if ($f) { fclose($f); } return ($rc); }
function Array2File($aIn, $sFileOut) { return (String2File(implode("\n", $aIn), $sFileOut)); }
If you're generating your string text using a GET or POST from a TEXTAREA (e.g., a mini-web-text-editor), remember that strip_slashes and str_replace of "/r/n" to "/n" may be necessary as well using these functions.
HTH --dir @ bad
|
|
|
|