Mark Fenoglio - Big Nerd Ranch Tue, 19 Oct 2021 17:47:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Simple Debugging in PEAR::DB https://bignerdranch.com/blog/simple-debugging-in-peardb/ https://bignerdranch.com/blog/simple-debugging-in-peardb/#respond Sun, 19 Feb 2006 13:26:56 +0000 https://nerdranchighq.wpengine.com/blog/simple-debugging-in-peardb/

One of the most important (and least loved) activities in a programmer's life is debugging code. When debugging PHP, there are several strategies, ranging from strategic use of print_r to elaborate systems that send debugging information to specific debug tables in a database.

In this article, we look at a simple tip for finding errors in SQL code when using PEAR::DB.

The post Simple Debugging in PEAR::DB appeared first on Big Nerd Ranch.

]]>

One of the most important (and least loved) activities in a programmer’s life is debugging code. When debugging PHP, there are several strategies, ranging from strategic use of print_r to elaborate systems that send debugging information to specific debug tables in a database.

In this article, we look at a simple tip for finding errors in SQL code when using PEAR::DB.

Debugging PEAR::DB

The PEAR modules provide a great deal of power and convenience for PHP programmers. One of the most widely used modules is DB, with its support for a ridiculous number of databases. PEAR::DB also includes some extremely helpful methods like autoPrepare() and autoExecute(). The downside to these methods is that they are (in many respects) a “black box” approach. You provide a key-value (associated) array along with the table name, insert or update constant, and predicate. What you hope to get is a new or updated record in your database.

When it doesn’t happen, there isn’t a whole lot of information (at first glance). Since the autoExecute() method constructs the SQL statement for you, you cannot simply use “echo $sql” as you might if you were constructing the SQL statements yourself.

However, the DB module also has a very simple mechanism for showing you what is happening behind the scenes.

Suppose you are updating a table in your database and the update doesn’t seem to be doing anything. Your code might look something like this:

$db->autoExecute($table, $_POST, DB_AUTOQUERY_UPDATE, "row_id=$id");

Header("Location: my_edit_page.php");

To find out why the update is not occurring, you could modify that same code to look like this:

$db->setOption('debug', true);

$my_query = $db->autoExecute($table, $_POST, DB_AUTOQUERY_UPDATE, "row_id=$id");

if (DB::isError($my_query)) {
	print $my_query->getDebugInfo();
}

// Header("Location: my_edit_page.php");

Now, when you attempt to save, the redirect will not happen and you will see both the SQL statement that PEAR::DB attempted to use as well as a message describing why it did not work.

Once you know where to look, debugging PHP is quite simple!

The post Simple Debugging in PEAR::DB appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/simple-debugging-in-peardb/feed/ 0
Uploading Files with PHP https://bignerdranch.com/blog/uploading-files-with-php/ https://bignerdranch.com/blog/uploading-files-with-php/#respond Sun, 18 Dec 2005 15:00:45 +0000 https://nerdranchighq.wpengine.com/blog/uploading-files-with-php/

Content management is a nearly universal challenge when discussing any data-driven web site. As a developer, you can create your own system or use any one of a number of sophisticated open-source or third-party packages. Many times, however, you have a simple concept in mind and you want to create your own – especially if you have very specific needs that existing solutions cannot easily accommodate. At some point, you are going to want to let users upload files. Sometimes reluctantly, but it will happen. PHP 5 handles this need very well.

The post Uploading Files with PHP appeared first on Big Nerd Ranch.

]]>

Content management is a nearly universal challenge when discussing any data-driven web site. As a developer, you can create your own system or use any one of a number of sophisticated open-source or third-party packages. Many times, however, you have a simple concept in mind and you want to create your own – especially if you have very specific needs that existing solutions cannot easily accommodate. At some point, you are going to want to let users upload files. Sometimes reluctantly, but it will happen. PHP 5 handles this need very well.

In this article, we look at a simple strategy for allowing users to upload images to your web site.

Proposed Solution

We are going to look at an example where we want to allow someone to upload images to a web site (for a soon-to-be famous website www.lookatmyawesomevacation.com). We are going to place some restrictions on file size, and permit only certain kinds of images. Making the web interface elegant and appropriate is left to the reader as homework.

There are several components necessary for file uploads to work properly:

  1. (HTML) use a multipart form

  2. (HTML) create the upload control and size field

  3. (PHP) check for errors

  4. (PHP) ensure validity of upload

  5. (PHP) upload file to web server

HTML Form

Our first step is to create a nice web page with the appropriate HTML for the file upload to work. We will call this page file_upload.html (and show what it looks like in Safari)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your Images</title>
</head>
<body>

<form method='POST' name='my_form' enctype='multipart/form-data' action='do_upload.php'>

<input type='hidden' name='MAX_FILE_SIZE' value="262144" />
Which image? <input name="upload_file" type="file" />
<br /><br />
<input type="submit" value="Send Selected Image" />

</form>

</body>
</html>

How Safari shows our HTML form

Let’s take a closer look at that code. First and foremost, your form must have enctype=’multipart/form-data’ among its attributes. In addition, this is one place you can specify a file size restriction. If you do so, the name of the field must be MAX_FILE_SIZE and its value is the number of bytes (in our case, 256K, which is 262144 bytes).

Your HTML form is not the only place where file size can be restricted. The server’s php.ini file also has a section related to file uploads. If you open php.ini in your favorite editor, and skip far enough down the file, you will see:

;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
;upload_tmp_dir =

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

As you can see, php.ini also controls whether file uploads will be allowed at all. The file size specified here is entered in megabytes (e.g., 2M represents 2 megabytes). Both the form-based limit and php-based limit generate different error messages when you act on the uploaded file.

If you aren’t sure where php.ini is located on your server, create a tiny script with this simple code:

<?php
phpinfo();
?>

When you run that script in your browser, the first block on the resulting page will have an item called “Configuration File (php.ini) Path” that will tell you where the php.ini file is located. Obviously, if you are using PHP as part of a hosting package, you may not have any control over this file at all.

PHP File Handling

Now that we have our HTML form, we need our PHP script to handle its results. We will call this script do_upload.php (whatever name we choose must match the action attribute of the <form> in our HTML page).

<?php

$err_upload = "";

$image_file = <b>$_FILES['upload_file']</b>;
$temporary_name = $image_file['tmp_name'];

if (<b>is_uploaded_file($temporary_name)</b>) {

	// get image information
	$image_metadata = <b>getimagesize($temporary_name)</b>;

	if ($image_metadata) {
		$image_width = $image_metadata[0];
		$image_height = $image_metadata[1];
		$image_type = <b>$image_metadata[2]</b>;

		$save_name = $temporary_name;

		switch ($image_type)
		{
			case IMAGETYPE_GIF:
				$save_name .= ".gif";
				break;
			case IMAGETYPE_PNG:
				$save_name .= ".png";
				break;
			default:
				$err_upload = "Sorry... we only allow gif and png images.";
				break;
		}

		if (! $err_upload) {
			if (<b>move_uploaded_file($tmp_name, "/path/to/images/$save_name")</b>) {
				// you might update a database with key information here so
				// that the image can be used later
			} else {
				$err_upload = "Sorry... something went horribly awry.";
			}
		}
	}

} else {

	// some error occurred: handle it
	switch ($image_file['error'])
	{
		case 1: // file too big (based on php.ini)
		case 2: // file too big (based on MAX_FILE_SIZE)
			$err_upload = "Sorry... image too big.";
			break;
		case 3: // file only partially uploaded
		case 4: // no file was uploaded
		case 6: // missing a temporary folder
		case 7: // failed to write to disk (only in PHP 5.1+)
			$err_upload = "Sorry... failed to upload... problem with server.";
			break;
	}
}

if ($err_upload) {
	print $err_upload;
} else {
	print "Success!!!";
}
?>

Okay, there is a lot going on here, but there are really only a few key steps in the process.

  1. We use the $_FILES superglobal array to get our file content (‘upload_file’ is the name of the file field in our HTML form).

  2. We use “if (is_uploaded_file($temporary_name))” as the safest way to test whether the upload worked or not.

  3. Since our example is considering only images, we can use “if ($image_metadata)” because it identifies the image as either an image or not (it recognizes many different types).

  4. We use “move_uploaded_file($tmp_name, “/path/to/images/$save_name”)” to put the uploaded file in our desired destination. One common mistake is when the desired directory does not have the correct file permissions so that PHP can work its magic.

  5. Everything else in that script handles various error conditions: from fundamental problems with the upload process to non-image data being uploaded to non-gif and non-png images being uploaded. PHP gives you a tremendous amount of control over the process.

This is only an introductory look at file uploads. There are many other considerations when doing this kind of work. For example, instead of uploading the file to the server, it may be desirable to have the file made part of the database that feeds your web site. Or, you may want images but may want to create thumbnails of those images and save them into the database while referencing the larger files. The possibilities are endless.

