Iván Chillón
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # PRO - Recuperación Programación Pendientes curso 2020-21 ## La prueba * Esta prueba está disponible en la siguiente URL: [https://tinyurl.com/pro-pte-2021](https://tinyurl.com/pro-pte-2021) * Dispones de **3 sesiones de clase** para realizar la prueba. * Para la realización de la prueba solo podrás usar como material de consulta los contenidos de la siguiente página: [https://www.w3schools.com/php/](https://www.w3schools.com/php/) * Para superar la prueba se ha de obtener, al menos, un **6**. * Los puntos por actividad son: * A1 (3 ptos) * `obtener_precio()` - **0,5 pto** * `total_compra()` - **1 pto** * `mostrar_compra()` - **1,5 pto** * A2 (3 ptos) * A3 (3 ptos) * A4 (1 pto) ## Entrega comprime todos los archivos resultantes en cada una de las actividades en un fichero `pro_ptes_apellidos_nombre.zip` y remítelo por correo a `ichigar@canariaseducacion.es` ## Actividades Crea un archivo **a1.php** e inserta el siguiente contenido: ```php <?php function obtener_precio($catalogo, $producto){ # completar función } function total_compra($catalogo, $carrito){ # completar función } function mostrar_compra($catalogo, $carrito){ # completar funcion } # Programa principal $catalogo = [ ["producto" => "lapiz", "precio" => 0.5], ["producto" => "boligrafo", "precio" => 1.19], ["producto" => "afilador", "precio" => 0.99], ["producto" => "goma", "precio" => 1.35], ["producto" => "rotulador", "precio" => 3.50], ["producto" => "estuche", "precio" => 7.20] ]; $carrito = [ ["producto" => "estuche", "cantidad" => 1], ["producto" => "lapiz", "cantidad" => 2], ["producto" => "rotulador", "cantidad" => 3] ]; $p_goma = obtener_precio($catalogo, "goma")$ echo "<p>El precio de la goma es de $p_goma € </p>") $total = total_compra($catalogo, $carrito) echo "<p>El total de la compra es de: $total €.</p>") echo "<p>El extracto de la compra es<p>"") mostrar_compra(catalogo, carrito) ``` Teniendo en cuenta que: * La lista `catalogo` representa el catálogo de una papelería online con el nombre de los productos y su precio * La lista `carrito` almacena los productos seleccionados y su cantidad por un usuario que ha accedido a la tienda online. * Todos los productos del carrito existen en el catálogo. Funciones: #### `obtener_precio()` La función `obtener_precio()`a la que le pasamos el array asociativo con el catálogo y el nombre de un producto y devuelve el precio de dicho producto. #### `total_compra()` La función `total_compra()` a la que le pasamos la lista con el catálogo y la lista con el carrito de la compra y devuelve el valor total de los productos seleccionados. #### `mostrar_compra()` La función `mostrar_compra()` a la que le pasamos el catálogo y el carrito con los datos de la compra actual y muestra los detalles de la misma en una tabla html de la forma: ```htmlembedded <table border="1"> <tr> <th>Producto</th><th>cantidad</th><th>P U</th><th>P Total</th> </tr> <tr> <td>Estuche</td><td>1</td><td>7.20</td><td>7.20</td> </tr> <tr> <td>Lapiz</td><td>2</td><td>0.50</td><td>1.00</td> </tr> <tr> <td>Rotulador</td><td>3</td><td>3.50</td><td>10.50</td> </tr> <tr> <td colspan='4'>Total: 18,70€</td> </tr> </table> ``` Teniendo en cuenta que: * El nombre de los productos debe aparecer con el primer caracter en mayúscula. * El precio unitario de cada producto lo obtenemos usando la función `obtener_precio()` * El total del carrito lo calcule llamando a la función `total_compra()` Guarda el resultado en un fichero de nombre `a1.php` ## A2. Codigos postales ### Leyendo de ficheros en PHP El siguiente programa lee un archivo de nombre `fichero.txt` y muestra su contenido por pantalla: ```php <?php $stream = fopen("fichero.txt", "r"); while(($line=fgets($stream))!==false) { echo $line; } ?> ``` En un fichero de nombre `cp_gc.txt` guarda las siguientes líneas: ``` Las Palmas de Gran Canaria,35001 Santa Lucía de Tirajana,35110 Agüimes,35118 San Bartolomé de Tirajana,35120 Mogán,35120 Gáldar,35188 Telde,35200 Valsequillo de Gran Canaria,35216 Ingenio,35250 Santa Lucía de Tirajana,35280 Santa Brígida,35300 Vega de San Mateo,35320 Valleseco,35349 Artenara,35350 Tejeda,35360 Arucas,35413 Moya,35413 Firgas,35435 Santa María de Guía de Gran Canaria,35450 La Oliva,35469 La Aldea de San Nicolás,35470 Arrecife,35500 Teguise,35507 Tías,35510 Tinajo,35550 Yaiza,35570 Puerto del Rosario,35600 Antigua,35610 Tuineje,35620 Pájara,35625 Betancuria,35637 La Oliva,35650 ``` A continuación escribe un programa que cargue la información del fichero y muestre un formulario que contenga: * Una lista desplegable todas las localidades (no deben aparecer repetidas) de la provicia de Las Palmas * Un botón para enviar. Al hacer click en enviar se mostrará una página con el nombre de la localidad y su código postal Guarda todos los archivos de la actividad en un fihcero de nombre `a2.zip` ## A3. Validación de campos A partir de las siguientes clases: ```php <?php // Clase abstracta abstract class Validate { public $input; public function __construct($input) { $this->input = $input; } protected function validate_equal_length($length){ return strlen($this->input) == $length ? true : false; } protected function validate_min_length($min_length){ return strlen($this->input) > $min_length ? true : false; } protected function validate_is_numeric(){ $digits = "0123456789"; $chars = str_split($this->input); // Convierte cadena a array // Busca si alguno de los caracteres no es un dígito numérico foreach ($chars as $char){ if (! strpos($digits, $char) && $char != "0"){ return false; } } return true; } abstract public function validate(); // Se debe implementar para el caso particular de cada clase derivada } // Clase de ejemplo: ValidateCP implementa Validate para validar código postal class ValidateCP extends Validate{ private $cp_length = 5; public function validate(){ // se comprueba si no valida que la longitud sea 5 if (! $this->validate_equal_length($this->cp_length)){ return false; } // se comprueba si alguno de los caracteres no es numérico if (! $this->validate_is_numeric()){ return false; } // Si valida todos los requisitos se devuelve true return true; } } $validar_texto = new ValidateText("holayadios"); $valid = $validar_texto->validate(); echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; $validar_cp = new ValidateCP("35003"); $valid = $validar_cp->validate(); echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; ``` A partir del código anterior crea la clase `ValidateEmail` que implemente la clase abstracta `Validate` de para validar una dirección de **email**. La clase `ValidEmail` debe implementar la clase abstracta anterior y aprovechar los métodos de la misma. En caso de necesitar nuevos métodos se deben añadir a la clase `ValidEmail`; no se puede modficar la clase abastracta `Validate` Una dirección de **email** será valida si cumple las siguientes condiciones.: * Tiene una longitud mayor de 6 caracteres * Contiene una `@` y no es el primer carácter (no puede contener más de una). * Contiene al menos un punto `.` * Después del último punto debe haber 2 o más caracteres. Ejemplos de pruebas: ```php // No valida por longitud $valid_email = new ValidateEmail("a@b.a") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; // No valida por no contener @ $valid_email = new ValidateEmail("antonioexample.com") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; // No valida por contener más de una @ $valid_email = new ValidateEmail("anto@nioi@example.com") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; // No valida por no contener punto $valid_email = new ValidateEmail("antonio@examplecom") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; // No valida por no contener 2 o más caracteres después del último . $valid_email = new ValidateEmail("antonio.garcia@exampleco.m") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; // Válido $valid_email = new ValidateEmail("antonio.garcia@exampleco.com") $valid = $valid_email->validate() echo $valid ? "<p>Es válido</p>" : "<p>No es válido</p>"; ``` Guarda el resultado en un fichero de nombre `a3.php` ## A4. cc2sc A la función `cc2sc()` le pasamos un identificador en formato "camel case" y **devuelve** el identificador convertido a formato "snake case". Suponer que el identificador recibido es válido: ```php <?php function cc2sc($catalogo, $producto){ # completar función ?> ``` Ejemplos de valores de entrada y del resultado esperado: ``` nomVariable - nom_variable NomVariable - nom_variable nomVariableCompuesto - nom_variable_compuesto variable - variable ``` Guarda el resultado en un fichero de nombre `a4.php` ###### tags: `pro` `ptes` `prueba` `recuperación` `20-21`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully