Sie sind auf Seite 1von 20

<?php // These will all perform the required output the same echo "Hello World!

"; print "Hello World!"; print ("Hello World!"); ?>

Poti adauga cod html si css in codul php


<?php echo '<div style="background-color: #639; padding:8px; width:110px;"> <font color="#FFFF00"><strong>Hello World!</strong></font> </div>'; ?>

<?php // Define your variable and its value $name1 = "Joe"; // Create a simple function that will display a sentence function sampleFunction() { // Set $name1 variable as global global $name1; // Now echo a sentence to the browser echo "Hello $name1, welcome to my web page."; } // This is how you can execute a function to run, we talk more about function s later sampleFunction(); ?> $_GET $_POST $_REQUEST $_FILES $_SESSION $_COOKIE $GLOBALS $_SERVER $_ENV Stores any variables created using the GET method Stores any variables created using the POST method Stores any variables created through a user input script (it can access both POST or GET) Stores any file upload variables created through user input scripts Stores any variables created through registering session variables Stores any variables created through setcookie Stores any variables that have been globally defined Stores server information such as headers, file names, reference paths, and current page. Stores any variables associated with the server environment.

<?php //Obtain user IP address $ip = $_SERVER['REMOTE_ADDR']; // Obtain browser $browser = $_SERVER['HTTP_USER_AGENT']; // Obtain user system language $language = $_SERVER['HTTP_ACCEPT_LANGUAGE']; // Obtain the URL of the page that they came from $referingURL = $_SERVER['HTTP_REFERER']; // Obtain the page they are currently on $currentPage = $_SERVER['REQUEST_URI']; // Now show all of that information on page echo "$ip <br />"; echo "$browser <br />"; echo "$language <br />"; echo "$referingURL <br />"; echo "$currentPage <br />"; ?>

Magic constants
<?php // __LINE__ Returns the current line number of the file. echo __LINE__; echo "<br />"; // __FILE__ Returns the full path and filename of the file. If used inside a n include, the name of the included file is returned. echo __FILE__; echo "<br />"; // __FUNCTION__ Returns the function name the code is currently executing in side of echo __FUNCTION__; echo "<br />"; // __CLASS__ The class name. As of PHP 5 this magic constant returns the clas s name as it was declared. echo __CLASS__; echo "<br />"; ?>

Variabile
<?php // Boolean... true or false data types $userChoice = true; // Integer.... whole numbers $num1 = 3; // Floating Point Numbers $num2 = 8.357 // String... a set of alphanumeric characters $string1 = "Hello World, I just turned 21!"; // Array... we cover building arrays in later lessons $my_friend_array = array(1 => 'Joe', 2 => 'Adam', 3 => 'Brian', 4 => 'Susan', 5 => 'Amy', 6 => '0', 7 => 'Bob'); // Null... value for missing, empty, or unset variables. If null... it has no value and is not set. $var1 = NULL; // Casting a variable to null will remove the variable and unse t its value ?>

PHP face conversia automat pentru tine


<?php $var1 = "18 years old"; $var2 = "14 years old"; // Since PHP knows that it cannot add two strings mathematically it automatic ally // removes the string parts of the variables and proceeds to do the math correctly $sumOfBoth = $var1 + $var2; // Very interesting that we get such a result and not an error echo $sumOfBoth; ?> <?php // Same variable and value $var1 = "250gb"; // This time use settype() and claim integer as the data type settype($var1, 'integer'); $var1 = (integer) $var1; // acelasi lucru echo "You stated that your Hard Drive size capacity is " . $var1 . " Gigabyte s"; ?>

Concatenarea se face cu .

Concatenarea la ceva se face cu .=

EX: $htmlOutput .= '<table bgcolor="#663366" cellpadding="8">';

