|
użytkowników online: 57
|
OPINIE UŻYTKOWNIKÓW
|
Przyznam, że jestem pod sporym wrażeniem. Od wielu lat zajmuje się grafiką przeznaczoną do druku ze szczególnym uwzględnieniem opakowań. Z radością stwierdzam, iż twórca serwisu jest moim ulubionym typem potencjalnego współpracownika (choć branża troszeczkę inna) tzn. pada pytanie i błyskawicznie pada konkretna odpowiedź bez względu na stopień skomplikowania pytania. Gorąco polecam współpracę, gdyż macie pewność że nie zostaniecie potraktowani sloganami typu "oczywiście", "nie ma sprawy" tylko otrzymacie konkretną pomoc. Tak trzymać! Na pewno jeszcze nie raz skorzystam
Paweł
Studio Gama
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
file (PHP 3, PHP 4, PHP 5) file -- Czyta całą zawartość pliku do tablicy Opisarray file ( string nazwa_pliku [, int użyj_include_path [, resource kontekst]] )
Działa identycznie jak readfile(), tylko że
file() zwraca plik w tablicy. Każdy
element tablicy odpowiada linii w pliku. Elementy tablicy zawierają
znak nowej linii. W przypadku błędu, file()
zwraca FALSE.
Możesz użyć opcjonalnego parametru use_include_path i
ustawić go na "1", jeśli chcesz szukać pliku także w
include_path.
Podpowiedź: Jeśli włączona jest dyrektywa
konfiguracyjna fopen wrappers,
możliwe jest podanie jako nazwy pliku adresu URL. Zobacz opis funkcji
fopen() aby dowiedzieć się jak przekazać nazwę pliku, oraz
fopen wrappers aby uzyskać listę
obsługiwanych protokołów.
Notatka:
Każda linia w wynikowej tabeli będzie zawierać znak(i) końca linii,
jeśli nie chcesz ich musisz uzyć rtrim().
Notatka: W przypadku problemów z
rozpoznawaniem znaków końca linii przez PHP przy czytaniu
plików stworzonych lub znajdujących się na komputerach Macintosh, może pomóc
włączenie dyrektywy konfiguracji auto_detect_line_endings.
Notatka:
W PHP 4.3.0 możesz użyć file_get_contents() aby
zwrócić zawartość pliku do łańcucha.
W PHP 4.3.0 file() stał się binarnie bezpieczny.
Notatka: Wsparcie dla kontekstów zostało
dodane w PHP 5.0.0.
| Ostrzeżenie | Łącząc się przez SSL, serwer
Microsoft IIS pogwałca reguły protokołu przez zamknięcie połączenia bez
wysłania znacznika close_notify. PHP zgłosi to jako "SSL: Fatal Protocol Error"
po przesłaniu całości danych. Aby obejść ten błąd, wystarczy obniżyć poziom
raportowania błędów (error_reporting) aby nie były
wyświetlane ostrzeżenia. PHP w wersji 4.3.7 i nowsze wykrywa obecność
zepsutego serwera IIS przy otwieraniu strumienia przez wrapper https:// i
wyłącza wyświetlanie tych ostrzeżeń. Używając funkcji
fsockopen() do otwarcia gniazda ssl:// należy samemu
zatroszczyć się o wyłączenie ostrzeżeń. |
Patrz także: readfile(),
fopen(), fsockopen(), popen(),
file_get_contents()
i include().
User Contributed Notesjonathan dot gotti at free dot fr
01-Feb-2006 11:52
you can use
$file = array_map('rtrim',file('myfile.txt'));
to remove annoying ending lines of the resulting array.
Nuts
19-Jan-2006 12:16
WARNING ON WINDOWS:
file() function will add "\r\n" in to the end of the row, even if you use only "\n" char to make rows in the file!
On UNIX systems there is no such problem.
brunosermeus at gmail dot com
25-Dec-2005 07: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 02:37
I used the config file reader written by mvanbeek at supporting-role dot co dot uk for one of my own scripts. 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 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) com
11-Sep-2005 03:59
This code will help you if you want to pass the URL to the script by GET and the URL includes "&", so the address bar looks like "http://www.example.com/script.php
?url=http://www.example.com/script2.php
?var1=value1&var2=value2&var3=value3"
and the effect of
echo $_GET['url'];
is
"url=http://www.example.com/script2.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/script2.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 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
undejj
28-Jul-2005 05: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 descriptive.
camilokawerin(at)ciudad(dot)com(dot)ar
21-Mar-2005 01: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.
$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]};
}
}
redzia
08-Feb-2005 04: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 uk
14-Jan-2005 05: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 com
10-Jan-2005 09: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.)com
04-Jan-2005 03: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.)com
23-Dec-2004 02: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$com
03-Oct-2004 09: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 com
21-Jul-2004 10: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 uk
18-Jun-2004 02: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 com
12-Jun-2004 04:18
heres a little script 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 org
14-Apr-2004 07: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.fr
29-Feb-2004 09: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 info
12-Feb-2004 11: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 uk
31-Dec-2003 06:39
I needed a cross platform config file for a project using both perl and php, so I used the perl script in the Perl Cookbook, and wrote the following PHP script. 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.
global-thenumberafterzero at nospam dot web dot de
31-Oct-2003 04:21
If you want a more powerful tool to open files you may want to use the curllib functions. If curllib is installed on your Server it is probably the best (but not fastest) tool for opening files. More information you can find here:
http://curl.haxx.se
or on php.net:
http://de.php.net/manual/de/ref.curl.php
dir @ badblue com
12-Sep-2003 11: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 @ badblue com
hhw
23-Aug-2003 05:43
The following function can handle text files whose line endings are whatever <LF> (*nix), <CR><LF> (M$) or <CR> (Mac)
function file2($filename) {
$fp = fopen($filename, "rb");
$buffer = fread($fp, filesize($filename));
fclose($fp);
$lines = preg_split("/\r?\n|\r/", $buffer);
return $lines;
}
John
21-Jul-2003 01:32
after many months of confusion and frustration, i have finally figured out something that i should have noticed the first time around.
you can't file("test.txt") when that same file has been flocked. i guess i didn't have a full understanding of what i was doing when i used flock(). all i had to do was move the flock() around, and all was well.
webmaster AT the-afterburner DOT de
25-Mar-2003 01:35
If you want to send a URL via GET to a script and want to open this URL via file() there are problems if there is a & sign in the URL, all after die & sign is cut.
TO fix this an get it working with the & sign in the URL
@$myopenedcontent= implode("", file ("$url"));
$myopenedcontent=eregi_replace('&','{KU}',$myopenedcontent);
so all & signs are replaced by {KU}
before use the file() function you have to rereplace it, the whole code:
$url=eregi_replace('{KU}','&,$url);
@$myopenedcontent= implode("", file ("$url"));
$myopenedcontent=eregi_replace('&','{KU}',$myopenedcontent);
echo "$myopenedcontent";
hope it is helpful ;)
Bye
Afterburner
justin at visunet dot ie
20-Mar-2003 06:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:
$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
The resulting array is $lines.
I did a test on a 200,000 line file. It took seconds with fgets() compared to minutes with file().
gaurav_saparia at yahoo dot com
17-Mar-2003 11:47
<?
$headers = "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: $sendername <$senderemail>\r\n";
$contents = implode("",file("newsletter.htm") );
echo($contents);
$a_list = array() ;
$a_list = file("mail_list.txt") ;
echo("<h6>Total ".count($a_list)." email addresses found in the list </h6><br>") ;
$cnt = 0 ;
for($i=0 ;$i<count($a_list) ; $i++)
{
$cnt ++ ;
echo($cnt . "....sending mail to ".$a_list[$i] ."....") ;
mail($a_list[$i],$sub,"$contents","$headers");
echo("Done .....<br>");
}
?>
03-Mar-2003 11:16
akaylaa at yahoo dot com
06-Dec-2002 08:01
a quick way to count the number of lines in a file is
$lines = file ('filename');
$num_lines = count ($lines);
echo ("Total lines in file: " . $num_lines);
e dot maccarthy at csuohio dot edu
03-Jun-2002 12:04
[[Editors note: using fopen/fgets instead of file() would be more efficient for this task as there is no need to load the entire file into memory]]
Here is a quick snippet that will read in N number of lines of a file, then print them.
$n=10
$fp = file('/path/to/your/file');
$i=0
while($i < $n){
echo "$fp[$i]";
$i++;
}
I am using this right now to display the current progress of the seti@home client working on my server, instead of displaying the whole thing, which isn't web page friendly.
Because sometimes short really is sweet...
andrea at brancatelli dot it
16-Mar-2002 08:16
file() has a strange behaviour when reading file with both \n and \r as line delimitator (DOS files), since it will return an array with every single line but with just a \n in the end. It seems like \r just disappears.
This is happening with PHP 4.0.4 for OS/2. Don't know about the Windows version.
php@don't_spam_me
09-Feb-2002 09:56
It appears that the file() function causes file access problems for perl cgi scripts accessing the same files. I am using Perl v5.6.0 in linux with PHP/4.0.4pl1. After running a php app using the file() function, any perl cgi trying to access the same file randomly dies returning an internal server error: premature end of script headers.
The simple fix is to use fopen(), fgets() and fclose() instead of file().
|