Saltar al contenido
Underc0de /foro

[ + ] PHP Manual... Everything You Need to Learn It

🌐 This is an automatic translation of a topic from Underc0de, the largest Spanish-speaking hacking and IT community. Read the original (Spanish) and reply →
Alex ·
I want to clarify that as of today 31/10/13 this manual is more than 5 years old, it's a classic but it shouldn't be taken as "everything about php", it's not even half of what you need to know about php.<br /><br />It's not my own work, it's by a friend, carlmycol<br /><br />I'm posting it because it's the manual I started with and it brought back old memories hehehehe<br /><br />
Index
<br />
Citar<br />Part One<br /><br /> 1   What is PHP?         <br /> 2   "Hello World" program in PHP         <br /> 3   A little program more useful than "Hello World"         <br /> 4   Variable types         <br /> 5   String variables         <br /> 6   Conditional structure (if)         <br /> 7   Loop structures (for - while - do/while)         <br /> 8   Sending data from a FORM (text and submit controls)         <br /> 9   FORM (radio control)         <br />10   FORM (checkbox control)
<br />
Citar<br />Part Two<br />11   FORM (select control)         <br />12   FORM (textarea control)         <br />13   Arrays (traditional)         <br />14   Creating a text file.         <br />15   Reading a text file.         <br />16   Arrays (associative)         <br />17   Functions in PHP         <br />18   Database (MySQL)         <br />19   INSERT (Adding records to a table)         <br />20   Listing (selecting records from a table)          
<br /><br />
CitarPart Three<br />21   Query (selecting records from a table)          <br />22   DELETE (Removing a record from a table)         <br />23   DELETE (Removing all records from a table)         <br />24   UPDATE (Modifying a record in a table)         <br />25   INSERT (and querying another table)         <br />26   Listing (selecting records from several tables - INNER JOIN)          <br />27   SQL count function.         <br />28   UPDATE (Modifying a record working with two tables)         <br />29   SQL Group By clause.         <br />30   Parameters in a hyperlink.
<br /><br />
CitarPart Four<br />31   Record pagination.         <br />32   Uploading a file to the server (Upload)         <br />33   Creating and reading a cookie         <br />34   Deleting a cookie         <br />35   Session cookie         <br />36   Session variables ($_SESSION)         <br />37   Including an external file (require_once)         <br />38   Redirecting to another page (header)         <br />39   Creating dynamic images from PHP.         <br />40   Adding dynamic images to an HTML file
<br /><br />
CitarPart Five<br />41   Handling dates and times (date function)         <br />42   Validating a date entered from the keyboard (checkdate)         <br />43   Storing a date in a MySQL table          <br />44   Formatting data on a page (printf)         <br />45   Formatting data and output to a string (sprintf)         
<br /><br />
Chapters Proposed by Sknight
<br /><br />
Citar1.-     Touch up the part about what PHP is<br /><br />2.-     Add a section on Libraries in PHP.<br /><br />3.-     Processing forms, there you'd have to merge several parts of the tutorial you posted, and also add something about the GET and POST methods<br /><br />4.-     Managing MySQL Databases with PHP: Creating a database, Connecting to a db, Querying the db, Inserting records, deleting records<br /><br />5.-     Object-oriented PHP<br /><br />6.-     I'll send you the image upload I made for my new website, to improve the upload part.
<br /><br />Source: PHPya.com.ar
Alex ·
Start of Part One<br /><br />
What is PHP?
<br /><br />PHP (acronym for "PHP: Hypertext Preprocessor") is a high-level interpreted language embedded in HTML pages and executed on the server.<br /><br />To start programming in PHP, you first need to understand how page requests work in a browser.<br /><br />Communication between client and server without PHP:<br /><br />1 - We type the address and the file to request in the browser bar.<br /><br />2 - The web browser sends the message over the Internet to the computer, for example Los enlaces son solo para miembros. Registrate o iniciá sesión requesting the page (file) pagina1.htm<br /><br />3 - The web server (which can be Apache, IIS, etc.), which is a program running on the machine www.lanacion.com, receives the message and reads the requested file from the hard drive.<br /><br />4 - The web server sends the file requested by the browser exactly as it is on the hard drive.<br /><br />5 - The browser displays on screen the file the web server sent.<br /><br />This process is always the same when we talk about static pages (pages that don't change); whatever client requests the page, the content will always be the same. The only way for the file's content to change is for the administrator of that website to edit the content of the file pagina1.htm and make changes.<br /><br /><br />Communication between client and server with PHP:<br /><br />1 - We type the address and the file to request in the browser bar.<br />2 - The web browser sends the message over the Internet to the computer called www.lanacion.com requesting the page (file) pagina1.php<br /><br />3 - The web server (which can be Apache, IIS, etc.) receives the message and, seeing that the extension is "php", asks the PHP interpreter (another program running on the web server) to send it the file.<br /><br />4 - The PHP interpreter reads the file pagina1.php from disk<br /><br />5 - The PHP interpreter executes the commands contained in the file and possibly communicates with a database manager (examples include MySql, Oracle, Informix, SQL Server, etc.)<br /><br />6 - After executing the program contained in the file, it sends it to the web server.<br /><br />7 - The web server sends the page to the client that requested it.<br /><br />8 - The browser displays on screen the file the web server sent.<br /><br />For those who know other programming languages (C - Java - C# - Pascal etc.), output normally goes to the screen; in PHP the output is the HTML page (which then travels over the internet and reaches the client that requested it)
Alex ·
"Hello World" program in PHP
<br /><br />In this course we assume you know the main HTML tags and some programming language, at least a little bit.<br />To add a PHP program inside an HTML page, on the one hand when creating the file we must give it the php extension (unlike static pages that have the htm or html extension), and within the page content, enclose the program between the symbols <?php [aqui el programa PHP] ?>.<br /><br />The PHP command to print inside the page is called echo. Our "Hello World" program will then be:<br /><br />
Código: text
<html><br /><head></head><br /><body><br /><?php<br />  echo "Hola Mundo";<br />?><br /></body><br /></html>
<br /><br />That is, the page generated when the program runs will be:<br /><br />
Código: text
<html><br /><head></head><br /><body><br />Hola Mundo<br /></body><br /></html>
<br /><br /><br />As we can see, this little program is not very useful, since the result of running this PHP program will always be the same, that is, displaying the text "Hola Mundo".
Alex ·
Operators in PHP (arithmetic, logical, comparison)
<br /><br />A simple problem we may face that can't be solved using only HTML is making a page available only during the first 10 days of the month.<br />We'll show a sign saying the site is available if the date is less than or equal to 10; otherwise we'll show an out-of-service message.<br /><br />To get the web server's date we must call the date function and request only the day:<br />$dia=date("d");<br /><br />Variables in PHP are preceded by the $ character. If we pass the string "d" to the date function it will return only the day (if we want the full date: $fecha=date("Y:m:d")<br /><br />To check whether the variable $dia is less than or equal to 10, we must use the if statement, similar to other languages.<br />So the page with the program looks like this:<br /><br />
Código: text
<html><br /><head></head><br /><body> <br /><br /><?php $dia=date("d"); if ($dia<=10) { echo "sitio activo"; } else { echo "sitio fuera de servicio"; } ?><br /><br /></body> </html>
<br /><br /><br />Variable names are case-sensitive, so if we initially write it in lowercase we must keep it that way in the rest of the program. However, PHP language statements are not case-sensitive, so whether we write IF or if, both forms will be fine. Those of us coming from other languages like C, C++, Java are used to writing keywords in lowercase, but this is just habit.<br />The if condition must be enclosed in parentheses. The available relational operators are:<br /><br />> Greater than<br />>= Greater than or equal<br />< Less than<br /><= Less than or equal<br />== Equal<br />!= Not equal<br /><br />If the condition evaluates to true, the first block enclosed in braces is executed; if the condition evaluates to false, the block in braces following the else is executed.
Alex ·
Variable Types
<br /><br />Variable names start with the $ sign and are case-sensitive (unlike the language keywords).<br /><br />In PHP it's not necessary to define the type before using a variable; variables are created at the moment they are used. Variables are declared when a value is assigned to them, for example:<br /><br />$dia = 24; //Se declara una variable de tipo integer.<br />$sueldo = 758.43; //Se declara una variable de tipo double.<br />$nombre = "juan"; //Se declara una variable de tipo string.<br />$exite = true; //Se declara una variable boolean.<br /><br />We can also point out that for line comments we must use two characters //<br /><br />To print variables we'll initially use the echo command. A complete program that initializes and displays the contents of four variables of different types is:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />$dia = 24; //Se declara una variable de tipo integer.<br />$sueldo = 758.43; //Se declara una variable de tipo double.<br />$nombre = "juan"; //Se declara una variable de tipo string.<br />$exite = true; //Se declara una variable boolean.<br />echo "Variable entera:";<br />echo $dia;<br />echo "<br>";<br />echo "Variable double:";<br />echo $sueldo;<br />echo "<br>";<br />echo "Variable string:";<br />echo $nombre;<br />echo "<br>";<br />echo "Variable boolean:";<br />echo $exite;<br />?><br /></body><br /></html>
<br /><br />We used one echo command to display the messages, another for the contents of the variables, and finally another to print HTML tags. This process can be shortened a bit, but to keep things clearer at first we'll take the long road of printing one piece of data with each echo command.
Alex ·
String Variables
<br />A variable of this type can store a series of characters.<br />$cadena1="Hola";<br />$cadena2="Mundo";<br />echo $cadena1." ".$cadena2;<br /><br />To concatenate strings we use the . operator<br /><br />Keep in mind that the echo command above could be written longer like this:<br />echo $cadena1;<br />echo " ";<br />echo $cadena2;<br /><br />As you do exercises, we'll be able to condense the output of multiple variables into a single echo command.<br />When a string enclosed in double quotes contains a variable inside it, it is treated as such, so its contents will be used for storage.<br /><br />$dia=10;<br />$fecha="Hoy es $dia";<br />echo $fecha;<br />The screen shows: Hoy es 10<br />That is, in the string, the variable name $dia is replaced with its contents.<br /><br />A string can be defined with single quotes (but it's important to keep in mind that variables are not substituted if we use single quotes):<br /><br />$nombre='juan carlos';
Alex ·
Conditional structure (if)
<br /><br />When we want the program, once it reaches a certain point, to take a specific path in some cases and a different one if the execution conditions differ, we use the set of statements:<br />if, else and elseif. The basic structure of this type of statement is as follows:<br /><br />if (Condición) <br />{<br />  Instrucción 1;<br />  Instrucción 2;<br />}<br />else<br />{<br />  Instrucción A;<br />  Instrucción B;<br />}<br /><br />When execution reaches the point where the if statement is, the program will check whether or not the condition is met. If the condition is true, statements 1 and 2 will be executed; otherwise, statements A and B will be executed.<br />In cases where there are several conditions, ifs can be used in a so-called nested way, as shown below:<br /><br />if (Condicion 1) <br />{<br />  Instrucción 1;<br />  Instrucción 2;<br />}<br />else<br />{<br />  if (Condicion 2)<br />  {               <br />    Instrucción A;<br />    Instrucción B;<br />  }<br />  else<br />  {<br />    Instrucción X;<br />    Instrucción Z;<br />  }<br />}<br /><br />This way you can introduce as many conditions as you want within the main condition. A variant of this system uses the elseif statement, which lets you introduce an additional condition in a single line:<br /><br />if (Condicion 1) <br />{<br />  Instrucción 1;<br />  Instrucción 2;<br />}<br />elseif (Condicion 2)<br />{<br />  Instrucción A;<br />  Instrucción B;<br />}<br />else<br />{<br />  Instrucción X;<br />  Instrucción Z; <br />}<br /><br />For conditions, keep in mind we have the following operators:<br />== to check if one variable equals another.<br />!= not equal.<br />>= greater than or equal.<br />> greater than.<br /><= less than or equal<br />< less than<br /><br />The best way to understand this conditional structure is through examples. The first one we'll tackle is generating a random value (that is, the machine picks it at random, like drawing a ball from a lottery drum) between 1 and 10. Then we'll show a message saying whether it's less than or equal to 5 or greater than 5.<br />The complete program is:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />$valor=rand(1,10);<br />echo "El valor sorteado es $valor<br>";<br />if ($valor<=5)<br />{<br />  echo "Es menor o igual a 5";<br />}<br />else<br />{<br />  echo "Es mayor a 5";<br />} <br />?><br /></body><br /></html>
<br /><br />It's important to remember that the if condition must always be in parentheses. If the if condition evaluates to true (that is, the drawn number is less than or equal to 5), the first block between braces is executed. If the if condition evaluates to false, the block between braces after the else is executed.<br />We generate the random value by calling the random function, passing it the minimum and maximum values:<br /><br />$valor=rand(1,10);<br /><br />We print the generated value in order to check the result:<br /><br />echo "El valor sorteado es $valor<br>";<br /><br />In the first problem we have only two possible paths: the value is less than or equal to five, or it's greater. In a second example we'll show how to set up a nested if conditional structure.<br />The problem is the following: Generate a random value between 1 and 100. Then show whether it has 1, 2 or 3 digits.<br />As we can see, this is a problem with three possible paths. The value can have 1 digit, 2 digits or 3 digits. If we think a bit, we can see that to have one digit a value between 1 and 9 must be generated, to have two digits it must be between 10 and 90, and finally to have 3 digits the value must be 100.<br />The page with the corresponding program is:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />$valor=rand(1,100);<br />echo "El valor sorteado es $valor<br>";<br />if ($valor<=9)<br />{<br />  echo "Tiene un dígito";<br />}<br />else<br />{<br />  if ($valor<100)<br />  {<br />    echo "Tiene 2 dígitos";<br />  }<br />  else<br />  {<br />    echo "Tiene 3 dígitos";<br />  }<br />}<br />?><br /></body><br /></html>
<br /><br />It's important to note how the second if structure is contained within the braces of the else of the first if. That is, if the random value is less than or equal to 9, the true block of the first if is executed and therefore the if nested in the else is not executed. Conversely, if the condition of the first if evaluates to false, the else block of the first if is executed, which contains an if structure with its true and false blocks.<br /><br />For illustration, the same example solved with the if/elseif structure would be:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />$valor=rand(1,100);<br />echo "El valor sorteado es $valor<br>";<br />if ($valor<=9)<br />{<br />  echo "Tiene un dígito";<br />}<br />elseif ($valor<100)<br />{<br />  echo "Tiene 2 dígitos";<br />}<br />else<br />{<br />  echo "Tiene 3 dígitos";<br />}<br />?><br /></body><br /></html>
<br /><br />If you have a lot of practice with other programming languages, this nested if structure will suit you better; if you started programming recently, it's best to choose and practice the first form.
Alex ·
Loop structures (for - while - do/while)
<br /><br />Loop structures are similar to the C language.<br />for structure:<br />for([Inicialización de la variable];[Condición];[Incremento o decremento de la variable])<br />{<br />[Instrucciones];<br />}<br /><br />The first example we'll do is display the numbers from 1 to 100 on the page:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />for($f=1;$f<=100;$f++)<br />{<br />  echo $f;<br />  echo "<br>";<br />}<br />?><br /></body><br /></html><br /><br />Quien no ha visto la estructura for en otro lenguaje pasamos a explicarla:<br /><br />for($f=1;$f<=100;$f++)<br />{<br />  echo $f;<br />  echo "<br>";<br />}
<br /><br />The first argument of the for is the initialization of a variable; in this case the variable $f is initialized with the value 1. This first argument of the for is executed only once. Then the second argument, which is the condition, is executed. If it evaluates to true, the whole block between the opening and closing braces is executed. After the loop block has executed, the third argument of the for is executed, which is the variable increment; in this case $f++ increments the contents of the variable $f by 1 (instead of $f++ we can also write the assignment $f=$f+1).<br />After the variable increment, the for condition (second argument) is executed again; if it validates as true again, it goes on to execute the loop block.<br />This cycle repeats until the for condition evaluates to false.<br /><br />The second loop structure is:<br />while (condición)<br />{<br />[Instrucciones];<br />}<br /><br />This structure exists in almost every language. The block repeats while the while condition is true.<br />The while condition is checked before entering the block to repeat. If it evaluates to false the first time, the block will not be executed.<br />Let's look at an example: Generate a random value between 1 and 100, then print on the page from 1 up to the generated value (one by one):<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body><br /><?php<br />$valor=rand(1,100);<br />$inicio=1;<br />while($inicio<=$valor)<br />{<br />  echo $inicio;<br />  echo "<br>";<br />  $inicio++;<br />}<br />?><br /></body><br /></html>
<br /><br />The variable $inicio has the value 1 before entering the while. Each time the while block runs once, $inicio is incremented by one. When $inicio exceeds the random variable $valor, the loop structure ends and execution moves to the statement immediately following the closing brace.<br />It's important to note that after the while condition we do NOT put a SEMICOLON.<br /><br />Finally, the language has a loop structure similar to while called do/while, where the condition is checked after the loop block executes.<br />do<br />{<br />[Instrucciones];<br />} while (condición);<br /><br />As homework, try to make a page using this structure. Keep in mind that at the end of the while line there IS a semicolon.
Alex ·
Sending data from a FORM (text and submit controls)
<br /><br />Handling FORMS generally requires two pages, one that implements the form and another that processes the data entered in the form.<br />The minimal structure of a form is the following: for entering a person's name, a text object and a button to send the data to the server:<br /><br />
Código: text
<html> <br />  <head> <br />  <title>Formulario de entrada del dato</title> <br />  </head> <br />  <body><br /><form method="post" action="pagina2.php"> <br />  Ingrese su nombre: <br />  <input type="text" name="nombre"> <br />  <br> <br />  <input type="submit" value="confirmar"> <br />  </form><br /></body> <br /></html>
<br /><br /><br />This page is coded entirely in HTML, that is, a form contains pure HTML tags.<br />The <form> and </form> tags let us define a form on the page. The FORM tag has two properties we must initialize: action and method. The action property indicates the name of the file that will receive the data entered by the user in the form, which will be sent to the server when the button (submit) is pressed. The method property indicates how that data is organized to send it to the server, either via the post or get methods (form data is normally sent using the post method).<br />To create a text box for entering the name we must define an object of type "text" and give it a name:<br /><input type="text" name="nombre"><br />The type property lets us define the type of control and with the name property we indicate the control's name.<br />Finally, every form has a submit-type button:<br /><input type="submit" value="confirmar"><br />We also use the input tag, but in the type property we indicate that it's a data submission button. In the value property we indicate the text we want to appear on the button.<br />Now we need a page with a small PHP program that processes the data entered in the form:<br /><br />
Código: text
<html> <br />  <head> <br />  <title>Captura de datos del form</title> <br />  </head> <br />  <body><br /><?php <br />  echo "El nombre ingresado es:"; <br />  echo $_REQUEST['nombre']; <br />  ?><br /></body> <br /></html>
<br /><br />To access the data in PHP there is an array called $_REQUEST, using as the index the name of the text box we defined in the form (that name is case-sensitive)<br />In our problem we just display on screen the value entered on the previous page:<br />echo $_REQUEST['nombre'];
Alex ·
FORM (radio control)
<br /><br />To analyze this control we'll set up an example:<br />Implement a form that asks for two integers, one in each text. Add two radio-type controls that let us choose whether to add or subtract the two values entered:<br /><br />
Código: text
<html><br />  <head><br />  <title>Problema</title><br />  </head><br />  <body><br /><form action="pagina2.php" <br />  method="post"><br />  Ingrese primer valor:<br />  <input type="text" name="valor1"><br />  <br><br />  Ingrese segundo valor:<br />  <input type="text" name="valor2"><br />  <br><br />  <input type="radio" name="radio1" value="suma">sumar<br />  <br><br />  <input type="radio" name="radio1" value="resta">restar<br />  <br><br />  <input type="submit" name="operar"><br />  </form><br /></body><br />  </html>
<br /><br /><br />It's important to note that this is again a pure HTML file, with no PHP code.<br />The two numbers are entered in two controls<br /><input type="text" name="valor1"> <input type="text" name="valor2"> It's important to note that each text has a DIFFERENT name.<br />To select the type of operation to perform we use two radio-type controls:<br /><input type="radio" name="radio1" value="suma">sumar<br> <input type="radio" name="radio1" value="resta">restar It's important to note that both controls have the SAME name. This is necessary so the browser knows the two controls are related (remember that when you select one radio the other must be deselected)<br />From the other page we'll access the value of the selected control.<br /><br />Finally we add a submit-type control to send the form data.<br />The code of the page that processes the form, called "pagina2.php" (the one we specified in the form's FORM tag), is:<br /><br />
Código: text
<html><br />  <head><br />  <title>Problema</title><br />  </head><br />  <body><br /><?php<br />  if ($_REQUEST['radio1']=="suma")<br />  {<br />    $suma=$_REQUEST['valor1'] + $_REQUEST['valor2'];<br />    echo "La suma es:".$suma;<br />  }<br />  else<br />  {<br />    if ($_REQUEST['radio1']=="resta")<br />    {<br />      $resta=$_REQUEST['valor1'] - $_REQUEST['valor2'];<br />      echo "La resta es:".$resta;<br />    }<br />  }<br />?><br /></body><br /> </html>
<br /><br />The associative array $_REQUEST has three components: $_REQUEST['radio1'] $_REQUEST['valor1'] $_REQUEST['valor2'] The component $_REQUEST['radio1'] stores the string "suma" or "resta" depending on which was selected in the form.<br />With two ifs we check which operation is selected and perform it:<br /><br />  if ($_REQUEST['radio1']=="suma")<br />  {<br />  $suma=$_REQUEST['valor1'] + $_REQUEST['valor2'];<br />  echo "La suma es:".$suma;<br />  .<br />  .
Alex ·
FORM (checkbox control)<br />
<br /><br />To analyze this control we'll use practically the same example as with the radio object:<br />Implement a form that asks for two integers, one in each text. Add two checkbox-type controls that let us choose whether to add and/or subtract the values entered.<br /><br />The html form has the following code:<br /><br />
Código: text
<head><br />  <title>Problema</title><br />  </head><br />  <body><br /><form action="pagina2.php" <br />  method="post"><br />  Ingrese primer valor:<br />  <input type="text" name="valor1"><br />  <br><br />  Ingrese segundo valor:<br />  <input type="text" name="valor2"><br />  <br><br />  <input type="checkbox" name="check1">sumar<br />  <br><br />  <input type="checkbox" name="check2">restar<br />  <br><br />  <input type="submit" name="operar"><br />  </form><br /></body><br />  </html>
<br /><br />What's new in this problem are the two checkbox-type controls:<br /><br />  <input type="checkbox" name="check1">sumar<br />  <br><br />  <input type="checkbox" name="check2">restar<br />  <br><br /><br />It's important to note that each checkbox has a different name.<br /><br />Now let's look at the code of the page that processes the form:<br /><br />
Código: text
<html><br /><head><br /><title>Problema</title><br /></head><br /><body> <br /><?php<br />  if (isset($_REQUEST['check1']))<br />  {<br />    $suma=$_REQUEST['valor1'] + $_REQUEST['valor2'];<br />    echo "La suma es:".$suma."<br>";<br />  }<br />  if (isset($_REQUEST['check2']))<br />  {<br />    $resta=$_REQUEST['valor1'] - $_REQUEST['valor2'];<br />    echo "La resta es:".$resta;<br />  }<br />  ?><br /></body><br />  </html>
<br /><br />If the checkbox is not selected in the form, no entry is created in the associative array $_REQUEST; to know whether a given component exists in an array we use the isset function; if it returns true it means it exists and therefore the checkbox is selected.<br />We place two ifs at the same level since both checkbox-type controls could be selected.<br /><br />End of Part One
Grupo de WhatsApp