Llenguatge PHP W3Schools
Exemples vistos a classe
Taules de multiplicar amb dos bucles for anidats:
<!DOCTYPE html>
<html>
<head>
<title>Taules de multiplicar</title>
</head>
<body>
<h1>Taules de multiplicar</h1>
<?php
for ($y=1; $y<=10; $y++) {
echo "<table border=\"1\">";
for ($x=1; $x<=10; $x++) {
echo "<tr><td>".$y." * ".$x." = </td><td>".$x*$y."</td></tr>";
}
echo "</table>";
echo "<br />";
}
?>
</body>
</html>
Celsius to Fahrenheit
hem fet una cerca ràpida a Google per trobar la funció que necessitem:
Sense necessitat d'entendre la funció, la gràcia de la programació estructurada és que no cal que entengui la funció. Només he de saber com fer-la servir en el meu codi.
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Celsius to Fahrenheit</title>
</head>
<body>
<h1>Celsius to Fahrenheit</h1>
<?php
echo "35ºC són ".celsius_to_fahrenheit(35)." F";
?>
</body>
</html>
Formulari amb persistència de les dades i gravar les dades a un fitxer:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Demanar informació</h1>
<?php include 'llibreria.php';?>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
if (empty($_POST["name"]) || empty($_POST["email"])) {
$nameErr = "Name and email are required";
echo $nameErr;
} else {
$myfile = fopen("client.txt", "a") or die("Unable to open file!");
fwrite($myfile, $name."\n");
fwrite($myfile, $email."\n");
fwrite($myfile, $website."\n");
fwrite($myfile, $comment."\n");
fwrite($myfile, $gender."\n");
fwrite($myfile, "===================\n");
fclose($myfile);
echo $name."<br />";
echo $email."<br />";
echo $website."<br />";
echo $comment."<br />";
echo $gender."<br />";
}
}
?>
<form action="form4.php" method="post">
Name: <input type="text" name="name" value="<?php echo $name ?>"> *<br />
E-mail: <input type="text" name="email" value="<?php echo $email ?>"> *<br />
Website: <input type="text" name="website" value="<?php echo $website ?>"><br />
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment ?></textarea><br />
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br />
<input type="submit">
</form>
</body>
</html>
Exercicis proposats
1. Posem en un array associatiu (http://www.w3schools.com/php/php_arrays.asp) els mesos i el número de dies que té cada mes. Utilitzant un bucle que recorri l'array, posar tots els dies de l'any 2016:
1 gen 2 gen ... 31 gen 1 feb ... 29 feb ... 31 des
Solució:
<html>
<head>
<title>Exercici proposat 1</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Exercici proposat 1</h1>
<h2>Dies de l'any</h2>
<?php
//http://www.w3schools.com/php/php_arrays.asp
$mesos = array("Gener"=>"31", "Febrer"=>"29", "Març"=>"31", "Abril"=>"30", "Maig"=>"31", "Juny"=>"30", "Juliol"=>"31", "Agost"=>"31", "Setembre"=>"30", "Octubre"=>"31", "Novembre"=>"30", "Desembre"=>"31");
foreach($mesos as $mes => $num_dia) {
//echo "mes=" . $mes . ", num_dies=" . $num_dia . "<br />";
for ($i=1; $i<=$num_dia;$i++) {
echo $i." ".$mes;
echo "<br />";
}
echo "<br />";
}
?>
</body>
</html>
2. Sabent que el 1 de gener del 2016 és divendres, formatar la següent sortida:
divendres 1 gen dissabte 2 gen ... diumenge 31 gen dilluns 1 feb ... dilluns 29 feb ... dissabte 31 des
Solució:
<html>
<head>
<title>Exercici proposat 2</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Exercici proposat 2</h1>
<h2>Dies de l'any i dies de la setmana</h2>
<?php
//http://www.w3schools.com/php/php_arrays.asp
$mesos = array("Gener"=>"31", "Febrer"=>"29", "Març"=>"31", "Abril"=>"30", "Maig"=>"31", "Juny"=>"30", "Juliol"=>"31", "Agost"=>"31", "Setembre"=>"30", "Octubre"=>"31", "Novembre"=>"30", "Desembre"=>"31");
$dies_setmana = array("dilluns", "dimarts", "dimecres", "dijous", "divendres", "dissabte", "diumenge");
$dia_setmana = 4;
foreach($mesos as $mes => $num_dia) {
//echo "mes=" . $mes . ", num_dies=" . $num_dia . "<br />";
for ($i=1; $i<=$num_dia;$i++) {
echo $dies_setmana[$dia_setmana]." ".$i." ".$mes;
$dia_setmana++;
if ($dia_setmana == 7) $dia_setmana=0;
echo "<br />";
}
echo "<br />";
}
?>
</body>
</html>
3. Estem fent un concurs de relats curs. En el teu portal tens un petit formulari on demanes a la gent que fiqui el seu nom, comentari, i que envïi un document pdf de menys de 200K. Els documents aniran a parar dins la carpeta pdf/. Referència:
- http://www.w3schools.com/php/php_file_upload.asp (Complete Upload File PHP Script)
Gestió dels errors
Per al programador és frustrant tenir un error en el script php i no tenir informació d'on s'ha produït l'error. Per ex, un simple error de sintaxi com deixar-se el punt i coma final produeix una pantalla blanca, i no tens ni idea d'on està l'error. La solució és fàcil, s'ha de configurar la gestió d'errors en el fitxer php.ini.
El fitxer php.ini normalment el trobaràs a:
- /etc/php5/apache2/php.ini
L'edites i mires la part de gestió d'errors:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Error handling and logging ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; This directive informs PHP of which errors, warnings and notices you would li ; it to take action for. The recommended way of setting values for this ; directive is through the use of the error level constants and bitwise ; operators. The error level constants are below here for convenience as well a ; some common settings and their meanings. ; By default, PHP is set to take action on all errors, notices and warnings EXC ; those related to E_NOTICE and E_STRICT, which together cover best practices a ; recommended coding standards in PHP. For performance reasons, this is the ; recommend error reporting setting. Your production server shouldn't be wastin ; resources complaining about best practices and coding standards. That's what ; development servers and development settings are for. ; Note: The php.ini-development file has this setting as E_ALL | E_STRICT. This ; means it pretty much reports everything which is exactly what you want during ; development and early testing. ; ; Error Level Constants: ; E_ALL - All errors and warnings (includes E_STRICT as of PHP 6.0. ; E_ERROR - fatal run-time errors ; E_RECOVERABLE_ERROR - almost fatal run-time errors ; E_WARNING - run-time warnings (non-fatal errors) ; E_PARSE - compile-time parse errors ; E_NOTICE - run-time notices (these are warnings which often result ; from a bug in your code, but it's possible that it was ; intentional (e.g., using an uninitialized variable and ; relying on the fact it's automatically initialized to an ; empty string) ; E_STRICT - run-time notices, enable to have PHP suggest changes ; to your code which will ensure the best interoperability ; and forward compatibility of your code ; E_CORE_ERROR - fatal errors that occur during PHP's initial startup ; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's ; initial startup ; E_COMPILE_ERROR - fatal compile-time errors ; E_COMPILE_WARNING - compile-time warnings (non-fatal errors) ; E_USER_ERROR - user-generated error message ; E_USER_WARNING - user-generated warning message ; E_USER_NOTICE - user-generated notice message ; E_DEPRECATED - warn about code that will not work in future versions ; of PHP ; E_USER_DEPRECATED - user-generated deprecation warnings ; ; Common Values: ; E_ALL & ~E_NOTICE (Show all errors, except for notices and coding standard ; E_ALL & ~E_NOTICE | E_STRICT (Show all errors, except for notices) ; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors ; E_ALL | E_STRICT (Show all errors, warnings and notices including coding s ; Default Value: E_ALL & ~E_NOTICE ; Development Value: E_ALL | E_STRICT ; Production Value: E_ALL & ~E_DEPRECATED ; http://php.net/error-reporting ; error_reporting = E_ALL & ~E_DEPRECATED ; error_reporting = E_ALL & ~E_NOTICE ; error_reporting = E_WARNING & ~E_NOTICE & ~E_DEPRECATED error_reporting = E_ALL & ~E_NOTICE
Un valor correcte és
error_reporting = E_ALL & ~E_NOTICE
que vol dir que mostres tots els errors i warnings, i no mostris les notificacions.
També és important:
display_errors = On
creat per Joan Quintana Compte, novembre 2013, novembre 2017