Friday, December 26, 2008

I was designed and programmed with a php website to download tutorials. Although yet to add new development and programming tutorials, you can find and download a php tutorial if you need it.
The tutorials in pdf format, are completely free.
This is my small contribution to the programmers who need to document some programming languages. I hope you like it.

Tuesday, July 15, 2008

42 tips for optimizing your php code

• If a method can be static, declare it static. Speed improvement is by a factor of 4.
• echo is faster than print.
• Use echo's multiple parameters instead of string concatenation.
• Set the maxvalue for your for-loops before and not in the loop.
• Unset your variables to free memory, especially large arrays.
• Avoid magic like __get, __set, __autoload
• require_once() is expensive
• Use full paths in includes and requires, less time spent on resolving the OS paths.
• If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
• See if you can use strncasecmp, strpbrk and stripos instead of regex
• str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
• If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
• It's better to use switch statements than multi if, else if, statements.
• Error suppression with @ is very slow.
• Turn on apache's mod_deflate
• Close your database connections when you're done with them
• $row[’id’] is 7 times faster than $row[id]
• Error messages are expensive
• Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
• Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
• Incrementing a global variable is 2 times slow than a local var.
• Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
• Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
• Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
• Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
• Methods in derived classes run faster than ones defined in the base class.
• A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
• Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
• When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
• A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
• Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
• Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request
• When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.


Ex.

if (strlen($foo) < 5) { echo "Foo is too short"; }

vs.

if (!isset($foo{5})) { echo "Foo is too short"; }


Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
• When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.
• Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.
• Do not implement every data structure as a class, arrays are useful, too
• Don't split methods too much, think, which code you will really re-use
• You can always split the code of a method later, when needed
• Make use of the countless predefined functions
• If you have very time consuming functions in your code, consider writing them as C extensions
• Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
• mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

Wednesday, July 2, 2008

Php Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. These special constants are case-insensitive and are as follows:

A few "magical" PHP constants

Name

Description

__LINE__

The current line number of the file.

__FILE__

The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.

__FUNCTION__

The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

__CLASS__

The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

__METHOD__

The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

Php Error Control Operators

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.
If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php

/* Intentional file error */

$my_file = @file ('non_existent_file') or

die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:

$value = @$cache[$key];

// will not issue a notice if the index $key doesn't exist.

?>


Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include() calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Warning

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

Thursday, May 8, 2008

Reasons to Love PHP and MySQL

There are ever so many reasons to love PHP and MySQL. Let us count a few.

Cost

PHP costs you nothing. Zip, zilch, nada, not one red cent. Nothing up front, nothing over the lifetime of the application, nothing when it’s over. Did we mention that the Apache/PHP/MySQL combo runs great on cheap, low-end hardware that you couldn’t even think about for IIS/ASP/SQL Server?

MySQL is a slightly different animal in its licensing terms. Before you groan at the concept of actually using commercial software, consider that although MySQL is open-source licensed for many uses, it is not and has never been primarily community-developed software. MySQL AB is a commercial entity with necessarily commercial interests. Unlike typical open source projects, where developers often have regular full-time (and paying) day jobs in addition to their freely given open source efforts, the MySQL developers derive their primary income from the project. There are still many circumstances in which MySQL can be used for free (basically anything nonredistributive, which covers most PHP-based projects), but if you make money developing solutions that use MySQL, consider buying a license or a support

contract. It’s still infinitely more reasonable than just about any software license you will ever pay for.

For purposes of comparison, Table 1-1 shows some current retail figures for similar products in the United States. All prices quoted are for a single-processor public Web server with the most common matching database and development tool; $0 means a no-cost alternative is a common real-world choice.

Comparative Out-of-Pocket Costs

ASP/SQL ColdFusion

Item Server MX/SQL Server JSP/Oracle PHP/MySQL

Development tool $0–2499 $599 $0–~2000 $0–249

Server $999 $2298 $0–~35,000 $0

RDBMS $4999 $4999 $15,000 $0–220

Open source software: don’t fear the cheaper

But as the bard so pithily observed, we are living in a material world —where we’ve internalized maxims such as, “You get what you pay for,” “There’s no such thing as a free lunch,” and “Things that sound too good to be true usually are.” You (or your boss) may, therefore, have some lingering doubts about the quality and viability of no-cost software. It probably doesn’t help that until recently software that didn’t cost money — formerly called freeware , shareware, or free software — was generally thought to fall into one of three categories:

Programs filling small, uncommercial niches

Programs performing grungy, low-level jobs

Programs for people with bizarre socio-political issues

It’s time to update some stereotypes once and for all. We are clearly in the middle of a sea change in the business of software. Much (if not most) major consumer software is distributed without cost today; e-mail clients, Web browsers, games, and even full-service office suites are all being given away as fast as their makers can whip up Web versions or set up

FTP servers. Consumer software is increasingly seen as a loss-leader, the flower that attracts the pollinating honeybee — in other words, a way to sell more server hardware, operating systems, connectivity, advertising, optional widgets, or stock shares. The full retail price of a piece of software, therefore, is no longer a reliable gauge of its quality or the eccentricity-level of its user.

