0% found this document useful (0 votes)
153 views33 pages

Codigo Ficheros PHP

The document contains code snippets from various PHP files related to an auto parts website. It includes files for displaying a freight cost table, order form, order processing, viewing orders, website front page with random images, and customer feedback form.

Uploaded by

m_montiel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views33 pages

Codigo Ficheros PHP

The document contains code snippets from various PHP files related to an auto parts website. It includes files for displaying a freight cost table, order form, order processing, viewing orders, website front page with random images, and customer feedback form.

Uploaded by

m_montiel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

CODIGO FICHEROS PHP

freight.html
<html>
<body>
<table border="0" cellpadding="3">
<tr>
<td bgcolor="#CCCCCC" align="center">Distance</td>
<td bgcolor="#CCCCCC" align="center">Cost</td>
</tr>
<tr>
<td align="right">50</td>
<td align="right">5</td>
</tr>
<tr>
<td align="right">100</td>
<td align="right">10</td>
</tr>
<tr>
<td align="right">150</td>
<td align="right">15</td>
</tr>
<tr>
<td align="right">200</td>
<td align="right">20</td>
</tr>
<tr>
<td align="right">250</td>
<td align="right">25</td>
</tr>
</table>
</body>
</html>
freight.php
<html>
<body>
<table border = 0 cellpadding = 3>
<tr>
<td bgcolor = "#CCCCCC" align = center>Distance</td>
<td bgcolor = "#CCCCCC" align = center>Cost</td>
</tr>
<?php
$distance = 50;
while ($distance <= 250 ){
echo "<tr>\n <td align = right>$distance</td>\n";
echo " <td align = right>". $distance / 10 ."</td>\n</tr>\n";
$distance += 50;
} ?>
</table>
</body>
</html>
orderform.html
<html>