Switch
<?php while ($flavor = "chocolate") { switch ($flavor) { case "strawberry"; echo "Strawberry is stock!"; break 2; // Exits the switch and the while case "vanilla"; echo "Vanilla is in stock!"; break 2; // Exits the switch and the while case "chocolate"; echo "Chocolate is in stock!"; break 2; // Exits the switch and the while default; echo "Sorry $flavor is not in stock"; break 2; // Exits the switch and the while } } ?>

Continue
<?php for ($i = 1; $i <= 10; $i++) { if ($i <= 5) { continue; } echo "$i, "; } ?> 6, 7, 8, 9, 10

<?php // define a variable that holds a URL string value $url = "http://www.developphp.com"; // Use PHP's "str_replace" built in function to remove what we do not want in the value $new_url = str_replace("http://www.", "", $url); // Now echo out the new adjusted value to view echo "$new_url"; ?>

Vectori <?php $cart_array = array("cereal", "coffee beans", "bananas", "onion"); ?>


echo serialize($cart_array); a:4:{i:0;s:12:"Wonder Bread";i:1;s:7:"Pickles";i:2;s:10:"Moyannaise";i:3;s:7:"Lettuce";} a: = Number of items in the array { } = Contains all items in the array i: = That array item's index or increment number s: = That array item's character count (size) and value Now let's force the index number of our keys to start from 1 instead of the default 0 <?php $cart_array[1] = "Wonder Bread"; $cart_array[2] = "Pickles"; $cart_array[3] = "Moyannaise"; $cart_array[4] = "Lettuce"; echo echo echo echo echo echo echo echo echo ?> $cart_array[1]; "<br />"; $cart_array[2]; "<br />"; $cart_array[3]; "<br />"; $cart_array[4]; "<br /><hr />"; serialize($cart_array);

Wonder Bread Pickles Moyannaise Lettuce a:4:{i:1;s:12:"Wonder Bread";i:2;s:7:"Pickles";i:3;s:10:"Moyannaise";i:4;s:7:"Lettuce";}


<?php $cart_array["cereal"] = "5.00"; $cart_array["coffee beans"] = "2.50"; $cart_array["bananas"] = "3.50"; $cart_array["onion"] = "1.00"; $cart_array["lettuce"] = "2.40"; $cart_array["tomato"] = "1.00"; // and here is how you can output any key's value you choose echo "Bananas cost $" . $cart_array["bananas"] . " at this store."; echo "<br /><br />"; // And here is how you can print the whole array for viewing and debugging print_r($cart_array); ?> Sau poate fi definit astfel

$cart_array = array( "cereal" => "5.00",

.....

};

<?php // create a multidimensional array that holds member details from our site $members = array ( "member1" => array ( "name" => "John", "zodiac" => "Scorpio", "country" => "USA" ), "member2" => array ( "name" => "Susan", "zodiac" => "Virgo", "country" => "Ireland" ), "member3" => array ( "name" => "William", "zodiac" => "Pisces", "country" => "Great Britain" ), "member4" => array ( "name" => "Eduardo", "zodiac" => "Leo", "country" => "Mexico" ) ); $datasetCount = count($members); // returns count of array items of any array echo "Member Count: $datasetCount<br /> "; ?>

Afiseaza 4
<?php $cart_array = array("Milk", "Cheese", "Eggs", "Cereal", "Jelly"); // has key increment index of 0 // To force key incrementing to start at 1 use this line instead to build you r array //$cart_array = array(1 => "Milk", "Cheese", "Eggs", "Cereal", "Jelly"); // F orce key incrementing to start at 1 $i = 0; // create a varible that will tell us how many items we looped over foreach ($cart_array as $key => $value) { $i++; // increment $i by one each loop pass echo "Cart Item $i ______ Key = $key | Value = $value<br />;} ?>

<?php // create a multidimensional array that holds member details from our site $members = array ( "member1" => array ( "name" => "John", "zodiac" => "Scorpio", "country" => "USA" ), "member2" => array ( "name" => "Susan", "zodiac" => "Virgo", "country" => "Ireland" ), "member3" => array ( "name" => "William", "zodiac" => "Pisces", "country" => "Great Britain" ), "member4" => array ( "name" => "Eduardo", "zodiac" => "Leo", "country" => "Mexico" ) ); $datasetCount = count($members); // returns count of array items of any array echo "<h1>There are $datasetCount members</h1>"; $i = 0; foreach ($members as $each_member) { $i++; echo "<h2>Member $i</h2>"; while (list($key, $value) = each ($each_member)) { echo "$key: $value<br />"; } } ?> <?php // All of the lollowing syntax will work the same include ("my_file.php"); include "my_file.php"; include 'my_file.php'; ?>

<?php // These first 5 examples use relative referenced paths(relative to where scr

ipt is) $my_file = "somefile.php"; // Connect to file in same folder $my_file = "myFolder/somefile.php"; //File in a folder within the current fol der // Connect to file in a folder within a folder $my_file = "myFolder/anotherFolder/somefile.php"; $my_file = "../somefile.php"; // Connect to file in parent directory(jump up one level) $my_file = "../../somefile.php"; // File 2 parent folders up(jump up two levels) // This example is referencing the file by full URL $my_file = "http://www.anyDomainName.com/somefile.php"; ?> <?php include ("file1.php"); include_once ("file2.php"); require ("file3.php"); require_once ("file4.php"); // All 4 files would be included into your main script // file1.php and file3.php can be included multiple times // file2.php and file4.php cannot be included multiple times ?> <?php // include a script into another script from another server include "http://www.yourwebsite.com/yourScript.php"; ?>
<?php // include a script into a caller script from another server, and send variables include "http://www.yourwebsite.com/yourScript.php?name=John&pin=8558"; ?>

Creare de document <?php // you can create any extension type file(html, php, xml, etc...) $file_x = "my_file.txt";
$createFile = touch($file_x); if (file_exists($file_x)) { echo "The file has been created"; } else { echo "The file has not been created"; } ?>

Stergere de document <?php // you can delete any extension type file(html, php, jpg, gif, flv, swf, etc...)

$file_x = "my_file.txt"; if (file_exists($file_x)) { unlink($file_x); // delete it here only if it exists echo "The file has been deleted"; } else { echo "The file was not found and could not be deleted"; } ?>

Deschiderea unui fisier pentru scriere/editare


Mode w w+ a a+ r r+ x x+ Mode Functionality Write to a file. If the file does not exist, attempt to create it. Reading and writing to a file. If the file does not exist, attempt to create it. Write to a file. If the file does not exist, attempt to create it. Reading and writing. If the file does not exist, attempt to create it. Reading file only. Reading and writing to a file. Create and open for writing only. If the file already exists, fopen() will fail by returning FALSE and generating an error. If the file does not exist, attempt to create it. Create and open for reading and writing. If the file already exists, fopen() will fail by returning

FALSE and generating an error. If the file does not exist, attempt to create it. Exemplu $fh = fopen('/var/www/docs/summary.html', 'w'); <?php // Here we define the file path and name $target_file = "my_file.txt"; // Here we define the string data that is to be placed into the file $target_file_data = "This is the string data or code I want to place in the n ewly created file."; // Here we are creating a file(since it does not yet exist) and adding data t o it $handle = fopen($target_file, "w"); fwrite($handle, $target_file_data); // write it fclose($handle); // Here we are opening and appending to the file $handle = fopen($target_file, "a"); // Here we define the string data that is to be appended to the data already in file $target_file_data = "Here is more data I want to append to the file."; fwrite($handle, $target_file_data); // write it

fclose($handle); // Here we display the file contents by including it include($target_file); ?>

DIRECTOARE(FOLDERS) <?php
// Define path and new folder name $newfolder = "myNewFolder"; mkdir($newfolder, 0777); // Make new folder and set file permissions on it ( chmod ) // check to see if it has been created or not using is_dir if (is_dir($newfolder)) { echo "The $newfolder directory has been created<br /><br />"; // it is good th check and see if it is_dir before we remove it rmdir($newfolder); } // check to see if the directory exists if (!file_exists($newfolder)) { echo "The $newfolder directory has been removed<br /><br />"; } else { echo "ERROR: Trouble removing $newfolder directory"; } ?>
<?php // SPECIFY THE DIRECTORY $dir = \"images/\"; // OPEN THE DIRECTORY $dirHandle = opendir($dir); // LOOP OVER ALL OF THE FILES while ($file = readdir($dirHandle)) { // IF IT IS NOT A FOLDER, AND ONLY IF IT IS A .JPG WE ACCESS IT if(!is_dir($file) && strpos($file, '.jpg')>0) { echo \"$dir\".\"$file\".\"<br />\"; } } // CLOSE THE DIRECTORY closedir($dirHandle); ?>

<?php // Specify the target directory and add forward slash $dir = "myFolder/"; // Open the directory

$dirHandle = opendir($dir); // Loop over all of the files in the folder while ($file = readdir($dirHandle)) { // If $file is NOT a directory remove it if(!is_dir($file)) { unlink ("$dir"."$file"); // unlink() deletes the files } } // Close the directory closedir($dirHandle); ?>

Stergerea fiserelor .txt folosind glob


<?php // Specify the target directory and add forward slash $path = "myFolder/"; // Loop over all of the .txt files in the folder foreach(glob($path ."*.txt*") as $file) { unlink($file); // Delete only .txt files through the loop } ?>

FILE EXISTS
<?php $file_x = "my_file.php"; if (file_exists($file_x)) { echo $file_x . " exists"; } else { echo $file_x . " does not exist"; } ?>

copy() function : How to make a copy of a file using PHP script <?php // Try any file type with any extensions(.jpg, .html, .doc, .pdf, etc...) $targetFile = "test.html"; $targetCopy = "test_copy.html"; // Use the built in copy function now copy($targetFile, $targetCopy); // Now you can choose to run a check to see if the new copy exists, // or you have the option to do nothing and assume it is made if (file_exists($targetCopy)) { echo "Success : $targetCopy has been made"; } else { echo "Failure: $targetCopy does not exist"; } ?>

VERIFICARE EMAIL
<?php $email = \"abc123@lolhaha\"; // Invalid email address //$email = \"somebody@somesite.com\"; // Valid email address // Set up regular expression strings to evaluate the value of email variable against $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'; // Run the preg_match() function on regex against the email address if (preg_match($regex, $email)) { echo $email . \" is a valid email. We can accept it.\"; } else { echo $email . \" is an invalid email. Please try again.\"; } ?>

Heredoc | Nowdoc
Se foloseste pentru a scrie bucati mari de cod
<?php $website = "http://www.romatermini.it"; echo <<<EXCERPT <p>Rome's central train station, known as <a href = "$website">Roma Termini</a>, was built in 1867. Because it had fallen into severe disrepair in the late 20th century, the government knew that considerable resources were required to rehabilitate the station prior to the 50-year <i>Giubileo</i>.</p> EXCERPT; ?>

Several points are worth noting regarding this example: The opening and closing identifiers (in the case of this example, EXCERPT) must be identical. You can choose any identifier you please, but they must exactly match. The only constraint is that the identifier must consist of solely alphanumeric characters and underscores and must not begin with a digit or an underscore. The opening identifier must be preceded with three left-angle brackets (<<<). Heredoc syntax follows the same parsing rules as strings enclosed in double quotes. That is, both variables and escape sequences are parsed. The only difference is that double quotes do not need to be escaped. The closing identifier must begin at the very beginning of a line. It cannot be preceded with spaces or any other extraneous character. This is a commonly recurring point of confusion among users, so take special care to make sure your

heredoc string conforms to this annoying requirement. Furthermore, the presence of any spaces following the opening or closing identifier will produce a syntax error. Daca vrei ca textul sa nu fie interpretat ci afisat ca un string folosesti Nowdoc Functii Pentru parametrii functiilor nu e nevoie sa specifici tipul. Daca insa vrei sa apartina unei anumite clase sau sa fie vector. Nu merge pentru alte date, gen integer sau string (da fatal error). Ca sa intorci variabile multiple dintr-o functie, le pui intr-un vector, iar la atribuire, variablilele le pui in list().Exemplu: function retrieveUserProfile() { $user[] = "Jason Gilmore"; $user[] = "jason@example.com"; $user[] = "English"; return $user; } list($name, $email, $language) = retrieveUserProfile(); echo "Name: $name, email: $email, language: $language";

Vectori
$states = array("OH" => "Ohio", "PA" => "Pennsylvania", "NY" => "New York")

La vectori de vectori(matrici) trebuie sa pui ; la final


$states = array ( "Ohio" => array("population" => "11,353,140", "capital" => "Columbus"), "Nebraska" => array("population" => "1,711,263", "capital" => "Omaha") );

Pentru a popula un vector cu valori dintr-o raza folosim functia range: zar = range (1,6); mr_pare = range(2,30,2); litere = range(A,F);

Parcurgere vector:

$customers = array(); $customers[] = array("Jason Gilmore", "jason@example.com", "614-999-9999"); $customers[] = array("Jesse James", "jesse@example.net", "818-999-9999"); $customers[] = array("Donald Duck", "donald@example.org", "212-999-9999"); foreach ($customers AS $customer) { vprintf("<p>Name: %s<br />E-mail: %s<br />Phone: %s</p>", $customer); }

Adaugare in la inceputul unui vector


$states = array("Ohio", "New York"); array_unshift($states, "California", "Texas"); // $states = array("California", "Texas", "Ohio", "New York");

Adaugare la sfarsitul vectorului


$states = array("Ohio", "New York"); array_push($states, "California", "Texas"); // $states = array("Ohio", "New York", "California", "Texas");

Eliminarea primului element


$states = array("Ohio", "New York", "California", "Texas"); $state = array_shift($states); // $states = array("New York", "California", "Texas") // $state = "Ohio"

Eliminarea ultimului element


$states = array("Ohio", "New York", "California", "Texas"); $state = array_pop($states); // $states = array("Ohio", "New York", "California" // $state = "Texas"

Functia in_array(cel_cautat,unde_cautam) returneaza true daca il gaseste si nu daca nu il gaseste. Poate avea un al 3lea parametru pentru a verifica si tipul variabilei boolean array_key_exists(mixed key, array array) - returneaza true daca vectorul are una dintre chei key; daca adaugi al 3 parametru strict, functia returneaza valoarea gasita la cheia key. Afiseaza cheile
$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines"); echo "<p>Can you name the capitals of these states?</p>";

while($key = key($capitals)) { printf("%s <br />", $key); next($capitals);}

Afiseaza valorile

$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines"); echo "<p>Can you name the states belonging to these capitals?</p>"; while($capital = current($capitals)) { printf("%s <br />", $capital); next($capitals); } strip_tags() sterge toate tagurile php si html din value <?php function sanitize_data(&amp;$value, $key) { $value = strip_tags($value); } array_walk($_POST['keyword'],"sanitize_data"); /* array_walk parcurge vectorul*/ ?>

Pentru vectori de vectori putem folosi functia array_walk_recursive() Masurarea unui vector:
$garden = array("cabbage", "peppers", "turnips", "carrots"); echo count($garden);
afiseaza 4

Daca vrem recursiv:


$locations = array("Italy", "Amsterdam", array("Boston","Des Moines"), "Miami"); echo count($locations, 1); afiseaza 6 deoarece si vectorul este considerat un element

sizeof() este echivalent cu count


De cate ori apare

Eliminarea duplicatelor cu array_unique(vector) :


$states = array("Ohio", "Iowa", "Arizona", "Iowa", "Ohio"); $uniqueStates = array_unique($states); print_r($uniqueStates); Array ( [0] => Ohio [1] => Iowa [2] => Arizona )

Afisare in ordine inversa array_reverse(vector)


$states = array("Delaware", "Pennsylvania", "New Jersey"); print_r(array_reverse($states)); // Array ( [0] => New Jersey [1] => Pennsylvania [2] => Delaware ) $states = array("Delaware", "Pennsylvania", "New Jersey"); print_r(array_reverse($states,1)); // Array ( [2] => New Jersey [1] => Pennsylvania [0] => Delaware )

Sortand cu sort se atribuie noi elementele schimba cheile. Sortand cu asort elementele pastreaza si cheile void natsort(array vector) picture1.jpg, picture10.jpg, picture2.jpg, picture20.jpg cu sort picture1.jpg, picture2.jpg, picture10.jpg, picture20.jpg cu natsort Picture1.jpg, PICTURE10.jpg, picture2.jpg, picture20.jpg natcasesort() array array_combine(array keys, array values) atribuie fiecare valori unei o chiei

Obiecte

class Employee { private $name; private $title; protected $wage; protected function clockIn() { echo "Member $this->name clocked in at ".date("h:i:s"); } protected function clockOut() { echo "Member $this->name clocked out at ".date("h:i:s"); } }

Apelarea proprietatilor
$employee->name $employee->title $employee->wage

Functie

function setName($name) { $this->name = $name; }

Constante

class mathFunctions { const PI = '3.14159265'; const E = '2.7182818284'; const EULER = '0.5772156649'; } echo mathFunctions::PI;

Metode

<?php class Visitors { public function greetVisitor() { echo "Hello<br />"; } function sayGoodbye() {

echo "Goodbye<br />"; }} Visitors::greetVisitor(); $visitor = new Visitors();

$visitor->sayGoodbye(); ?> Metode abstract <?php abstract class AbstractClass { // Foreaz implementarea n copii a urmtoarelor metode abstract protected function getValue(); abstract protected function prefixValue($prefix);
// Metod comun public function printOut() { print $this->getValue() . "\n"; }

class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; }} ?>

Metodele finale previn orice incercare de a fi rescrise in subclase Constructori: - pot accepta parametrii, care sunt dati proprietatilor obiectelor - pot apela metode si alte functii - constructorii pot apela alti constructori, inclusiv cei din clasa parinte
<?php class Employee { protected $name; protected $title; function __construct() { echo "<p>Employee constructor called!</p>"; }} class Manager extends Employee { function __construct() { parent::__construct(); echo "<p>Manager constructor called!</p>";

}}

$employee = new Manager(); This results in the following: Employee constructor called! Manager constructor called!

?>

Poti sa invoci constructori chiar daca nu au nicio legatura cu clasa. Spre exemplu, in constructorul tata poti invoca constructorul fiu.
array get_class_methods(mixed class_name)

Functia __clone() Orice cod definit in aceasta functie va fi executat cand este apelat procesul de clonare.
function __clone() { $this->tiecolor = "blue"; }

Noua clona va avea culoarea cravatei albastra

Definirea unui constructor in clasa fiu suprascrie constructorul din clasa tata O clasa poate implementa mai multe interfete O clasa abstracta este o clasa al carei scop nu este sa fie instantiata ci sa fie mostenita de alta clase Toate metodele dintr-o clasa abstracta trebuiesc implementate la mostenire Daca obiectul trebuie sa mosteneasca mai multe clase, folosim interfate. Obiectele in PHP pot mosteni mai multe interfete, dar nu pot extinde mai multe clase
<?php interface IEmployee {...} interface IDeveloper {...} interface IPillage {...} class Employee implements IEmployee, IDeveloper, iPillage { ... } class Contractor implements IEmployee, IDeveloper { ... } ?>

Folosirea librariilor
<?php require "Library.inc.php"; require "Data.inc.php"; use Com\Wjgilmore\Library as WJG; use Com\Thirdparty\DataCleaner as TP; // Instantiate the Library's Clean class $filter = new WJG\Clean(); // Instantiate the DataFilter's Clean class $profanity = new TP\Clean(); // Create a book title $title = "the idiotic sun also rises"; // Output the title before filtering occurs printf("Title before filters: %s <br />", $title); // Remove profanity from the title $title = $profanity->removeProfanity($title);

printf("Title after WJG\Clean: %s <br />", $title); // Remove white space and capitalize title $title = $filter->filterTitle($title); printf("Title after TP\Clean: %s <br />", $title); ?>

Exception handling
try { perform some task if something goes wrong throw IOexception("Could not open file.") if something else goes wrong throw Numberexception("Division by zero not allowed.") // Catch IOexception } catch(IOexception) { output the IOexception message } // Catch Numberexception } catch(Numberexception) { output the Numberexception message }

Directoare
Calea
Directory name: /home/www/htdocs/book/chapter10 Base name: index.html File extension: html File name: index You can use pathinfo() like this to retrieve this information: <?php $pathinfo = pathinfo('/home/www/htdocs/book/chapter10/index.html'); printf("Dir name: %s <br />", $pathinfo['dirname']); printf("Base name: %s <br />", $pathinfo['basename']); printf("Extension: %s <br />", $pathinfo['extension']); printf("Filename: %s <br />", $pathinfo['filename']); ?> This produces the following output: Dir name: /home/www/htdocs/book/chapter10 Base name: index.html Extension: html Filename: index

Marimea
<?php $file = '/www/htdocs/book/chapter1.pdf'; $bytes = filesize($file); $kilobytes = round($bytes/1024, 2); printf("File %s is $bytes bytes, or %.2f kilobytes", basename($file), $kilobytes); ?>

Functii
filesize(string filename); returneaza marimea unui fisier. $userfile= file_get_contents('users.txt'); returneaza ca string tot continutul fisierului in variabila string fgets(resource handle [, int length]) ; citeste o linie din fisier, al 2-lea parametru este pentru a specifica cate carac sa citeasca

Lucrul cu resurse
<?php // Open a text file for reading purposes $fh = fopen('/home/www/data/users.txt', 'r'); // While the end-of-file hasn't been reached, retrieve the next line while (!feof($fh)) echo fgets($fh); // Close the file fclose($fh); ?>

Das könnte Ihnen auch gefallen