On the server side, open source products have come on even stronger. Not only do they

compete with the best commercial stuff; in many cases there’s a feeling that they far exceed the competition. Don’t take our word for it! Ask IBM, any hardware manufacturer, NASA, Amazon.com, Rockpointe Broadcasting, Ernie Ball Corporation, the Queen of England, or the Mexican school system. If your boss still needs to be convinced, further ammunition is available at www.opensource.org and www.fsf.org.

The History of MySQL

Depending on how much detail you want, the history of MySQL can be traced as far back as 1979, when MySQL’s creator, Monty Widenius, worked for a Swedish IT and data consulting firm, TcX. While at TcX, Monty authored UNIREG, a terminal interface builder that connected to raw ISAM data stores. In the intervening 15 years, UNIREG served its makers rather well through a series of translations and extensions to accommodate increasingly large data sets.

In 1994, when TcX began working on Web data applications, chinks in the UNIREG armor, primarily having to do with application overhead, began to appear. This sent Monty and his colleagues off to look for other tools. One they inspected rather closely was Hughes mSQL, a light and zippy database application developed by David Hughes. mSQL possessed the distinct advantages of being inexpensive and somewhat entrenched in the market, as well as featuring a fairly well-developed client API. The 1.0 series of mSQL release lacked indexing, however, a feature crucial to performance with large data stores. Although the 2.0 series of mSQL would see the addition of this feature, the particular implementation used was not compatible with UNIREG’s B+-based features. At this point, MySQL, at least conceptually, was born.

Monty and TcX decided to start with the substantial work already done on UNIREG while developing a new API that was substantially similar to that used by mSQL, with the exception of the more effective UNIREG indexing scheme. By early 1995, TcX had a 1.0 version of this new product ready. They gave it the moniker MySQL and later that year released it under a combination open source and commercial licensing scheme that allowed continued development of the product while providing a revenue stream for MySQL AB, the company that evolved from TcX.

Over the past ten years, MySQL has truly developed into a world class product. MySQL now competes with even the most feature-rich commercial database applications such as Oracle and Informix. Additions in the 4.x series have included much-requested features such as transactions and foreign key support. All this has made MySQL the world’s most used open source database.


The History of PHP

Rasmus Lerdorf— software engineer, Apache team member, and international man of mystery — is the creator and original driving force behind PHP. The first part of PHP was devel-oped for his personal use in late 1994. This was a CGI wrapper that helped him keep track of people who looked at his personal site. The next year, he put together a package called the Personal Home Page Tools (a.k.a. The PHP Construction Kit) in response to demand from users who had stumbled into his work by chance or word of mouth. Version 2 was soon released under the title PHP/FI and included the Form Interpreter, a tool for parsing SQL queries.

By the middle of 1997, PHP was being used on approximately 50,000 sites worldwide. It was clearly becoming too big for any single person to handle, even someone as focused and energetic as Rasmus. A small core development team now runs the project on the open source “benevolent junta” model, with contributions from developers and users around the world.

Zeev Suraski and Andi Gutmans, the two Israeli programmers who developed the PHP3 and

PHP4 parsers, have also generalized and extended their work under the rubric of Zend.com

The fourth quarter of 1998 initiated a period of explosive growth for PHP, as all open source technologies enjoyed massive publicity. In October 1998, according to the best guess, just over 100,000 unique domains used PHP in some way. Just over a year later, PHP broke the one-million domain mark. When we wrote the first edition of this book in the first half of 2000, the number had increased to about two million domains. As we write this, approximately 15 million public Web servers (in the software sense, not the hardware sense) have PHP installed on them.

Public PHP deployments run the gamut from mass-market sites such as Excite Webmail and the Indianapolis 500 Web site, which serve up millions of pageviews per day, through “massniche” sites such as Sourceforge.net and Epinions.com, which tend to have higher functionality needs and hundreds of thousands of users, to e-commerce and brochureware sites such as The Bookstore at Harvard.com and Sade.com (Web home of the British singer), which must be visually attractive and easy to update. There are also PHP-enabled parts of sites, such as the forums on the Internet Movie Database (imdb.com); and a large installed base of nonpublic PHP deployments, such as LDAP directories (MCI WorldCom built one with over 100,000 entries) and trouble-ticket tracking systems.

In its newest incarnation, PHP5 strives to deliver something many users have been clamoring for over the past few years: much improved object-oriented programming (OOP) functionality. PHP has long nodded to the object programming model with functions that allow object programmers to pull out results and information in a way familiar to them. These efforts still fell short of the ideal for many programmers, however, and efforts to force PHP to build in fully object-oriented systems often yielded unintended results and hurt performance. PHP5’s newly rebuilt object model brings PHP more in line with other object-oriented languages such as Java and C++, offering support for features such as overloading, interfaces, private member variables and methods, and other standard OOP constructions.

