Web
PREVIOUS
NEXT
Basic JSP scripting elements
JavaServer Pages (JPSs) offer a number of ways to inject Java code into the Servlet code generated when a JSP is compiled.Scriptlet code elements put the included Java code into the _jspService method. The included code needs to be complete java code (remember the trailing semicolons):
exciting HTML code
<% String important = new String("Very important programmer"); %>
more HTML code
Expressions are evaluated and placed into out.print() methods to be written to the output stream. The code included is an expression, not a complete Java statement, so leave off the trailing semicolon:
HTML tags
<%= important %>
HTML tags
<%= new java.util.Date() %>
Declaration elements insert the enclosed code into the body of the servlet code allowing the declaration of variables or methods:
HTML stuff
<%! private int counter = 0; %>... Read More
JSP basics: import a Java class for use in a JSP
Importing Java classes enables the use of that class without using the fully qualified class name. Java classes can also be imported into JSPs with page directives.To import the Java class java.util.Calendar for use in a JSP, use one of the following:
<%@page import="java.util.Calendar"%>
<jsp:directive.page import="java.util.Calendar"/>... Read More
JSP basics: include directive to read content at compile time
JSPs are compiled entities. Two include techniques read the included content before and after compilation. This recipe describes the compiled include directive.When including a file header.jsp with the following syntax:
<%@ include file="header.jsp" %>
the contents of header.jsp are read into the JSP before it is compiled. Subsequent changes to the header.jsp file will not be included in the JSP until the JSP is recompiled.... Read More
JSP basics: include dynamic content at runtime
This method of including content reads the file at run-time after the JSP has been compiled. Changes to the included file are seen immediately and do not require recompilation of the JSP.To include the file footer.jsp at runtime, use the following syntax:
<jsp:include page="footer.jsp" />... Read More
PHP: Create a File on your Server
Create an empty file on the server that can be written to.The handle is the file to be written to, and the filename is of course the name of the file being created. Using these simple commands you can create and add text to your file.
<?php
$filename = 'test.txt';
$Content = "Add this to the file\r\n";
echo "open";
$handle = fopen($filename, 'x+');
echo " write";
fwrite($handle, $Content);
echo " close";
fclose($handle);
/*
if($handle = fopen($filename, 'a')){
if(is_writable($filename){
if(fwrite($handle, $content) === FALSE){
echo "Cannot write to file $filename";
exit;
}
echo "The file $filename was created and written successfully!";
fclose... Read More
PHP: Generate Dynamic Images from Text
How to create images from text dynamically (quote generator)Here is a piece of code i have used in the past. It uses a text file on the server, named quote.txt, but you could link it to any sort of inuput.
I have read many tutorials which claim to do the same, but most do not work, this WILL work, a test out link is provided, and this is the exact code used.
<?php
Header ("Content-type: image/gif");
$textfile = "quote.txt";
$quotes = array();
if(file_exists($textfile)){
$quotes = file($textfile);
srand ((float) microtime() * 10000000);
$string = '-'.$quotes[array_rand($quotes)];
$string = substr($string,0,strlen($string)-2);
}
else{
$string = "No 'Quote' available at this time.";
}
$font = 2;
$width = ImageFontWidth($font... Read More
PHP: Upload Files to the server
With PHP, it is simple to upload any file to your server.
uploader.php
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}?>
The form used to apply this uploading:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="1000" />
Upload File: <input name="uploadedfile" type="file" /> <br />
<input type="submit"... Read More
PHP: Password Protect Your pages.
A simple PHP implementation which will prevent unwanted access to certain pages.Simply place your page inside a large php if statement:
<?php
if($_POST['password'] == 'Any_Password_You_Like'){
?>
<!--html code for page goes here -->
<?php
} else {
?>
<script language=javascript>
window.open("http://www.yoursite.com/default.htm");
</script>
<?php
}
?>
The code is translated server side, will not reveal your password, and will generate either the page protected, or apply the else, which re-directs to a default page. The default segment could also be written in php and simply echo text to the screen.
Questions/Comments: william_a_wilson@hotmail.com
-William. (marvin_gohan)... Read More
Solve PHP error: Cannot modify header information - headers already sent
This error message is commonly seen by programmers starting to use PHP. Understanding why this error occurs will help find the solution.PHP handles lots of the work of generating web pages for you, without you even having to ask. A web page is composed of two parts, the header and the body.
The header is generally stuff that you don't need to worry about, is generated automatically, and contains information about the page, the server, related cookies, and so on. The header information is important, but it is not typically seen by the user. Here are some examples:
Date: Mon, 10 Jul 2006 18:51:59 GMT
Server: Apache/2.2.0 (Unix) mod_ssl/2.2.0 OpenSSL/0.9.7g
Content-Encoding: gzip
Content-Type: text/html
Sometimes programmers want to change some of the header values. For example, if the PHP if generating XML output, the Content-Type should be changed to reflect this. Another common example is in redirecting the user's browser to a different web page using th... Read More
PHP: Rename or move a file on the server
Working with server-side files with PHP adds a great deal of flexibility to some applications. A common scenario when working with files involves creating a temporary file through uploading or other means and then renaming this file to a permanent location. This recipe describes changing the name of an existing file using the PHP function rename(). The syntax for the PHP rename function is consistent with that of the UNIX mv function, which always makes things more comfortable. The general syntax is:
rename('/path1/old_filename', '/path2/new_filename');
The rename function returns true if the rename was successful, and false otherwise.
Just like with the unlink function which deletes files, the rename function most likely fails because of file permissions. To rename a file, the directory containing it must be writable by the user trying to rename it. The file's permissions (and ownership) are irrelevant.... Read More
PHP syntax: sort an associative array by index keys
To sort an associative array by index values (or keys), use ksort.
ksort($capitals);
An optional parameter (sort_flags) can be passed to ksort to alter the way that it sorts the array. The following code will sort an associative array numerically by index.
ksort($ar, SORT_NUMERIC);
Without this option, the index values '15, 2, 1' would be sorted '1, 15, 2' and with the SORT_NUMERIC option, the values would be sorted 1, 2, 15.... Read More
PHP: Set or create a simple browser cookie with setcookie
Web applications overcome the lack of session support in the HTTP protocol primarily through the use of cookies. Transparent to the user and simple for the web developer, cookies provide the foundation of keeping up with who a web user is, where they've been, and what they had for lunch. Well, who and where, anyway.The built-in PHP function setcookie() creates or updates a cookie name/value pair in the user's browser. A cookie contains information sent by a web server to a user's browser. Whenever a web page is accessed at that server that meets the requirements, cookies associated with that server (that haven't expired) are sent back without modification to the server.
The basic cookie consists of a name and a value. For example, a cookie with name 'user' can be set to the user's username, possibly encoded for security. To set the cookie user with the value 'qmchenry' use this command:
setcookie('user','qmchenry');
This cookie has a default expiration time of 0 which means it ... Read More
PHP: Read a browser cookie value
Once your web application has set a cookie in a user's browser, it is a simple matter to retrieve that value in subsequent page requests. This recipe describes reading a value from a cookie in PHP.After a cookie with a name of 'user' has been set in a previous page, the value can be accessed with the global array $_COOKIE like this:
$user = $_COOKIE['user'];
Since this is a normal array, anything you can do to an array like iterate through it one value at a time. For debugging purposes, it is often useful to use this quick trick to see the whole contents of an array:
print_r($_COOKIE);... Read More
PHP syntax: iterate over an associative array
An associative array stores an arbitrary index in addition to the values. This is useful for storing configuration information such as in the $_SERVER array.An individual element of this array can be retrieved with:
$_SERVER['SITE_HTMLROOT']
To loop through all of the elements in $_SERVER and display the values and their corresponding indexes:
foreach ( $_SERVER as $ind=>$val )
echo "$ind : $val <br />";... Read More
PHP syntax: sort an associative array by value with asort
To sort an associative array by the array values, use asort.
asort($capitals);
An optional parameter (sort_flags) can be passed to asort to alter the way that it sorts the array. The following code will sort an associative array numerically by array value.
asort($ar, SORT_NUMERIC);
Without this option, the index values '15, 2, 1' would be sorted '1, 15, 2' and with the SORT_NUMERIC option, the values would be sorted 1, 2, 15.... Read More
PHP syntax: comments
PHP allows three forms of comments all of which may seem familiar to programmers of other languages.
/* comment block
everything within the slash-asterisk
pairs is commented */
Two inline comment styles cause everything following to be ignored:
$var++; // increment var
$var=2; # another comment
Comments don't work when they are in quotes (otherwise we couldn't use a # in the output of an echo statement).... Read More
PHP syntax: create an associative array
An associative array can use non-numeric index values and are useful because they can be iterated over sequentially and values can be extracted individually by index. Database select results can be returned as associative arrays in which the column names become indicies.The following code creates an associative array of the first few US states and their capitals. The state name is the index and the capital is the value.
$capitals=array("Alabama"=>"Montgomery",
"Alaska"=>"Juneau",
"Arizona"=>"Phoenix",
"Arkansas"=>"Little Rock",
"California"=>"Sacramento",
"Colorado"=>"Denver&q... Read More
PHP: determine the directory path of the server root
It is sometimes necessary to refer to files in the host filesystem explicitly. By retrieving this information dynamically instead of hard coding it, moving the code from one server or hosting company to another is much simpler.The fully qualified path of the directory containing the root of the web documents is:
$_SERVER["SITE_HTMLROOT"]
To assign the fully qualified path of images/sadie.gif to the variable $pic:
$var = $_SERVER["SITE_HTMLROOT"].'/images/sadie.gif';... Read More
PHP syntax: for loop basics
The for loop allows iteration a fixed number of times.
The basic for loop syntax is:
for (initialization; condition; incrementor) {
code;
}
The initialization defines the loop variable and its initial value (such as $i=1). The loop will continue to iterate while the conditional expression evaluates as true (like $i<10). Each time the loop is executed, the incrementor code is exectued (the code $i++ would increment the loop variable $i by one; $i=$i*2 would double the loop variable $i each iteration).
Putting these together in a simple example,
for ($i=1; $i<=10; $i+=2) {
echo "$i ";
}
This code would generate the output "1 3 5 7 9" since the variable $i starts at 1 and increments by two each loop until it is no longer less than or equal to 10.... Read More
PHP conditional syntax: using switch and case statements
The switch/case statement offers similar functionality to the if/elseif statement, although it offers a more elegant solution and has capabilities beyond the if/elseif alternative.A switch/case statement allows multiple comparisons of a varaible. For example, the if statement
if ($var == 1) {
echo "One";
} elseif ($var == 1) {
echo "Two";
} else {
echo "Other";
}
is identical to the switch/case statement:
switch ($var) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
default:
echo "Other";
}
In this example, if $var is equal to 1, the first case statement will be true and the associated code (ech... Read More