The post Uploading Files with PHP appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/uploading-files-with-php/feed/ 0
XML in PHP 5 https://bignerdranch.com/blog/xml-in-php-5/ https://bignerdranch.com/blog/xml-in-php-5/#respond Thu, 17 Nov 2005 03:02:15 +0000 https://nerdranchighq.wpengine.com/blog/xml-in-php-5/

Now that PHP 5 is becoming more and more prevalent over its predecessors, some really good books that cover PHP need revisions. Nowhere is this more true than with XML-related topics, where PHP 5 has a completely different way of working with XML -- and, in fact, the mechanisms from PHP 4 will no longer work. In this article, we'll be looking at one way to build and parse an XML tree using the new methods in PHP 5.

The post XML in PHP 5 appeared first on Big Nerd Ranch.

]]>

Now that PHP 5 is becoming more and more prevalent over its predecessors, some really good books that cover PHP need revisions. Nowhere is this more true than with XML-related topics, where PHP 5 has a completely different way of working with XML – and, in fact, the mechanisms from PHP 4 will no longer work.

In this article, we’ll be looking at one way to build and parse an XML tree using the new methods in PHP 5.

XML Review

As a (very) quick reminder about what XML is, you work with tags much like you do in HTML, but with two very important distinctions:

  1. (restriction) You must close every tag

  2. (benefit) You get to define the name of these tags in your XML document

In other words, what you are doing is creating a “tree” of XML entities where you are defining the data structure for the objects you want to manage (or allow others to manage).

By way of example, you might have the following XML file represent the teams in Major League Baseball.

<?xml version="1.0" encoding="iso-8859-1"?>
<teams>
	<team>
		<name>Atlanta Braves</name>
		<stadium>Turner Field</stadium>
		<league>National</league>
	</team>
	<team>
		<name>Chicago Cubs</name>
		<stadium>Wrigley Field</stadium>
		<league>National</league>
	</team>

	...

	<team>
		<name>Baltimore Orioles</name>
		<stadium>Camden Yards</stadium>
		<league>American</league>
	</team>

	...

</teams>

Creating XML in DOM

The general workflow for creating an XML document using DOM is (where Steps 2 and 3 are repeated to complete the XML):

  1. Create a new DOM document

  2. Create elements

  3. Append children

In our example (considering only the first two teams), the code would be:

<?php

// xml_teams_dom.php

// create the new XML document
$dom = new DOMDocument('1.0', 'iso-8859-1');

// create the root element
$list_of_teams = $dom->createElement('teams');
$dom->appendChild($list_of_teams);

// create the first team element
$team = $dom->createElement('team');
$list_of_teams->appendChild($team);

// now create all the subelements for the team
$name = $team->appendChild($dom->createElement('name'));
$name->appendChild($dom->createTextNode('Atlanta Braves'));

$stadium = $team->appendChild($dom->createElement('stadium'));
$stadium->appendChild($dom->createTextNode('Turner Field'));

$league = $team->appendChild($dom->createElement('league'));
$league->appendChild($dom->createTextNode('National'));

// create the second team element
$team = $dom->createElement('team');
$list_of_teams->appendChild($team);

// now create all the subelements for the second team
$name = $team->appendChild($dom->createElement('name'));
$name->appendChild($dom->createTextNode('Chicago Cubs'));

$stadium = $team->appendChild($dom->createElement('stadium'));
$stadium->appendChild($dom->createTextNode('Wrigley Field'));

$league = $team->appendChild($dom->createElement('league'));
$league->appendChild($dom->createTextNode('National'));

$xml_result = $dom->saveXML();

// simple mechanism to see the XML

print <<<XML_SHOW
<textarea cols='80' rows='40' name='xml_result'>$xml_result</textarea>
XML_SHOW;

?>

XML Parsing

Now that we have an XML structure, how exactly do we interrogate it for information?

The general workflow for parsing an XML document for specific elements is:

  1. Create a new DOM document

  2. Load an XML tree into the DOM document

  3. Query the new XML tree and loop through the desired elements

In our case, we might add the following code to our script:

// pull in the work we've just done
$team_xml = new DOMDocument();
$team_xml->loadXML($xml_result);

// statement block to get at the elements of the xml document
$team_list = $team_xml->getElementsByTagName('team');
foreach ($team_list AS $team) {
	foreach ($team->childNodes AS $item) {
		print $item->nodeName . " = " . $item->nodeValue . "<br />";
	}
}

This obviously only scratches the surface of using XML in PHP 5. XML is an extremely important tool in PHP (and everywhere else), particularly in the development of web services.

The post XML in PHP 5 appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/xml-in-php-5/feed/ 0