With the crash of the dot-com bubble, PHP is poised to be used on more sites than ever.

Demand for Web-delivered functionality has decreased very little, and emerging technological standards continue to pop up all the time, but available funding for hardware, licenses, and especially headcount has drastically decreased. In the post-crash Web world, PHP’s shallow learning curve, quick implementation of new functionality, and low cost of deployment are hard arguments to beat.


What is PHP and MySQL

What Is PHP?

PHP is the Web development language written by and for Web developers. PHP stands for PHP: Hypertext Preprocessor. The product was originally named Personal Home Page Tools, and many people still think that’s what the acronym stands for. But as it expanded in scope, a new and more appropriate (albeit GNU-ishly recursive) name was selected by community vote. PHP is currently in its fifth major rewrite, called PHP5 or just plain PHP.

PHP is a server-side scripting language, which can be embedded in HTML or used as a standalone binary (although the former use is much more common). Proprietary products in this niche are Microsoft’s Active Server Pages, Macromedia’s ColdFusion, and Sun’s Java Server Pages. Some tech journalists used to call PHP “the open source ASP” because its functionality is similar to that of the Microsoft product — although this formulation was misleading, as PHP was developed before ASP. Over the past few years, however, PHP and server-side Java have gained momentum, while ASP has lost mindshare, so this comparison no longer seems appropriate. You can think of it as a collection of super-HTML tags or small programs that run inside your Web pages — except on the server side, before they get sent to the browser. For example, you can use PHP to add common headers and footers to all the pages on a site or to store form-submitted data in a database.

Strictly speaking, PHP has little to do with layout, events, on the fly DOM manipulation, or really anything about what a Web page looks and sounds like. In fact, most of what PHP does is invisible to the end user. Someone looking at a PHP page will not necessarily be able to tell that it was not written purely in HTML, because usually the result of PHP is HTML.

PHP is an official module of Apache HTTP Server, the market-leading free Web server that runs about 67 percent of the World Wide Web (according to the widely quoted Netcraft Web server survey). This means that the PHP scripting engine can be built into the Web Server itself, leading to faster processing, more efficient memory allocation, and greatly simplified maintenance. Like Apache Server, PHP is fully cross-platform, meaning it runs native on sev-eral flavors of Unix, as well as on Windows and now on Mac OS X. All projects under the aegis of the Apache Software Foundation — ncluding PHP — are open source software.

What Is MySQL?

MySQL (pronounced My Ess Q El) is an open source, SQL Relational Database Management System (RDBMS) that is free for many uses (more detail on that later). Early in its history, MySQL occasionally faced opposition due to its lack of support for some core SQL constructs such as subselects and foreign keys. Ultimately, however, MySQL found a broad, enthusiastic user base for its liberal licensing terms, perky performance, and ease of use. Its acceptance was aided in part by the wide variety of other technologies such as PHP, Java, Perl, Python, and the like that have encouraged its use through stable, well-documented modules and extensions. MySQL has not failed to reward the loyalty of these users with the addition of both subselects and foreign keys as of the 4.1 series.

Databases in general are useful, arguably the most consistently useful family of software products —the “killer product” of modern computing. Like many competing products, both free and commercial, MySQL isn’t a database until you give it some structure and form. You might think of this as the difference between a database and an RDBMS (that is, RDBMS plus user requirements equals a database).

There’s lots more to say about MySQL, but then again, there’s lots more space in which to say it.


Friday, April 25, 2008

What Is PHP?

PHP is an open-source, server-side, HTML-embedded Web-scripting language that is compatible with all the major Web servers (most notably Apache). PHP enables you to embed code fragments in normal HTML pages — code that is interpreted as your pages are served up to users. PHP also serves as a “glue” language, making it easy to connect your Web pages to server-side databases.

Monday, April 7, 2008

Php Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators

Example

Name

Result

$a == $b

Equal

TRUE if $a is equal to $b.

$a === $b

Identical

TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)

$a != $b

Not equal

TRUE if $a is not equal to $b.

$a <> $b

Not equal

TRUE if $a is not equal to $b.

$a !== $b

Not identical

TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)

$a < $b

Less than

TRUE if $a is strictly less than $b.

$a > $b

Greater than

TRUE if $a is strictly greater than $b.

$a <= $b

Less than or equal to

TRUE if $a is less than or equal to $b.

$a >= $b

Greater than or equal to

TRUE if $a is greater than or equal to $b.

If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("1" == "1e0"); // 1 == 1 -> true

switch ("a") {
case 0:
echo "0";
break;
case "a": // never reached because "a" is already matched with 0
echo "a";
break;
}
?>

For various types, comparison is done according to the following table (in order).

Comparison with Various Types

Type of Operand 1

Type of Operand 2

Result

null or string

String

Convert NULL to "", numerical or lexical comparison

bool or null

anything

Convert to bool, FALSE < TRUE

object

object

Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation

string, resource or number

string, resource or number

Translate strings and resources to numbers, usual math

array

array

Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)

array

anything

array is always greater

object

anything

object is always greater

Example Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return null; // uncomparable
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}

?>


The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : 'false') ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Sunday, February 17, 2008

Como manejar archivos con Php

Apertura de un archivo con PHP

La función utilizada para abrir un archivo en PHP es fopen, la sintaxis.

fp_handler=fopen(“path”,”modo”);

Path es la ruta completa del archivo a abrir, si el path comienza con “http://” se realiza una conexión a la URL indicada y se abre la página como si fuera un archivo (con las limitaciones lógicas, por ejemplo no es posible escribir).
Los modos en los que se puede abrir un archivo son:

r Sólo lectura
r+ Lectura y escritura
w Sólo escritura, si no existe el archivo lo crea, si existe lo trunca
w+ Lectura y escritura, si existe lo trunca, si no existe lo crea
a Modo append sólo escritura si no existe lo crea
a+ Modo append lectura y escritura si no existe lo crea

La función devuelve un file_handler que luego debe ser usado en todas las funciones de tipo fnombre_funcion, como por ejemplo fgets, fputs, fclose, fread, fwrite, etc.

Lectura desde un archivo con Php

Las funciones que pueden usarse para leer un archivo son:

string=fgets(file_handler, longitud) : Lee una línea de texto hasta el fin de línea o bien hasta que se cumpla la longitud indicada, devuelve el resultado en la variable pasada. El archivo debe estar abierto con fopen.

var=fread(file_handler, cantidad): Lee la cantidad de bytes indicados ignorando saltos de línea y deja el resultado en la variable var.

Ejemplo

$buffer=fread($fp, 1024); //Lee 1Kb desde el archivo cuyo handler es $fp

string=fgetss(file_handler, longitud) Idéntica a fgets con la diferencia de que los tags html son eliminados del archivo a medida que se lee el mismo. Opcionalmente puede pasarse una lista de tags que no deben ser eliminados.

Ejemplo:

$string=fgetss($fp,999999,”<b> <i> <table> <tr> <td>”);

Lee una línea (de cualquier longitud) eliminando los tags html excepto los indicados como segundo parámetro. Los tags que cierran los tags especificados en la lista de tags permitidos tampoco son eliminados.

Escritura a un archivo con Php

fwrite(file_handler, variable, longitud);

Escribe la variable al archivo indicado por file_handler. Si esta indicado el parámetro “longitud” (que es opcional) se escribirán tantos bytes como la longitud indicada por dicho parámetro o como la longitud de la variable, en aquellos casos en que el parámetro longitud es mayor que la longitud de la variable.
La función devuelve la cantidad de bytes escritos en el archivo.

Ejemplo:

$q = fwrite($fp,$buffer,999999);

fputs es idéntico a fwrite y funciona de la misma manera. (es un alias).

Cierre de archivos con Php

fclose(file_handler)

Cierra un archivo abierto con fopen.

Fin de archivo con Php

boolean = feof(file_handler);

Devuelve verdadero si no quedan más bytes para leer en el archivo o si se produce algún tipo de error al leer.

Ejemplo:
$fp=fopen(“/usr/luis/archivo.txt”,”r”);
while(!feof($fp)) {
$s=fgets($fp,999999);
print(“$s”);
}



Manejo de archivos con Php

PHP provee funciones para copiar, renombrar, mover y borrar archivos y directorios, las funciones son:

rename(path_origen, path_destino); Renombra un archivo.

Ejemplo:
$newname=”/usr/eduardo/file.txt”;
Rename(“/usr/eduardo/archivo.txt”,”$newname”);

unlink(path_a_borrar); Elimina un archivo.

rmdir(directorio_a_borrar); Elimina un directorio (debe estar vacío)

mkdir(path_a_crear); Crea un directorio Nuevo.

copy(path_origen, path_destino); Copia un archivo o varios.

Otras funciones útiles con Php

fseek(file_handler,posicion,desde) Posiciona el puntero de lectura/escritura de un archivo en el offset indicado. El parámetro “desde” es opcional y puede tomar uno de los siguientes valores:

SEEK_SET (el offset es absoluto)
SEEK_CUR (el offset es relativo a la posición actual)
SEEK_END (el offset es desde el final del archivo)

El default es SEEK_SET

ftruncate(file_handler, longitud) Trunca el archivo indicado a la longitud en bytes especificada.

array=file(path) Lee un archivo de texto y devuelve un vector donde cada elemento del vector es una línea del archivo.

file_exists(path) Devuelve true/false según el path indicado exista o
no.

filemtime(path) Devuelve la fecha de última modificación de un archivo en formato Unix. (ver manejo de fechas)

filesize(path) Devuelve el tamaño de un archivo.

filetype(path) Devuelve el tipo de un archivo.

flock(file_handler,modo) Lockea un archivo (independientemente del filesystem),
el modo puede ser:

1: Lock en modo lectura (compartido)
2: Lock en modo escritura (exclusivo)
3: Release del lock adquirido.

Al hacer un fclose del archivo se liberan automáticamente los locks adquiridos sobre el mismo.
Si flock no puede obtener el lock espera hasta que el lock este disponible, si se quiere que flock no bloquee el script sumar 4 al modo (modos: 5,6,7) y consultar por el valor devuelto por la función: true si el lock fue adquirido o false si no fue adquirido. Usando esta función pueden implementarse mecanismos de sincronización entre procesos.

fpassthru(file_handler) Escribe al standard_output el contenido del archivo.

readfile(path) Lee todo el archivo y lo escribe al standard output.

is_dir(path) True/false según el path sea un directorio

is_file(path) True/false según el path sea un archivo

tempnam(path) Dado el nombre de un directorio devuelve un nombre de archivo que no existe en el directorio dado (útil para crear archivos temporarios)

Manejo de directorios con Php

Las siguientes funciones de PHP están orientadas a recorrer directorios y obtener los archivos que se encuentran dentro de ellos. Las funciones son independientes del file-system con lo cual funcionan correctamente tanto en UNIX como en Windows.

directory_handle = opendir(path);
Abre el directorio pasado como parámetro y devuelve un handler al directorio, previamente puede usarse la función is_dir(path) para verificar si el path es un directorio en caso de que esta validación sea necesaria.

string = readdir(directory_handler)
Lee la próxima entrada en el directorio abierto con opendir, usualmente las dos primeras entradas de un directorio con “.” y “..” por lo que el código que procesa los archivos del directorio debe tener esto en cuenta para no procesar dichas entradas en caso de que tal cosa no sea deseable.

closedir(directory_handler)
Cierra un handler abierto con opendir.

rewinddir(directory_handler)
Rebobina el puntero interno de un directorio para que apunte nuevamente al comienzo del mismo.

Estructuras de control en php: la estructura "if"

El caso de la instruccion "IF" es una de las características más importantes de muchos idiomas, incluido PHP. Permite la ejecución condicional de fragmentos de código. PHP cuenta con una estructura que es similar a la de C:

if (expr)

statement

La expresión se evalúa a su valor Boolean. Si la expresión evalúa a TRUE, PHP ejecutará las instrucciones, y si se evalúa a FALSE la ignora.

El siguiente ejemplo se mostrará que "a es mayor que b" si $ a es mayor que $ b:

<?php

if ($a > $b)

echo "a is bigger than b";

?>

A menudo, lo que se quiere es tener más de una declaración para ser ejecutado condicionalmente. Por supuesto, no hay necesidad de envolver cada declaración con una cláusula IF. En lugar de ello, podemos agrupar varias sentencias. Por ejemplo, este código mostrará "a es mayor que b" si $ a es mayor que $ b, y luego asignar el valor de $ a a $ b:

<?php

if ($a > $b) {

echo "a is bigger than b";

$b = $a;

}

?>

La declaracion IF se pueden anidar indefinidamente en el marco de otras estructuras de control, que le proporciona una total flexibilidad para la ejecución condicional de las diferentes partes de tu programa.

Estructuras de Control en PHP: elseif

elseif, como su nombre sugiere, es una combinación de if y else. Como else, extiende una sentencia if para ejecutar una sentencia diferente en caso de que la expresión if original se evalúa como FALSE. No obstante, a diferencia de else, ejecutará esa expresión alternativa solamente si la expresión condicional elseif se evalúa como TRUE. Por ejemplo, el siguiente código mostraría a es mayor que b, a es igual a b o a es menor que b:

  

<?php

if ($a > $b) {

print "a es mayor que b";

} elseif ($a == $b) {

print "a es igual que b";

} else {

print "a es mayor que b";

}

?>


Puede haber varios elseifs dentro de la misma sentencia if. La primera expresión elseif (si hay alguna) que se evalúe como TRUE se ejecutaría. En PHP, también se puede escribir 'else if' (con dos palabras) y el comportamiento sería idéntico al de un 'elseif' (una sola palabra). El significado sintáctico es ligeramente distinto (si estas familiarizado con C, es el mismo comportamiento) pero la línea básica es que ambos resultarían tener exactamente el mismo comportamiento.

La sentencia elseif se ejecuta sólo si la expresión if precedente y cualquier expresión elseif precedente se evalúan como FALSE, y la expresión elseif actual se evalúa como TRUE.

Variables variables en PHP

A veces es conveniente tener nombres de variables variables. Dicho de otro modo, son nombres de variables que se pueden establecer y usar dinámicamente. Una variable normal se establece con una sentencia como:

<?php

$a = "hello";

?>

Una variable variable toma el valor de una variable y lo trata como el nombre de una variable. En el ejemplo anterior, hello, se puede usar como el nombre de una variable utilizando dos signos $. p.ej.

<?php

$$a = "world";

?>

En este momento se han definido y almacenado dos variables en el árbol de símbolos de PHP: $a, que contiene "hello", y $hello, que contiene "world". Es más, esta sentencia:

<?php

echo "$a ${$a}";

?>

produce el mismo resultado que:

<?php

