Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, March 15, 2009

PHP Arrays

Here are some of the useful facts and functions about arrays in PHP. Content of this post is summarized from Programming PHP by Kevin Tatroe and Rasmus Lerdorf. You can find the online version of this chapter here.

Indexed Vs Associative Arrays
PHP allows you to declare 2 kinds of array: Indexed and Associative. An indexed array means that the elements in the array are "indexed" or referred to by position in the array. To refer to the i-th element in the array, you simply call $arr[i-1](assuming $arr is the array name).

Elements in an associative array are key-value pairs. The keys are unique, so you cannot have two elements with the same key. An example of an associative array would be {'Gasket'=>15.29,'Wheel'=>75.25,'Tire'=>50.00}. To find out the "value" of Gasket, we use $arr['Gasket'].

Define Arrays

$addresses = array( );

Constructs an empty array

$addresses = array('spam@cyberpromo.net', 'abuse@example.com');

Initializes an indexed array

$price = array(
'Gasket' => 15.29,
'Wheel' => 75.25,
'Tire' => 50.00);

Initializes an associative array

Append Values to the End of Array
$family = array('Fred', 'Wilma');
$family[] = 'Pebbles'; // $family[2] is 'Pebbles'
Note that appending like this to an associative array might not yield the desired result.
$person = array('name' => 'Fred');
$person[] = 'Wilma'; // $person[0] is now 'Wilma'

Find Array Length
Use sizeof($arr)or count($arr). This works for both indexed and associative arrays.

Chapter 5 (Arrays) of the Programming PHP book offers an extensive range of array manipulation functions. You may want to check it out.

Thursday, March 12, 2009

PHP - File Upload

Want to create something like this?
Choose a file to upload:

PHP Solution: (Source: http://www.tizag.com/phpT/fileupload.php)

What to include in your HTML Form:

<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

Points to note:
1) The form type must be "multipart/form-data" in order for the form to process files.
2) MAX_FILE_SIZE attribute determines the maximum file size that can be uploaded.
3) Upon clicking "Upload File" button, data will be posted to the server and uploader.php will handle the processing.

What to include in uploader.php (PHP file that does the "uploading"):

$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
echo "Successful upload!";

else echo "There was an error uploading the file, please try again!";

Points to note:
1) $target_path is the value of where you want to store the uploaded file.
2) $_FILES['uploadedfile'] = file that was posted using the form and has the name 'uploadedfile'.
3) $_FILES['uploadedfile']['name'] = original path of the user uploaded file.
4) $_FILES['uploadedfile']['tmp_name'] = path to the temporary file that resides in the server.
5) move_uploaded_file function moves the uploaded file from its temporary position to the target path.

Important!
You might want to add more conditions, checks and/or validations before allowing visitors to upload files onto your server. This is to prevent your server from being filled with junk and thus compromising your server's security.

Pop-up window upon submitting PHP Form

Context:
Suppose you have a form with 2 different buttons :
1) "Save Post" - on click, processes the data in the form, refreshes the current page (but displays an empty form).
2) "View All Posts" - on click, processes the data in the form, opens a pop-up window, gathers information based on the posted form data from the main window.Currently we are concerned with button (2).

PHP Code:
<form name="mainForm" action="" method="post">
<input name="email">
<input type="password" name="password">
<input name="mypost">
<input type="submit" name="button1" value="Save Post">
<button type="button" onClick="return viewTempAds()">View All</button>
</form>

Javascript Code:
function viewAllPosts() {
document.forms['mainForm'].action="viewAllPosts.php";
document.forms['mainForm'].target="popup";
document.forms['mainForm'].onSubmit="window.open('','popup','menubar=no,width=600')";
document.forms['mainForm'].submit();
}

Explanation:

Both buttons 1 and 2 require the form to carry out different actions after submitting. As such, we can dynamically change the value of the form action by using Javascript. We set the value of the action value to the desired page that we wish to display in the pop-up, and we set the form value of onSubmit to open a new window. We are also submitting the form remotely in the Javascript function.