<body>
<form action="processorder.php" method="post">
<table border="0">
<tr bgcolor="#cccccc">
<td width="150">Item</td>
<td width="15">Quantity</td>
</tr>
<tr>
<td>Tires</td>
<td align="center"><input type="text" name="tireqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>Oil</td>
<td align="center"><input type="text" name="oilqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>Spark Plugs</td>
<td align="center"><input type="text" name="sparkqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>How did you find Bob's?</td>
<td><select name="find">
<option value = "a">I'm a regular customer</option>
<option value = "b">TV advertising</option>
<option value = "c">Phone directory</option>
<option value = "d">Word of mouth</option>
</select> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit
Order"></td>
</tr>
</table>
</form>
</body>
</html>
processorder.php
<?php
// create short variable names
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$find = $_POST['find'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>

<h2>Order Results</h2>
<?php
echo '<p>Order processed at ';
echo date('H:i, jS F');
echo '</p>';
echo '<p>Your order is as follows: </p>';
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo 'Items ordered: '.$totalqty.'<br />';
if( $totalqty == 0) {
echo 'You did not order anything on the previous page!<br />';
}
else {
if ( $tireqty > 0 )
echo $tireqty.' tires<br />';
if ( $oilqty > 0 )
echo $oilqty.' bottles of oil<br />';
if ( $sparkqty > 0 )
echo $sparkqty.' spark plugs<br />';
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty *
SPARKPRICE;
echo 'Subtotal: $'.number_format($totalamount,2).'<br />';
$taxrate = 0.10; // local sales tax is 10%
$totalamount = $totalamount * (1 + $taxrate);
echo 'Total including tax: $'.number_format($totalamount,2).'<br />';
/*
if($find == 'a')
echo '<p>Regular customer.</p>';
elseif($find == 'b')
echo '<p>Customer referred by TV advert.</p>';
elseif($find == 'c')
echo '<p>Customer referred by phone directory.</p>';
elseif($find == 'd')
echo '<p>Customer referred by word of mouth.</p>';
else
echo '<p>We do not know how this customer found us.</p>';
*/
switch ($find){
case a:
echo '<p>Regular customer.</p>';
break;
case b:
echo '<p>Customer referred by TV advert.</p>';
break;
case c:
echo '<p>Customer referred by phone directory.</p>';
break;

case d:
echo '<p>Customer referred by word of mouth.</p>';
break;
default:
echo '<p>We do not know how this customer found us.</p>';
break;
}
?>
</body>
</html>
orderform.html
<html>
<head>
<title>Bob's Auto Parts</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Form</h2>
<form action="processorder.php" method=post>
<table border=0>
<tr bgcolor=#cccccc>
<td width=150>Item</td>
<td width=15>Quantity</td>
</tr>
<tr>
<td>Tires</td>
<td align="left"><input type="text" name="tireqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>Oil</td>
<td align="left"><input type="text" name="oilqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>Spark Plugs</td>
<td align="left"><input type="text" name="sparkqty" size="3"
maxlength="3"></td>
</tr>
<tr>
<td>Shipping Address</td>
<td align="center"><input type="text" name="address" size="40"
maxlength="40"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Submit Order"></td>
</tr>
</table>
</form>
</body>
</html>

processorder.php
<?php
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$address = $_POST['address'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
$date = date('H:i, jS F');
echo '<p>Order processed at '. $date . '</p>';
echo '<p>Your order is as follows: </p>';
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo 'Items ordered: '. $totalqty .'<br />';
if( $totalqty == 0){
echo 'You did not order anything on the previous page!<br />';
}
else {
if ( $tireqty>0 )
echo $tireqty.' tires<br />';
if ( $oilqty>0 )
echo $oilqty.' bottles of oil<br />';
if ( $sparkqty>0 )
echo $sparkqty.' spark plugs<br />';
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount = $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty *
SPARKPRICE;
$totalamount=number_format($totalamount, 2, '.', ' ');
echo '<p>Total of order is '.$totalamount.'</p>';
echo '<p>Address to ship to is '.$address.'</p>';
$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
.$sparkqty." spark plugs\t\$".$totalamount ."\t". $address."\n";
@$fp = fopen("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt", 'ab');
flock($fp, LOCK_EX);
if (!$fp) {
echo '<p><strong> Your order could not be processed at this time. '
.'Please try again later.</strong></p></body></html>';
exit;
}

fwrite($fp, $outputstring, strlen($outputstring));


flock($fp, LOCK_UN); // desbloquear
fclose($fp);
echo '<p>Order written.</p>';
?>
</body>
</html>
vieworders.php
<?php
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<html>
<head>
<title>Bob's Auto Parts - Customer Orders</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Customer Orders</h2>
<?php
if (!file_exists($DOCUMENT_ROOT/ejemplos/02/orders/orders.txt")){
echo '<p><strong>File no exists.' .'Please try again
later.</strong></p>';
exit;
}
@ $fp = fopen("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt", 'rb');
if (!$fp) {
echo '<p><strong>No orders pending.' .'Please try again
later.</strong></p>';
exit;
}
while (!feof($fp)) {
$order= fgets($fp, 999);
echo $order . '<br />';
}
$num= filesize("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt");
echo "Tamao del fichero: ". $num ." bytes.</br>";
echo 'Final position of the file pointer is '.(ftell($fp)) . '<br />';
rewind($fp);
echo 'After rewind, the position is '.(ftell($fp)) . '<br />';
fclose($fp);
?>
</body>
</html>
bobs_front_page.php
<?php
$pictures = array('tire.jpg', 'oil.jpg', 'spark_plug.jpg', 'door.jpg',
'steering_wheel.jpg',
'thermostat.jpg', 'wiper_blade.jpg', 'gasket.jpg', 'brake_pad.jpg');
shuffle($pictures);
?>
<html>
<head>
<title>Bob's Auto Parts</title>

</head>
<body>
<center>
<h1>Bob's Auto Parts</h1>
<table width = 100%>
<tr>
<?php
for ( $i = 0; $i < 3; $i++ ) {
echo '<td align="center"><img src="';
echo $pictures[$i];
echo '"width="100" height="100"></td>';
}
?>
</tr>
</table> </center>
</body>
</html>
vieworders.php
<?php
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$orders= file("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt");
$number_of_orders = count($orders);
if ($number_of_orders == 0) {
echo '<p><strong>No orders pending . Please try again
later.</strong></p>';
}
for ($i= 0; $i< $number_of_orders; $i++) {
echo $orders[$i].'<br />';
}
?>
vieworders2.php
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; ?>
<html>
<head> <title>Bob's Auto Parts - Customer Orders</title> </head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Customer Orders</h2>
<?php
// Read in the entire file. Each order becomes an element in the array
$orders= file("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt");
$number_of_orders = count($orders);
if ($number_of_orders == 0) {
echo '<p><strong>No orders pending . Please try again
later.</strong></p>';
}
echo "<table border=1>\n";
echo '<tr><th bgcolor="#CCCCFF">Order Date</th>
<th bgcolor="#CCCCFF">Tires</th>
<th bgcolor="#CCCCFF">Oil</th>
<th bgcolor="#CCCCFF">Spark Plugs</th>
<th bgcolor="#CCCCFF">Total</th>
<th bgcolor="#CCCCFF">Address</th>
<tr>';

for ($i=0; $i<$number_of_orders; $i++) {


$line = explode( "\t", $orders[$i] );
//split up each line
// keep only the number of items ordered
$line[1] = intval( $line[1] );
$line[2] = intval( $line[2] );
$line[3] = intval( $line[3] );
// output each order
echo "<tr><td>$line[0]</td>
<td align='right'>$line[1]</td>
<td align='right'>$line[2]</td>
<td align='right'>$line[3]</td>
<td align='right'>$line[4]</td>
<td>$line[5]</td>
</tr>";
}
echo '</table>';
?>
</body>
</html>
feedback.html
<html>
<head> <title>Bob's Auto Parts - Customer Feedback</title> </head>
<body>
<h1>Customer Feedback</h1>
<p>Please tell us what you think.</p>
<form method= "post" action="processfeedback.php">
Your name: <br /> <input type="text" name="name" size="40"><br />
Your email address: <br /> <input type="text" name="email"
size="40"><br />
Your feedback:<br /> <textarea name="feedback" rows="5" cols="30">
</textarea><br />
<input type="submit" value="Send feedback">
</form>
</body>
</html>
processfeedback.php
<?php
$name=$_POST['name'];
$email=$_POST['email'];
$feedback=$_POST['feedback'];
$toaddress = '[email protected]';
$subject = 'Feedback from web site';
$mailcontent = 'Customer name: ' .$name. "\n" .'Customer email: '.
$email."\n"
."Customer comments: \n".$feedback."\n";
$fromaddress = 'From: [email protected]';
mail($toaddress, $subject, $mailcontent, $fromaddress);
?>
<html>
<head>
<title>Bob's Auto Parts - Feedback Submitted</title>
</head>
<body>

<h1>Feedback submitted</h1>
<p>Your feedback has been sent.</p>
</body></html>
home.html
<html>
<head>
<title>TLA Consulting Pty Ltd</title>
<style type="text/css">
h1 {color:white; font-size:24pt; text-align:center; font-family:arial,sans-serif}
.menu {color:white; font-size:12pt; text-align:center; font-family:arial,sansserif; font-weight:bold}
td {background:black}
p {color:black; font-size:12pt; text-align:justify; font-family:arial,sans-serif}
p.foot {color:white; font-size:9pt; text-align:center; font-family:arial,sansserif; fontweight:bold}
a:link,a:visited,a:active {color:white}
</style>
</head>
<body>
<!-- page header -->
<table width="100%" cellpadding="12" cellspacing="0" border="0">
<tr bgcolor="black">
<td align="left"><img src="logo.gif" alt="TLA logo" height=70
width=70></td>
<td>
<h1>TLA Consulting</h1> </td>
<td align="right"><img src="logo.gif" alt="TLA logo" height=70
width=70></td>
</tr>
</table>
<!-- menu -->
<table width="100%" bgcolor="white" cellpadding="4" cellspacing="4">
<tr >
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Home</span></td>
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Contact</span></td>
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Services</span></td>
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Site Map</span></td>
</tr>
</table>
<!-- page content -->
<p>Welcome to the home of TLA Consulting. Please take some time to get to
know us.</p>
<p>We specialize in serving your business needs and hope to hear from you
soon.</p>
<!-- page footer -->
<table width="100%" bgcolor="black" cellpadding="12" border="0">

<tr>
<td>
<p class="foot">&copy; TLA Consulting Pty Ltd.</p>
<p class="foot">Please see our <a href="legal.php">legal information
page</a></p>
</td>
</tr>
</table>
</body>
</html>
header.inc
<html>
<head>
<title>TLA Consulting Pty Ltd</title>
<style type="text/css">
h1 {color:white; font-size:24pt; text-align:center; font-family:arial,sans-serif}
.menu {color:white; font-size:12pt; text-align:center; font-family:arial,sansserif; fontweight:bold}
td {background:black}
p {color:black; font-size:12pt; text-align:justify; font-family:arial,sans-serif}
p.foot {color:white; font-size:9pt; text-align:center; font-family:arial,sansserif; fontweight:bold}
a:link,a:visited,a:active {color:white}
</style>
</head>
<body>
<!-- page header -->
<table width="100%" cellpadding="12" cellspacing="0" border="0">
<tr bgcolor="black">
<td align="left"><img src="logo.gif" alt="TLA logo" height=70
width=70></td>
<td>
<h1>TLA Consulting</h1>
</td>
<td align="right"><img src="logo.gif" alt="TLA logo" height=70
width=70></td>
</tr>
</table>
<!-- menu -->
<table width="100%" bgcolor="white" cellpadding="4" cellspacing="4">
<tr >
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Home</span></td>
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Contact</span></td>
<td width="25%">
<img src="s-logo.gif" alt="" height=20 width=20> <span
class="menu">Services</span></td>
<td width="25%">

<img src="s-logo.gif" alt="" height=20 width=20> <span


class="menu">Site Map</span></td>
</tr>
</table>
footer.inc
<!-- page footer -->
<table width="100%" bgcolor="black" cellpadding="12" border="0">
<tr>
<td>
<p class="foot">&copy; TLA Consulting Pty Ltd.</p>
<p class="foot">Please see our <a href="legal.php">legal information
page</a></p>
</td>
</tr>
</table>
</body>
</html>
home.php
<?php require('header.inc'); ?>
<!-- page content -->
<p>Welcome to the home of TLA Consulting. Please take some time to get to
know us.</p>
<p>We specialize in serving your business needs and hope to hear from you
soon.</p>
<?php require('footer.inc'); ?>
create_table.php
<?php
function create_table($data){
echo '<table border = 1>';
reset($data); // Remember this is used to point to the beginning
$value = current($data);
while ($value) {
echo "<tr><td>$value</td></tr>\n";
$value = next($data);
}
echo '</table>';
}
$my_array = array('Line one.','Line two.','Line three.');
create_table($my_array);
?>
larger.php
<?php
function larger ($x, $y){
if (!isset($x)||!isset($y))
return false;
else if ($x>=$y)
return $x;
else
return $y;
}
$a = 1; $b = 2.5; $c = 1.9;
echo larger($a, $b).'<br />';

echo larger($c, $a).'<br />';


if(@larger($d,$a)== false)
echo "Faltan variables";
else
echo larger($d, $a).'<br />';
?>
recursion.php
<?php
function reverse_r($str) {
if (strlen($str)>0)
reverse_r(substr($str, 1));
echo substr($str, 0, 1);
return;
}
function reverse_i($str) {
for ($i=1; $i<=strlen($str); $i++)
return;
}
reverse_r('Hello');
reverse_i('Hello');

echo substr($str, -$i, 1); }

?>
var_args.php
<?php
function var_args() {
echo "Number of parameters:";
echo func_num_args(); // recoge el nmero de argumentos
echo '<br />';
$args = func_get_args();
foreach ($args as $arg)
echo $arg.'<br />';
}
var_args(1,2,3);
var_args("hello", 47.3);
?>
page.inc
<?php
class Page {
public $content;
public $title = 'TLA Consulting Pty Ltd';
public $keywords = 'TLA Consulting, Three Letter Abbreviation, some of my
best friends are
search engines';
public $buttons = array( 'Home' => 'home.php', 'Contact' =>
'contact.php',
'Services' => 'services.php', 'Site Map' => 'map.php' );
public function __set($name, $value) {
$this->$name = $value;
}
public function Display( ) {
echo "<html>\n<head>\n";

$this -> DisplayTitle();


$this -> DisplayKeywords();
$this -> DisplayStyles();
echo "</head>\n<body>\n";
$this -> DisplayHeader();
$this -> DisplayMenu($this->buttons);
echo $this->content;
$this -> DisplayFooter();
echo "</body>\n</html>\n";
}
public function DisplayTitle( ) {
echo '<title> '.$this->title.' </title>';
}
public function DisplayKeywords( ) {
echo "<meta name=\"keywords\" content=\"$this->keywords\" />";
}
public function DisplayStyles( ) {
?>
<style>
h1 {color:white; font-size:24pt; text-align:center; font-family:arial,sansserif}
.menu {color:white; font-size:12pt; text-align:center; font-family:arial,sansserif;
font-weight:bold}
td {background:black}
p {color:black; font-size:12pt; text-align:justify; font-family:arial,sans-serif}
p.foot {color:white; font-size:9pt; text-align:center; font-family:arial,sansserif;
font-weight:bold}
a:link,a:visited,a:active {color:white}
</style>
<?php
}
public function DisplayHeader( ) {
?>
<table width="100%" cellpadding ="12" cellspacing ="0" border ="0">
<tr bgcolor ="black">
<td align ="left"><img src = "logo.gif" /></td>
<td> <h1>TLA Consulting Pty Ltd</h1> </td>
<td align ="right"><img src = "logo.gif" /></td>
</tr>
</table>
<?php
}
public function DisplayMenu($buttons) {
echo "<table width='100%' bgcolor='white' cellpadding='4'
cellspacing='4'\n";
echo " <tr>\n";

$width = 100/count($buttons);
//calculate button size
while (list($name, $url) = each($buttons)) {
$this -> DisplayButton($width, $name, $url, !$this>IsURLCurrentPage($url));
}
echo " </tr>\n";
echo "</table>\n";
}
public function IsURLCurrentPage($url) {
if(strpos($_SERVER['PHP_SELF'], $url )==false) {
return false;
} else {
return true;
}
}
public function DisplayButton($width, $name, $url, $active = true) {
if ($active) {
echo "<td width ='$width%'>
<a href ='$url'>
<img src ='s-logo.gif' alt ='$name' border ='0' /></a>
<a href ='$url'><span class='menu'>$name</span></a></td>";
}
else
{
echo "<td width ='$width%'>
<img src ='side-logo.gif'>
<span class='menu'>$name</span></td>";
}
}
public function DisplayFooter() {
?>
<table width = "100%" bgcolor ="black" cellpadding ="12" border ="0">
<tr>
<td>
<p class="foot">&copy; TLA Consulting Pty Ltd.</p>
<p class="foot">Please see our <a href ="">legal information
page</a></p>
</td>
</tr>
</table>
<?php
}
}
?>
home.php
<?php
require ('page.inc');
$homepage = new Page();
$homepage->content =' <p>Welcome to the home of TLA Consulting.
Please take some time to get to know us.</p>
<p>We specialize in serving your business needs and hope to hear
from you soon.</p>';
$homepage->Display();

?>
services.php
<?php
require ('page.inc');
class ServicesPage extends Page {
private $row2buttons = array( 'Re-engineering' => 'reengineering.php',
'Standards Compliance' => 'standards.php', 'Buzzword Compliance' =>
'buzzword.php',
'Mission Statements' => 'mission.php' );
public function Display() {
echo "<html>\n<head>\n";
$this -> DisplayTitle();
$this -> DisplayKeywords();
$this -> DisplayStyles();
echo "</head>\n<body>\n";
$this -> DisplayHeader();
$this -> DisplayMenu($this->buttons);
$this -> DisplayMenu($this->row2buttons);
echo $this->content;
$this -> DisplayFooter();
echo "</body>\n</html>\n";
}
}
$services = new ServicesPage();
$services -> content ='<p>At TLA Consulting, we offer a number of services.
Perhaps the productivity of your employees would improve if we reengineered your business.
Maybe all your business needs is a fresh mission statement, or a new
batch of
buzzwords.</p>';
$services -> Display();
?>
reflection.php
<?php
require_once('page.inc');
$class = new ReflectionClass('Page');
echo '<pre>'. $class . '</pre>';
?>
iterator.php
<?php
class ObjectIterator implements Iterator {
private $obj;
private $count;
private $currentIndex;
function __construct($obj) {
$this->obj = $obj;
$this->count = count($this->obj->data);
}
function rewind() {
$this->currentIndex = 0;

}
function valid() {
return $this->currentIndex < $this->count;
}
function key() {
return $this->currentIndex;
}
function current() {
return $this->obj->data[$this->currentIndex];
}
function next() {
$this->currentIndex++;
}
}
class Object implements IteratorAggregate {
public $data = array();
function __construct($in) {
$this->data = $in;
}
function getIterator() {
return new ObjectIterator($this);
}
}
$myObject = new Object(array(2, 4, 6, 8, 10));
$myIterator = $myObject->getIterator();
for($myIterator->rewind(); $myIterator->valid(); $myIterator->next()) {
$key = $myIterator->key();
$value = $myIterator->current();
echo "$key => $value <br />";
}
?>
printable.php
<?php
class MyObject {
protected $name = 'Antonio';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo '<br/>';
echo serialize($obj);
?>
Otra versin:

<?php
class Printable{
var $prueba1= 'Hola';
var $prueba2;
var $a = array (1, 2, array ("a", "b", "c"));
public function _toString(){
return var_export($this, true);
}
}
$p= new Printable;
echo serialize($p);
echo '<br/>';
echo var_dump($p);
echo '<br/>';
echo $p->_toString();
?>

file_exception.php
?php
class fileOpenException extends Exception {
function __toString() {
return 'fileOpenException '. $this->getCode() . ': '. $this>getMessage().'<br />'.' in '
. $this->getFile(). ' on line '. $this->getLine()
. '<br />';
}
}
class fileWriteException extends Exception {
function __toString() {
return 'fileWriteException '. $this->getCode() . ': '. $this>getMessage().'<br />'.' in '
. $this->getFile(). ' on line '. $this->getLine() . '<br />';
}
}
class fileLockException extends Exception {
function __toString() {
return 'fileLockException '. $this->getCode() . ': '. $this>getMessage().'<br />'.' in '
. $this->getFile(). ' on line '. $this->getLine() . '<br />';
}
}
?>
user_defined_exception.php
<?php
class myException extends Exception {
function __toString() {
return '<table border><tr><td><strong>Exception '. $this->getCode()

. '</strong>: '. $this->getMessage().'<br />'.' in ' . $this->getFile(). ' on line


'. $this->getLine()
. '</td></tr></table><br />';
}
}
try {
throw new myException('A terrible error has occurred', 42);
}
catch (myException $m) {
echo $m;
}
?>
orderform.html
<html>
<head>
<title>Bob's Auto Parts</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Form</h2>
<form action="processorder.php" method=post>
<table border=0>
<tr bgcolor=#cccccc>
<td width=150>Item</td>
<td width=15>Quantity</td>
</tr>
<tr>
<td>Tires</td>
<td align=left><input type="text" name="tireqty" size=3
maxlength=3></td>
</tr>
<tr>
<td>Oil</td>
<td align=left><input type="text" name="oilqty" size=3
maxlength=3></td>
</tr>
<tr>
<td>Spark Plugs</td>
<td align=left><input type="text" name="sparkqty" size=3
maxlength=3></td>
</tr>
<tr>
<td>Shipping Address</td>
<td align=center><input type="text" name="address" size=40
maxlength=40></td>
</tr>
<tr>
<td colspan=2 align=center><input type=submit value="Submit
Order"></td>
</tr>
</table>
</form>

</body>
</html>
processorder.php
<?php
require_once('file_exceptions.php');
$tireqty = $_POST['tireqty'];
$oilqty = $_POST['oilqty'];
$sparkqty = $_POST['sparkqty'];
$address = $_POST['address'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<?php
$date = date('H:i, jS F');
echo '<p>Order processed at '. $date. '</p>';
echo '<p>Your order is as follows: </p>';
$totalqty = 0;
$totalqty = $tireqty + $oilqty + $sparkqty;
echo 'Items ordered: '.$totalqty.'<br />';
if( $totalqty == 0) {
echo 'You did not order anything on the previous page!<br />';
}
else {
if ( $tireqty>0 )
echo $tireqty.' tires<br />';
if ( $oilqty>0 )
echo $oilqty.' bottles of oil<br />';
if ( $sparkqty>0 )
echo $sparkqty.' spark plugs<br />';
}
$totalamount = 0.00;
define('TIREPRICE', 100);
define('OILPRICE', 10);
define('SPARKPRICE', 4);
$totalamount= $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty *
SPARKPRICE;
$totalamount= number_format($totalamount, 2, '.', ' ');
echo '<p>Total of order is '.$totalamount.'</p>';
echo '<p>Address to ship to is '.$address.'</p>';
$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
.$sparkqty." spark plugs\t\$".$totalamount ."\t". $address."\n";
// open file for appending
try {
if (!($fp = @fopen("$DOCUMENT_ROOT/ejemplos/02/orders/orders.txt",
'ab')))
throw new fileOpenException();

if (!flock($fp, LOCK_EX))
throw new fileLockException();
if (!fwrite($fp, $outputstring, strlen($outputstring)))
throw new fileWriteException();
flock($fp, LOCK_UN);
fclose($fp);
echo '<p>Order written.</p>';
}
catch (fileOpenException $foe) {
echo '<p><strong>Orders file could not be opened. '
.'Please contact our webmaster for help.</strong></p>';
}
catch (Exception $e) {
echo '<p><strong>Your order could not be processed at this time. '
.'Please try again later.</strong></p>';
}
?>
</body>
</html>
TRABAJAR CON MySQL
Abrir Simbolo del Sistema (Consola de comandos) e ir a la ubicacin de mysql:
cd xampp/mysql/bin/mysql -u root -h localhost
MariaDB [none]> update user set password= 18061962 where user=root;
MariaDB [none]> create database books;
MariaDB [none]> create user manuel@localhost identified by 18061962;
MariaDB [none]> grant all privileges on books.* to manuel identified by
18061962;
MariaDB [none]> use books;
MariaDB [books]> create table customers ( customerid int unsigned not null
auto_increment primary key, name char(50) not null, address char(100) not
null, city char(30) not null );
MariaDB [books]> create table orders ( orderid int unsigned not null
auto_increment primary key,
customerid int unsigned not null, amount float(6,2), date date not null );
MariaDB [books]> create table books ( isbn char(13) not null primary key,
author char(50),
title char(100), price float(4,2) );
MariaDB [books]> create table order_items ( orderid int unsigned not null, isbn
char(13) not null,
quantity tinyint unsigned, primary key (orderid, isbn) );
MariaDB [books]> alter table order_items add foreign key (orderid) references
orders (orderid);
MariaDB [books]> create table book_reviews ( isbn char(13) not null primary
key,
review text);
MariaDB [books]> show databases;
MariaDB [books]> show tables;
MariaDB [books]> describe customers;
MariaDB [books]> source C:\xampp\htdocs\ejemplos\10\book_insert.sql
insert into customers values
(NULL, "Julie Smith", "25 Oak Street", "Airport West"),
(NULL, "Alan Wong", "1/47 Haines Avenue", "Box Hill"),
(NULL, "Michelle Arthur", "357 North Road", "Yarraville");

insert into orders values


(NULL, 3, 69.98, "2000-04-02"),
(NULL, 1, 49.99, "2000-04-15"),
(NULL, 2, 74.98, "2000-04-19"),
(NULL, 3, 24.99, "2000-05-01");
insert into books values
("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers",
34.99),
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Teach Yourself GIMP in 24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System
Administration Unleashed", 49.99);
insert into order_items values
(1, "0-672-31697-8", 2),
(2, "0-672-31769-9", 1),
(3, "0-672-31769-9", 1),
(3, "0-672-31509-2", 1),
(4, "0-672-31745-1", 3);
insert into book_reviews values
("0-672-31697-8", "Morgan's book is clearly written and goes well beyond
most of the basic Java books out there.");
MariaDB [books]> load data infile C:/xampp/htdocs/ejemplos/13/customers.txt
into table customers; // carga registros en tabla procedente de un fichero de
texto con campos tabulados.
MariaDB [books]> alter table customers auto_increment= 10; // coloca posicin
MariaDB [books]> SELECT table_schema, table_name, engine FROM
information_schema.tables where table_schema= customers order by
table_schema, table_name, engine;
MariaDB [books]> SELECT table_schema, table_name, table_type, table_rows,
engine FROM information_schema.tables WHERE table_schema=books;
MariaDB [books]> ALTER orders TYPE=MyISAM; // para cambiar motor de
almacenamiento

search.html
<html>
<head>
<title>Book-O-Rama Catalog Search</title>
</head>
<body>
<h1>Book-O-Rama Catalog Search</h1>
<form action="results.php" method="post">
Choose Search Type:<br />
<select name="searchtype">
<option value="author">Author</option>
<option value="title">Title</option>
<option value="isbn">ISBN</option>
</select> <br />
Enter Search Term:<br />
<input name="searchterm" type="text"> <br />
<input type="submit" value="Search">

</form>
</body>
</html>
results.php
<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()) {
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
@ $db = new mysqli('localhost', 'manuel', '18061962', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from books where ".$searchtype." like '%".
$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of books found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo '<p><strong>'.($i+1).'. Title: ';
echo htmlspecialchars(stripslashes($row['title']));
echo '</strong><br />Author: ';
echo stripslashes($row['author']);
echo '<br />ISBN: ';
echo stripslashes($row['isbn']);
echo '<br />Price: ';
echo stripslashes($row['price']);
echo '</p>';
}
$result->free(); // tambin: mysqli_free_result($result)
$db->close();
// mysqli_close($db)
?>
</body>
</html>
newbook.html
<html>
<head>

<title>Book-O-Rama - New Book Entry</title>


</head>
<body>
<h1>Book-O-Rama - New Book Entry</h1>
<form action="insert_book.php" method="post">
<table border="0">
<tr>
<td>ISBN</td>
<td><input type="text" name="isbn" maxlength="13" size="13"></td>
</tr>
<tr>
<td>Author</td>
<td> <input type="text" name="author" maxlength="30"
size="30"></td>
</tr>
<tr>
<td>Title</td>
<td> <input type="text" name="title" maxlength="60"
size="30"></td>
</tr>
<tr>
<td>Price $</td>
<td><input type="text" name="price" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>
insert_book.php
<html>
<head>
<title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?php
// create short variable names
$isbn=$_POST['isbn'];
$author=$_POST['author'];
$title=$_POST['title'];
$price=$_POST['price'];
if (!$isbn || !$author || !$title || !$price) {
echo 'You have not entered all the required details.<br />'
.'Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()) {
$isbn = addslashes($isbn);
$author = addslashes($author);

$title = addslashes($title);
$price = doubleval($price);
}
@ $db = new mysqli('localhost', 'manuel', '18061962', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "insert into books values ('".$isbn."', '".$author."', '".$title."', '".
$price."')";
$result = $db->query($query);
if ($result)
echo $db->affected_rows.' book inserted into database.';
$db->close();
?>
</body>
</html>
search_generic.html
<html>
<head>
<title>Book-O-Rama Catalog Search</title>
</head>
<body>
<h1>Book-O-Rama Catalog Search</h1>
<form action="results_generic.php" method="post">
Choose Search Type:<br />
<select name="searchtype">
<option value="author">Author
<option value="title">Title
<option value="isbn">ISBN
</select> <br />
Enter Search Term:<br />
<input name="searchterm" type=text> <br />
<input type=submit value="Search">
</form>
</body>
</html>

results_generic.php
<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm){

echo 'You have not entered search details. Please go back and try
again.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
// set up for using PEAR DB
require_once('DB.php');
$user = 'manuel';
$pass = '18061962';
$host = 'localhost';
$db_name = 'books';
// set up universal connection string or DSN
$dsn = "mysqli://$user:$pass@$host/$db_name";
// connect to database
$db = &DB::connect($dsn);
// check if connection worked
if (DB::isError($db)){
echo $db->getMessage();
exit;
}
// perform query
$query = "select * from books where ".$searchtype." like '%".
$searchterm."%'";
$result = $db->query($query);
// check that result was ok
if (DB::isError($result)){
echo $db->getMessage();
exit;
}
// get number of returned rows
$num_results = $result->numRows();
// display each returned row
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetchRow(DB_FETCHMODE_ASSOC);
echo '<p><strong>'.($i+1).'. Title: ';
echo htmlspecialchars(stripslashes($row['title']));
echo '</strong><br />Author: ';
echo stripslashes($row['author']);
echo '<br />ISBN: ';
echo stripslashes($row['isbn']);
echo '<br />Price: ';
echo stripslashes($row['price']);
echo '</p>';
}
// disconnect from database
$db->disconnect();
?>
</body>
</html>
basic_function.sql

# Basic syntax to create a function


delimiter //
create function add_tax (price float) returns float
return price*1.1;
//
delimiter ;
basic_function_with_variables.sql
# Basic syntax to create a function
delimiter //
create function add_tax (price float) returns float
begin
declare tax float default 0.10;
return price*(1+tax);
end
//
delimiter ;
basic_stored_procedure.sql
# Basic stored procedure example
delimiter //
create procedure total_orders (out total float)
begin
select sum(amount) into total from orders;
end
//
delimiter ;
control_structures_cursors.sql
# Procedure to find the orderid with the largest amount
# could be done with max, but just to illustrate stored procedure principles
delimiter //
create procedure largest_order(out largest_id int)
begin
declare this_id int;
declare this_amount float;
declare l_amount float default 0.0;
declare l_id int;
declare done int default 0;
declare continue handler for sqlstate '02000' set done = 1;
declare c1 cursor for select orderid, amount from orders;
open c1;
repeat
fetch c1 into this_id, this_amount;
if not done then
if this_amount > l_amount then
set l_amount=this_amount;
set l_id=this_id;
end if;
end if;
until done end repeat;
close c1;
set largest_id=l_id;
end

//
delimiter ;
secret.php
<?php
@ $name = $_POST['name'];
@ $password = $_POST['password'];
if(empty($name)||empty($password)) {
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.
<form method="post" action="secret.php">
<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php
}
else if($name=='user'&&$password=='pass') {
// visitor's name and password combination are correct
echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
}
else {
// visitor's name and password combination are not correct
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
?>
secretdb.php
<?php
$name = $_POST['name'];
$password = $_POST['password'];
if(!isset($_POST['name'])&&!isset($_POST['password'])) {
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.

<form method="post" action="secretdb.php">


<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php
}
else {
// connect to mysql
$mysql = mysqli_connect( 'localhost', 'webauth', 'passw' );
if(!$mysql) {
echo 'Cannot connect to database.';
exit;
}
// select the appropriate database
$selected = mysqli_select_db( $mysql, 'auth' );
if(!$selected) {
echo 'Cannot select database.';
exit;
}
// query the database to see if there is a record which matches
$query = "select count(*) from authorised_users where name = '$name' and
password = '$password'";
$result = mysqli_query( $mysql, $query );
if(!$result) {
echo 'Cannot run query.';
exit;
}
$row = mysqli_fetch_row( $result );
$count = $row[0];
if ( $count > 0 ) {
// visitor's name and password combination are correct
echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
}
else {
// visitor's name and password combination are not correct
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}

}
?>
createauthdb.sql
create database auth;
use auth;
create table authorised_users ( name varchar(20), password varchar(40),
primary key (name) );
insert into authorised_users values ( 'username', 'password' );
insert into authorised_users values ( 'testuser', sha1('password') );
grant select on auth.* to 'webauth' identified by 'passw';
flush privileges;
MariaDB> source C:/xampp/htdocs/ejemplos/16/createauthdb.sql;
http.php
<?php
// if we are using IIS, we need to set $PHP_AUTH_USER and $PHP_AUTH_PW
if (substr($SERVER_SOFTWARE, 0, 9) == 'Microsoft' && !
isset($PHP_AUTH_USER) &&
!isset($PHP_AUTH_PW) && substr($HTTP_AUTHORIZATION, 0, 6) == 'Basic ' )
{
list($PHP_AUTH_USER, $PHP_AUTH_PW) =
explode(':', base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}
// Replace this if statement with a database query or similar
if ($PHP_AUTH_USER != 'user' || $PHP_AUTH_PW != 'pass'){
// visitor has not yet given details, or their name and password combination
are not correct
header('WWW-Authenticate: Basic realm="Realm-Name"');
if (substr($SERVER_SOFTWARE, 0, 9) == 'Microsoft')
header('Status: 401 Unauthorized');
else
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
else{ // visitor has provided correct details
echo '<h1>Here it is!</h1>';
echo '<p>I bet you are glad you can see this secret page.</p>';
}
?>
private_mail.php
<html>
<body>
<h1>Send Me Private Mail</h1>
<?php
// you might need to change this line, if you do not use
// the default ports, 80 for normal traffic and 443 for SSL
if($_SERVER['SERVER_PORT']!=443)
echo '<p><font color = red>WARNING: you have not connected to this
page using SSL.
Your message could be read by others.</font></p>';
?>

<form method = post action = "send_private_mail.php"><br>


Your email address:<br><input type = text name = from size = 38><br>
Subject:<br><input type = text name = title size = 38><br>
Your message:<br><textarea name = body cols = 30 rows =
10></textarea><br>
<input type = submit value = "Send!">
</form>
</body>
</html>
send_private_mail.php
<?php
$from = $_POST['from'];
$title = $_POST['title'];
$body = $_POST['body'];
$to_email = 'luke@localhost';
// Tell gpg where to find the key ring. On this system, user nobody's home
directory is /tmp/
putenv('GNUPGHOME=/tmp/.gnupg');
$infile = tempnam('', 'pgp');
//create a unique file name
$outfile = $infile.'.asc';
//write the user's text to the file
$fp = fopen($infile, 'w');
fwrite($fp, $body);
fclose($fp);
//set up our command
$command = "/usr/local/bin/gpg -a \\
--recipient 'Luke Welling <[email protected]>' \\
--encrypt -o $outfile $infile";
system($command, $result); // execute our gpg command
unlink($infile);
//delete the unencrypted temp file
if($result==0) {
$fp = fopen($outfile, 'r');
if(!$fp||filesize ($outfile)==0) {
$result = -1;
}
else {
$contents = fread ($fp, filesize ($outfile)); //read the encrypted file
unlink($outfile);
//delete the encrypted temp file
mail($to_email, $title, $contents, "From: $from\n");
echo '<h1>Message Sent</h1>
<p>Your message was encrypted and sent.Thank you.</p>';
}
}
if($result!=0) {
echo '<h1>Error:</h1> <p>Your message could not be encrypted, so has
not been sent.
<p>Sorry.';
}
?>
upload.html
<html>
<head>

<title>Administration - upload new files</title>


</head>
<body>
<h1>Upload new news files</h1>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Upload this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
</body>
</html>
upload.php
<html>
<head>
<title>Uploading...</title>
</head>
<body>
<h1>Uploading file...</h1>
<?php
if ($_FILES['userfile']['error'] > 0) {
echo 'Problem: ';
switch ($_FILES['userfile']['error']) {
case 1: echo 'File exceeded upload_max_filesize'; break;
case 2: echo 'File exceeded max_file_size'; break;
case 3: echo 'File only partially uploaded'; break;
case 4: echo 'No file uploaded'; break;
}
exit;
}
// Does the file have the right MIME type?
if ($_FILES['userfile']['type'] != 'text/plain') {
echo 'Problem: file is not plain text';
exit;
}
$upfile = '/uploads/'.$_FILES['userfile']['name'];
// put the file where we'd
like it
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile)) {
echo 'Problem: Could not move file to destination directory';
exit;
}
}
else {
echo 'Problem: Possible file upload attack. Filename: ';
echo $_FILES['userfile']['name'];
exit;
}
echo 'File uploaded successfully<br><br>';
// reformat the file contents
$fp = fopen($upfile, 'r');
$contents = fread ($fp, filesize ($upfile));
fclose ($fp);
$contents = strip_tags($contents);

$fp = fopen($upfile, 'w');


fwrite($fp, $contents);
fclose($fp);
// show what was uploaded
echo 'Preview of uploaded file contents:<br><hr>';
echo $contents;
echo '<br><hr>';
?>
</body>
</html>
progrex.php
<?php
chdir('/uploads/');
///// exec version
echo '<pre>';
// unix
exec('ls -la', $result);
// windows
// exec('dir', $result);
foreach ($result as $line)
echo "$line\n";
echo '</pre>';
echo '<br><hr><br>';
///// passthru version
echo '<pre>';
// unix
passthru('ls -la');
// windows
// passthru('dir');
echo '</pre>';
echo '<br><hr><br>';
///// system version
echo '<pre>';
// unix
$result = system('ls -la');
// windows
// $result = system('dir');
echo '</pre>';
echo '<br><hr><br>';
/////backticks version
echo '<pre>';
// unix
$result = `ls -al`;
// windows
// $result = `dir`;
echo $result;
echo '</pre>';
?>

You might also like