echo "$a $hello";

?>

p.ej. ambas producen el resultado: hello world.

Para usar variables variables con matrices, hay que resolver un problema de ambigüedad. Si se escribe $$a[1] el intérprete necesita saber si nos referimos a utilizar $a[1] como una variable, o si se pretendía utilizar $$a como variable y el índice [1] como índice de dicha variable. La sintaxis para resolver esta ambigüedad es: ${$a[1]} para el primer caso y ${$a}[1] para el segundo.

Tener en cuenta que variables variables no pueden usarse con Matrices superglobales. Esto significa que no se pueden hacer cosas como ${$_GET}.

Qué es PHP?

PHP (acrónimo de "PHP: Hypertext Preprocessor") es un lenguaje de "código abierto" interpretado, de alto nivel, embebido en páginas HTML y ejecutado en el servidor.

Una respuesta corta y concisa, pero, ¿qué significa realmente? Un ejemplo nos aclarará las cosas:

 

<html>

<head>

<title>Ejemplo</title>

</head>

<body>

<?php

echo "Hola, soy un script PHP!";

?>

</body>

</html>

Puede apreciarse que no es lo mismo que un script escrito en otro lenguaje de programación como Perl o C -- En vez de escribir un programa con muchos comandos para crear una salida en HTML, escribimos el código HTML con cierto código PHP embebido (incluido) en el mismo, que producirá cierta salida (en nuestro ejemplo, producirá un texto). El código PHP se incluye entre etiquetas especiales de comienzo y final que nos permitirán entrar y salir del modo PHP.

Lo que distingue a PHP de la tecnología Javascript, la cual se ejecuta en la máquina cliente, es que el código PHP es ejecutado en el servidor. Si tuviésemos un script similar al de nuestro ejemplo en nuestro servidor, el cliente solamente recibiría el resultado de su ejecución en el servidor, sin ninguna posibilidad de determinar qué código ha producido el resultado recibido. El servidor web puede ser incluso configurado para que procese todos los archivos HTML con PHP.

Lo mejor de usar PHP es que es extremadamente simple para el principiante, pero a su vez, ofrece muchas características avanzadas para los programadores profesionales.

Que se puede hacer con PHP?

PHP puede hacer cualquier cosa que se pueda hacer con un script CGI, como procesar la información de formularios, generar páginas con contenidos dinámicos, o enviar y recibir cookies. Y esto no es todo, se puede hacer mucho más.

Existen tres campos en los que se usan scripts escritos en PHP.

Scripts del lado del servidor. Este es el campo más tradicional y el principal foco de trabajo. Se necesitan tres cosas para que esto funcione. El intérprete PHP (CGI ó módulo), un servidor web y un navegador. Es necesario correr el servidor web con PHP instalado. El resultado del programa PHP se puede obtener a través del navegador, conectándose con el servidor web. Consultar la sección Instrucciones de instalación para más información.

Scripts en la línea de comandos. Puede crear un script PHP y correrlo sin ningún servidor web o navegador. Solamente necesita el intérprete PHP para usarlo de esta manera. Este tipo de uso es ideal para scripts ejecutados regularmente desde cron (en *nix o Linux) o el Planificador de tareas (en Windows). Estos scripts también pueden ser usados para tareas simples de procesamiento de texto.

Escribir aplicaciones de interfaz gráfica. Probablemente PHP no sea el lenguaje más apropiado para escribir aplicaciones gráficas, pero si conoce bien PHP, y quisiera utilizar algunas características avanzadas en programas clientes, puede utilizar PHP-GTK para escribir dichos programas. También es posible escribir aplicaciones independientes de una plataforma. PHP-GTK es una extensión de PHP, no disponible en la distribución principal.

PHP puede ser utilizado en cualquiera de los principales sistemas operativos del mercado, incluyendo Linux, muchas variantes Unix (incluyendo HP-UX, Solaris y OpenBSD), Microsoft Windows, Mac OS X, RISC OS y probablemente alguno más. PHP soporta la mayoría de servidores web de hoy en día, incluyendo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape e iPlanet, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd y muchos otros. PHP tiene módulos disponibles para la mayoría de los servidores, para aquellos otros que soporten el estándar CGI, PHP puede usarse como procesador CGI.

De modo que, con PHP tiene la libertad de elegir el sistema operativo y el servidor de su gusto. También tiene la posibilidad de usar programación procedimental o programación orientada a objetos. Aunque no todas las características estándar de la programación orientada a objetos están implementadas en la versión actual de PHP, muchas bibliotecas y aplicaciones grandes (incluyendo la biblioteca PEAR) están escritas íntegramente usando programación orientada a objetos.

Con PHP no se encuentra limitado a resultados en HTML. Entre las habilidades de PHP se incluyen: creación de imágenes, archivos PDF y películas Flash (usando libswf y Ming) sobre la marcha. Tambié puede presentar otros resultados, como XHTM y archivos XML. PHP puede autogenerar éstos archivos y almacenarlos en el sistema de archivos en vez de presentarlos en la pantalla.

