sábado, 20 de diciembre de 2025

try catch finally

<?php


function rankUser($age) {

    $rank = null;

    $status = null;


    try {

        if ($age >= 18 && $age <= 65) {

            $status = "allowed";


            if ($age < 45) {

                $rank = "Rookie";

            } else {

                $rank = "Veteran";

            }


        } else {

            $status = "denied";

            throw new Exception("Age must be between 18 and 65\n");

        }


    } catch (Exception $e) {

        echo 'Caught exception: ' . $e->getMessage() . "\n";

    } finally {

        if ($rank) {

            echo "User status $status, and Rank $rank";

        } else {

            echo "Sorry, your status is $status. You don't meet age requirements.";

        }

    }

}


rankUser(13);


?>


viernes, 12 de diciembre de 2025

Global variables insdide and outside a function

 <?php

$somevar = 15;

function addit() {

 GLOBAL $somevar;

 $somevar++;

 print "Somevar is $somevar";

}

addit();


?>



<?php

$somevar = 15;

function addit() {

 $GLOBALS["somevar"]++;

}

addit();

print "Somevar is ".$somevar;


?>

Static variables

 <?php

function keep_track() {

 STATIC $count = 0;

 $count++;

 print $count;

 print "<br>";

}

keep_track();

keep_track();

keep_track();

?>

Error reporting

<?php

// -------------------------------

// PHP Error Reporting Example

// -------------------------------


// Report all errors except user warnings and notices

error_reporting(E_ALL & ~E_USER_WARNING & ~E_USER_NOTICE);


// Display errors on screen (for development)

ini_set('display_errors', 1);


// Add a prefix to each error message

ini_set('error_prepend_string', '<strong>Error:</strong> ');


// Example errors

echo $undefined_variable;                 // Notice (ignored)

trigger_error("This is a warning", E_USER_WARNING);  // User warning (ignored)

trigger_error("This is an error", E_USER_ERROR);     // User error (shown with prefix)

?>

jueves, 4 de diciembre de 2025

 $options = array(

    CURLOPT_URL => 'http://www.example.com/',

    CURLOPT_RETURNTRANSFER => true,  // boolean

    CURLOPT_HEADER => false,         // boolean

    CURLOPT_USERAGENT => ''          // empty string, will be filtered

);


// Filter only non-empty strings

$options = array_filter($options, fn($v) => gettype($v) === 'string' && strlen($v) > 0);


$ch = curl_init();

foreach($options as $opt => $val){

    curl_setopt($ch, $opt, $val);

}


$response = curl_exec($ch);

curl_close($ch);


curl

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false)
{
echo
'Curl error: ' . curl_error($ch);
}
else
{
echo
'Operation completed without any errors';

}


//echo $error =( curl_errno($ch)>0)?curl_error($ch).", error code :  ".curl_errno($ch):"All good";




?>