Vous êtes sur la page 1sur 11

Ficheros

EjemploFicheros
contador.txt

index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejemplo Ficheros</title>
</head>
<body>
<h1>Contador</h1>
<?php
$lectura = fopen("contador.txt", "r") or die("Unable to opne file!");
$tamano = filesize('contador.txt');
if ($tamano > 0){
$visitas = fread($lectura, $tamano);
echo "<h2> Visitantes: $visitas </h2>";
}else{
$visitas = 0;
echo "<h2> Visitantes: $visitas </h2>";
}
fclose($lectura);

$escritura = fopen("contador.txt", "w") or die("Unable to opne file!");


$visitas = $visitas+1;
fwrite($escritura,$visitas);
fclose($escritura);

?>

</body>
</html>

Practica2
contactos.txt

index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>
<body>
<div class="container text-left">
<h1><strong>Agenda de contactos</strong></h1>

<a href="nuevo_contacto.php" class="btn btn-info" role="button">Nuevo


contacto</a>

<?php

$lectura = fopen("contactos.txt", "r") or die("Unable to opne file!");


$tamano = filesize('contactos.txt');
if ($tamano > 0){

while($linea = fgets($lectura)){
if(feof($lectura)) break;
$partes = explode(":",$linea);
echo "<div>";
echo "<h2>$partes[0]</h2>";
echo "<p>$partes[1] - $partes[2]</p>";
echo '<a href="borrar_contacto.php?telefono='.$partes[1].'"
role="buttton" class="btn btn-danger">Borrar</a>';
echo '<a href="editar_contacto.php?nombre='.
$partes[0].'&telefono='. $partes[1].'&email='.$partes[2].'" role="buttton"
class="btn btn-default">Editar</a>';

}else{
$visitas = 0;
echo "<br><br>No tienes ningn contacto en la lista.";
}

fclose($lectura);
?>

</div>

</body>
</html>

nuevo_contacto.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>
<body>
<div class="container text-left">
<h1><strong>Nuevo contacto</strong></h1>
<a href="index.php">Volver al inicio</a>

<div class="tab-pane" id="form1"><br/>


<form action="guardar.php" method="get" id="formulario" data-
toggle="validator" class="form-horizontal">
<div class="form-group">
<label for="login" class="control-label col-sm-
2">Nombre:</label>
<div class="col-sm-6">
<input type="text" class="form-control"
id="nombre" name="nombre" data-error="Por favor, introduzca
un login" required>
</div>
<div class="help-block with-errors"></div>
</div>

<div class="form-group">
<label class="control-label col-sm-2"
for="login">Telfono:</label>
<div class="col-sm-6">
<input class="form-control" type="tel"
id="telefono" name="telefono" data-error="Por favor, introduzca un
telfono vlido" required>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email" class="control-label col-sm-2">E-
mail:</label>
<div class="col-sm-6">
<input type="email" class="form-control"
id="email" name="email" data-error="Por favor, introduzca un e-mail
vlido" required>
</div>
<div class="help-block with-errors"></div>
</div>

<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" id="guardar"
name="guardar" class="btn btn-
default">Guardar</button>
</div>
</div>
</form>

</div>
</div>
</body>
</html>

guardar.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>
<body>

<?php
$nombre = $_GET['nombre'];
$telf = $_GET['telefono'];
$email = $_GET['email'];

$escritura = fopen("contactos.txt","a");

$linea = $nombre.":".$telf.":".$email .PHP_EOL;

fwrite($escritura,$linea);
fclose($escritura);

header('Location: index.php');
?>

</body>
</html>

borrar_contacto.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
$telefono = $_GET['telefono'];

$lectura = fopen("contactos.txt", "r") or die("Unable to opne file!");


$escritura = fopen("contactos2.txt", "w");

while (!feof($lectura)){

$linea = fgets($lectura);
$partes = explode(":",$linea);

if( $partes[1] == $telefono ){


fread($lectura,$linea);

}else{
fwrite($escritura,$linea);
}

fclose($lectura);
fclose($escritura);

rename("contactos2.txt", "contactos.txt");

header('Location:index.php');
?>

</body>
</html>

editar_contacto.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>

<div class="container text-left">


<h1><strong>Editar contacto</strong></h1>
<a href="index.php">Volver al inicio</a>
<?php
$nombre = $_GET['nombre'];
$telefono = $_GET['telefono'];
$email = $_GET['email'];
?>

<div class="tab-pane" id="form2"><br/>


<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get"
id="formulario" data-toggle="validator" class="form-
horizontal">
<div class="form-group">
<label for="login" class="control-label col-sm-
2">Nombre:</label>
<div class="col-sm-6">
<input type="text" class="form-control"
id="nombre2" name="nombre2" value="<?php echo $nombre; ?>" data-error="Por favor,
introduzca un login" required>
</div>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"
for="login">Telfono:</label>
<div class="col-sm-6">
<input class="form-control" type="tel"
id="telf2" name="telf2" value="<?php echo $telefono; ?>" readonly="readonly" data-
error="Por favor, introduzca un telfono vlido" required>
</div>
<div class="help-block with-errors"></div>
</div>

<div class="form-group">
<label for="email" class="control-label col-sm-2">E-
mail:</label>
<div class="col-sm-6">
<input type="email" class="form-control"
id="email2" name="email2" value="<?php echo $email; ?>" data-error="Por favor,
introduzca un e-mail vlido" required>
</div>
<div class="help-block with-errors"></div>
</div>

<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" id="guardar2"
name="guardar2" class="btn btn-
default">Guardar</button>
</div>
</div>
</form>
</div>
</div>
<?php

$nombre2 = $_GET['nombre2'];
$email2 = $_GET['email2'];

$lectura = fopen("contactos.txt", "r") or die("Unable to opne file!");


$escritura = fopen("contactos2.txt", "w");

$linea = fgets($lectura);
$partes = explode(":",$linea);

if ( $partes[0] == $nombre ){
fread($lectura,$linea);
}

// if( $partes[0] == $nombre2 ){


// fread($lectura,$linea);

// }else{
// $partes[0] = $nombre2;
// $linea = $partes[0].":".$partes[1].":".$partes[2];
// fwrite($escritura,$linea);
// }

// if( $partes[2] == $email2 ){


// fread($lectura,$linea);
// }else{
// $partes[2] = $email2;
// $linea = $partes[0].":".$partes[1].":".$partes[2];
// fwrite($escritura,$linea);
// }

fclose($lectura);
fclose($escritura);

rename("contactos2.txt", "contactos.txt");

if(isset($_GET['guardar2'])){
header('Location: index.php');
}

?>
</body>
</html>

nuevo2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if(isset($_GET['guardar'])){
$nombre = $_GET['nombre'];
$email = $_GET['telefono'];
$telf = $_GET['email'];

header('Location: guardar.php?nombre=$nombre&email=$email&telf=$telf');

}else{

}
?>

</body>
</html>

Cookies
Usar para almacena inf y no relevante en el funcionamiento de la web. No utilizar para
almacenar inf privada del usuario.
1. Crear cookie:
setcookie("colorFavorito", "#432FA1", time()+3600);

2. Consultar cookie:
$color = $_COOKIE["colorFavorito"];
echo "<style>body { background-color: " . $color . "; }</style>";

Ejercicio 26
preferencias.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejercicio 1 Cookies</title>
</head>
<body>

<h2>Selecciona preferencias: </h2>


<form action="guarda_prefs.php" method="get">
<label>Nombre: </label>
<input type="text" name="nombre" id="nombre" />
<br><br>

<label>Color: </label>
<input type="color" name="color" id="color" value="#000000" />
<br><br>

<input type="submit" name="enviar" id="enviar" value="Enviar"/>

</form>

</body>
</html>

guarda_prefs.php
<?php
$nombre = $_GET['nombre'];
$color = $_GET['color'];

setcookie("nombreusu", $nombre, time()+300);


setcookie("colorusu", $color, time()+300);

header ('Location: index.php');

?>

borrar_prefs.php
<?php

setcookie("nombreusu", $nombre, time()-1);


setcookie("colorusu", $color, time()-1);

header ('Location: index.php');

?>

index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<?php
if (isset($_COOKIE['colorusu'])){
echo "<style>body { background-color: " . $_COOKIE['colorusu'] . "; }
</style>";

}
?>
</head>
<body>

<?php

if (isset($_COOKIE['nombreusu'])){
echo '<h1>Bienvenido ' .$_COOKIE['nombreusu'].'</h1>';

}else{
echo 'Pgina de inicio';
}
echo '<br><br>';

?>

<a href="preferencias.php">Guardar preferencias</a>


<a href="borrar_prefs.php">Borrar preferencias</a>

</body>
</html>
Sesiones
Usar para almacenar datos complejos, o cruciales en el funcionamiento de la web. No
utilizar para almacenar inf privada del usuario.

1. Crear sesion:
<?php session_start(); ?>

2. Guardar y recuperar datos de la session:


$_SESSION["loginUsuario"] = $_REQUEST["login"];

3. Eliminar algun dato de la session:


unset($_SESSION["loginUsuario"]);

4. Borrar todas las variables que hemos creado con la session:


$_SESSION = array();

5. Cerrar o destruir session:


<?php session_destroy() ?>

Ejercicio 27
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejercicio 27</title>
</head>
<body>
<?php
$_SESSION['zapatillas'] = 40;
$_SESSION['sudadera'] = 15;
$_SESSION['pala'] = 50;
$_SESSION['pelota'] = 20;
$_SESSION['carro'] = 0;

?>

<a href="carro.php?$_SESSION['carro']+$_SESSION['zapatillas']" >Zapatillas


Rebook (40 euros)</a><br>
<a href="carro.php">Sudadera Domyos (15 euros)</a><br>
<a href="carro.php">Pala de pdel Vairo (50 euros)</a><br>
<a href="carro.php">Pelota de baloncesto Molten (20 euros)</a><br>
<a href="carro.php?unset($_SESSION['carro'])">Vaciar carro</a>
</body>
</html>
Ejercicio 28

usuarios.txt

login.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejercicio 28</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<label for="usuario"> Usuario: </label>
<input type="text" name="usuario" id="usuario"/><br><br>

<label for="password"> Contrasea: </label>


<input type="password" id="password" name="password"/><br><br>

<input type="submit" id="enviar" name="enviar" value="Enviar" />


</form>

<?php

$_GET['usuario'] = $usuario;
$_GET['password'] = $password;

$escritura = fopen("contactos.txt","a");

$linea = $usuario.":".$password .PHP_EOL;

if ($tamano > 0){

fwrite($escritura,$linea);

}else{
fwrite($escritura,echo 'No hay ningun usuario registrado.');

fclose($escritura);

header('Location: index.php');

?>

</body>
</html>

pag1.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejercicio 28</title>
<link rel="stylesheet" type="text/css" href="estilos.css" />
</head>
<body>
<header></header>
<nav>
<ul>
<li>
<a href="index.php">Index</a>
</li>

<li>
<a href="pag1.php">Pagina 1</a>
</li>

<li>
<a href="pag2.php">Pagina 2</a>
</li>

</ul>
</nav>

<main>
<h1>Pagina 1</h1>
</main>

</body>
</html>

Bases de Datos en PHP


Ejemplo
iawt6_ejercicio1.sql

index.php
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Ejercicio 2</title>
</head>
<body>
<h1>Ejercicio2 - T6.2</h1>

<?php

$bd = mysqli_connect("localhost","root",""); //Conectar al servidor (localhost,


usuari i contrasenya)
mysqli_select_db($bd, "iawt6_ejercicio1"); //Li pase la conexio que es bd i el
nom de la BD
mysqli_set_charset($bd, "utf-8");//Codificacio en que vaig a utilitzarla

//Operacions:

$consulta = "SELECT * FROM libro;";


$resultado = mysqli_query($bd, $consulta); // Execute la consulta

$totalRegistros = mysqli_num_rows($resultado); //Numero de resultats


echo "<p> $totalRegistros elementos encontrados. </p>";

/* while($fila = mysqli_fetch_assoc($resultado)){

$codigo = $fila['codigo'];
$titulo = $fila['titulo'];
$autor = $fila['autor'];

echo "$codigo : $titulo - $autor <br>";


}

while($fila = mysqli_fetch_assoc($resultado)){
$codigo = $fila[0];
$titulo = $fila[1];
$autor = $fila[2];

echo "$codigo : $titulo - $autor <br>";


}*/

while($fila = mysqli_fetch_assoc($resultado)){

?>

<div id="<?php echo $fila['codigo'];?>">


<a href="">Borrar</a>
<p> Nombre: <?php echo $fila['titulo'];?></p>
<p> Autor: <?php echo $fila['autor'];?></p>

</div>
<?php
}

mysqli_close($bd); //Tancar la conexi


?>

</body>
</html>

Comprobacin errores
Al conectar:
$db = mysqli_connect(...);
if (mysqli_connect_errno() != 0)
echo 'Error: '. mysqli_connect_error();

Despus de realizar una operacin:


mysqli_query($bd, $consulta);
if (mysqli_errno($bd) != 0){
echo 'Error: ' . mysqli_error($bd);
}

Vous aimerez peut-être aussi