Quizás la característica más potente y destacable de PHP es su soporte para una gran cantidad de bases de datos. Escribir un interfaz vía web para una base de datos es una tarea simple con PHP. Las siguientes bases de datos están soportadas actualmente:

  • Adabas D
  • Ingres
  • Oracle (OCI7 and OCI8)
  • dBase
  • InterBase
  • Ovrimos
  • Empress
  • FrontBase
  • PostgreSQL
  • FilePro (read-only)
  • mSQL
  • Solid
  • Hyperwave
  • Direct MS-SQL
  • Sybase
  • IBM DB2
  • MySQL
  • Velocis
  • Informix
  • ODBC
  • Unix dbm

También contamos con una extensión DBX de abstracción de base de datos que permite usar de forma transparente cualquier base de datos soportada por la extensión. Adicionalmente, PHP soporta ODBC (el Estándar Abierto de Conexión con Bases de Datos), asi que puede conectarse a cualquier base de datos que soporte tal estándar.

PHP también cuenta con soporte para comunicarse con otros servicios usando protocolos tales como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (en Windows) y muchos otros. También se pueden crear sockets puros. PHP soporta WDDX para el intercambio de datos entre lenguajes de programación en web. Y hablando de interconexión, PHP puede utilizar objetos Java de forma transparente como objetos PHP Y la extensión de CORBA puede ser utilizada para acceder a objetos remotos.

PHP tiene unas características muy útiles para el procesamiento de texto, desde expresiones regulares POSIX extendidas o tipo Perl hasta procesadores de documentos XML. Para procesar y acceder a documentos XML, soportamos los estándares SAX y DOM. Puede utilizar la extensión XSLT para transformar documentos XML.

Si usa PHP en el campo del comercio electrónico, encontrará muy útiles las funciones Cybercash, CyberMUT, VeriSign Payflow Pro y CCVS para sus programas de pago.

Para terminar, contamos con muchas otras extensiones muy interesantes, las funciones del motor de búsquedas mnoGoSearch, funciones para pasarelas de IRC, utilidades de compresión (gzip, bz2),, conversión de calendarios, traducción, etc.

Como saber que navegador usa un visitante con PHP

Para hacerlo, vamos a consultar la información que el navegador nos envía como parte de su petición HTTP. Esta información es guardada en una variable. Las variables siempre comienzan con un signo de dólar ("$") en PHP. La variable que vamos a utilizar en esta situación es $_SERVER["HTTP_USER_AGENT"].

$_SERVER es una variable reservada por PHP que contiene toda la información del servidor web. Es conocida como Autoglobal (o Superglobal).

Para poder ver esta variable solo necesitamos el siguiente codigo:

<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>

esto nos dara un resultado similar a:

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

$_SERVER es simplemente una variable que se encuentra disponible automáticamente en PHP.

Por ejemplo, si quisiéramos detectar el uso de "Internet Explorer", haríamos algo así:

   

<?php

if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {

echo "Está usando Internet Explorer<br />";

}

?>

esto nos dara un resultado similar a:

Esta usando Internet Explorer

En el caso anterior estamos buscando "MSIE" dentro de $_SERVER["HTTP_USER_AGENT"]. Si la cadena fue encontrada, la función devolverá verdadero ("TRUE"), la declaración "if" se evalúa a verdadero ("TRUE") y el código adentro de las llaves {} es ejecutado. De otra manera no resulta ejecutado.

Contador de usuarios activos con PHP

Con este script podemos contar los usuarios activos con PHP.

No vamos a usar ninguna base de datos. En su lugar usaremos un archivo llamado usuarios.dat

Creamos nuestro script PHP y lo llamamos activos.php

<?php

$tiempo_logout = 600; // segundos tras los cuales un usuario es marcado como inactivo

$arr = file("usuarios.dat");

$contenido = $REMOTE_ADDR.":".time()." ";

for ( $i = 0 ; $i < sizeof($arr) ; $i++ )

{

$tmp = explode(":",$arr[$i]);

if (( $tmp[0] != $REMOTE_ADDR ) && (( time() - $tmp[1] ) < $tiempo_logout ))

{

$contenido .= $REMOTE_ADDR.":".time()." ";

}

}

$fp = fopen("usuarios.dat","w");

fputs($fp,$contenido);

fclose($fp);

$array = file("usuarios.dat");

$USUARIOS_ACTIVOS = count($array);

?>

La explicación de lo que hace el codigo anterior es la siguiente:

  • Cargamos usuarios.dat a un array
  • Creamos el archivo de texto con las IP y la hora de visita de los que visitan nuestra web
  • “Borramos” de ese archivo los que llevan más de $tiempo_logout sin actividad
  • Escribimos el archivo
  • Declaramos una variable $USUARIOS_ACTIVOS que contiene el número de usuarios activos del momento

Para utilizar este Script, al principio de cualquier página ponemos

<?php

include(”activos.php”)

?>

y donde queremos mostrar el número de usuarios, usamos la variable $USUARIOS_ACTIVOS.

Como poner comentarios en el codigo Php

PHP soporta el estilo de comentarios de 'C', 'C++' y de la interfaz de comandos de Unix. Por ejemplo:

 

<?php

echo "Esto es una prueba"; // Esto es un comentario de una linea al estilo c++

/* Esta es una linea de un comentario multilíneas

Esto es otra linea de un comentario multilinea */

echo "Esto es otra prueba";

echo "Y esto otra prueba mas"; # comentario tipo shell de unix

?>

Ejemplo:

   

<h1>Esto es un <?php # echo "simple";?> ejemplo.</h1>

<p>El encabezado de arriba dice 'Esto es un simple ejemplo'.

Hay que tener cuidado con no anidar comentarios de estilo 'C', algo que puede ocurrir al comentar bloques largos de código.

  

<?php

/*

echo "esto es una prueba"; /* Este comentario puede causar problemas */

*/

?>

Los estilos de comentarios de una linea comentan hasta el final de la linea o del bloque actual de código PHP, lo primero que ocurra. Esto implica que el código HTML tras // ?> será impreso: ?> sale del modo PHP, retornando al modo HTML, el comentario // no le influye.

Formas de Entrar y salir de PHP

Para interpretar un archivo, php símplemente interpreta el texto del archivo hasta que encuentra uno de los carácteres especiales que delimitan el inicio de código PHP. El intérprete ejecuta entonces todo el código que encuentra, hasta que encuentra una etiqueta de fin de código, que le dice al intérprete que siga ignorando el código siguiente. Este mecanismo permite embeber código PHP dentro de HTML: todo lo que está fuera de las etiquetas PHP se deja tal como está, mientras que el resto se interpreta como código.

Hay cuatro conjuntos de etiquetas que pueden ser usadas para denotar bloques de código PHP. De estas cuatro, sólo 2 (<?php. . .?> y <script language="php">. . .</script>) están siempre disponibles; el resto pueden ser configuradas en el fichero de php.ini para ser o no aceptadas por el intérprete. Mientras que el formato corto de etiquetas (short-form tags) y el estilo ASP (ASP-style tags) pueden ser convenientes, no son portables como la versión de formato largo de etiquetas. Además, si se pretende embeber código PHP en XML o XHTML, será obligatorio el uso del formato <?php. . .?> para la compatibilidad con XML.

Las etiquetas soportadas por PHP son:

Ejemplo: Formas de escapar de HTML

1. <?php echo("si quieres servir documentos XHTML o XML, haz como aquí\n"); ?>

2. <? echo ("esta es la más simple, una instrucción de procesado SGML \n"); ?>

<?= expression ?> Esto es una abreviatura de "<? echo expression ?>"

3. <script language="php">

echo ("muchos editores (como FrontPage) no

aceptan instrucciones de procesado");

</script>

4. <% echo ("Opcionalmente, puedes usar las etiquetas ASP"); %>

<%= $variable; # Esto es una abreviatura de "<% echo . . ." %>

El método primero, <?php. . .?>, es el más conveniente, ya que permite el uso de PHP en código XML como XHTML.

El método segundo no siempre está disponible. El formato corto de etiquetas está disponible con la función short_tags() (sólo PHP 3), activando el parámetro del fichero de configuración de PHP short_open_tag, o compilando PHP con la opción --enable-short-tags del comando configure. Aunque esté activa por defecto en php.ini-dist, se desaconseja el uso del formato de etiquetas corto.

El método cuarto sólo está disponible si se han activado las etiquetas ASP en el fichero de configuración: asp_tags.

nota: El soporte de etiquetas ASP se añadió en la versión 3.0.4.

nota: No se debe usar el formato corto de etiquetas cuando se desarrollen aplicaciones o bibliotecas con intención de redistribuirlas, o cuando se desarrolle para servidores que no están bajo nuestro control, porque puede ser que el formato corto de etiquetas no esté soportado en el servidor. Para generar código portable y redistribuíble, asegúrate de no usar el formato corto de etiquetas.

La etiqueta de fin de bloque incluirá tras ella la siguiente línea si hay alguna presente. Además, la etiqueta de fin de bloque lleva implícito el punto y coma; no necesitas por lo tanto añadir el punto y coma final de la última línea del bloque PHP.

PHP permite estructurar bloques como:

Ejemplo: Métodos avanzados de escape

<?php

if ($expression) {

?>

<strong>This is true.</strong>

<?php

} else {

?>

<strong>This is false.</strong>

<?php

}

?>

Este ejemplo realiza lo esperado, ya que cuando PHP encuentra las etiquetas ?> de fin de bloque, empieza a escribir lo que encuentra tal cual hasta que encuentra otra etiqueta de inicio de bloque. El ejemplo anterior es, por supuesto, inventado. Para escribir bloques grandes de texto generamente es más eficiente separalos del código PHP que enviar todo el texto mediante las funciones echo(), print() o similares.