In php chekboxes are referred as arrays. When ever we read the values from the checkbox all the values are retrieved as the array. From the form if we read the value of textbox or a radio button or the select box, we generally read by using the name of the tab. For example if we read the value of the textbox then we directly read as $_POST['textboxname'].
But when reading the values from the checkboxes we need to be very carefull. As the checkbox value comes in the form of array. First we need to read the array and then split the array and read the values.
Example:
<form action="test.php" method="post">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="checkbox" name="test[]" value="1">
<input type="submit" value="submit">
</form>
Code for reading the checkbox values.
$test=$_POST['test'];
$finalvalues="";
if($test!="")
{
foreach($test as $cat4)
{
if($finalvalues=="")
{
$finalvalues=$cat4;
}
else
{
$finalvalues=$finalvalues."#".$cat4;
}
}
}
Here the final values are stored in the variable $finalvalues seperated by the "#" character. here we used foreach to read the values which are selected by the user individually.
Tuesday, March 31, 2009
Read values from Checkbox in PHP
Friday, March 27, 2009
mysql_real_escape_string funciton in PHP
mysql_real_escape_string function Escapes special characters in a string for use in a SQL statement
Syntax:
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )
Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
Returns the escaped string, or FALSE on error.
Example
<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>
Note:Using mysql_real_escape_string() around each variable prevents SQL Injection.
Note 2 mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.
Protecting Sql queries from SQL Injection in PHP
SQL injection is a serious concern for webmasters, as an experienced attacker can use this hacking technique to gain access to sensitive data and/or potentially cripple your database. If you haven’t secured your applications, I implore you to get yourself familiar with the following method and grind it into your coding routine. One unsafe query can result in a nightmare for you or your client.
In PHP the easiest way is to pass your data through the mysql_real_escape_string function. By escaping special characters on fields where the user can manipulate the database, you will avoid being vulnerable
// This is a vulnerable query.
$query = "SELECT * FROM products WHERE name='$productname'";
mysql_query($query);
// This query is more secure
$query = sprintf("SELECT * FROM products WHERE name='%s'",
mysql_real_escape_string($productname));
mysql_query($query);
These are two queries which perform same actions. First query is a general query which us used by more users.This query is not more secure when compared for security
The second one same but we used the sprintf method to invoke the query. Here we used mysql_real_escape_string method will will not accept the empty characters or special string. We can use this for the security reasons.
Real time example for this is
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// This means the query sent to MySQL would be:
echo $query;
?>
Here the query is generated as
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
Thus provides a option the query to be executed and This would allow anyone to log in without a valid password.
Wednesday, March 18, 2009
array_pop function in PHP
array_pop():
array_pop() pops and returns the last value of the array , shortening the array by one element. If array is empty (or is not an array), NULL will be returned. Will additionally produce a Warning when called on a non-array.
Note:
This function will reset() the array pointer after use.
Example:
<?php
$stack = array("fruits", "cars", "animals", "birds");
$category= array_pop($stack);
print_r($stack);
?>
When this file is executed the output will be
Array
(
[0] => fruits
[1] => cars
[2] => animals
)
Here only the 3 elements will be viewed in the array and the last element is assigned to the variable.
The value of the category will be "birds".
Tuesday, March 17, 2009
Changing port number from 80 to 85 in PHP
When installing a PHP software we may be stuck at certain point like we may be working on some of the other software's, which will allocate the port numbers, But when working with the PHP we need to setup the port number. by default php takes port number 80 as default port number.
There comes a situation where we need to change the port number from 80 to another port number like changing the port number from 80 to port number 85. Then what should be done?
Here are the steps to change the port number:
1. Open the files where you have installed your Apache(if you are using) or XAMPP folder if you have installed the XAMPP software.
2.If you are using the XAMPP software then open the folder "apache".
3.Again in that folder open the folder with name "conf".
4.In this folder open the file "httpd.CONF" file.
5.In the file check the following code
#Listen 12.34.56.78:80
Listen 80
6.change the 80 to 85 and save the file.
7.Restart the server and open the web browser with the given port number.
example: http://localhost:85/foldername.
Monday, March 16, 2009
Magic quotes in PHP
Magic quotes is mainly used for escaping or appeneding \ when a single is occured in the string which is returned in the form of $_GET or $_POST. This is used in PHP 4 and PHP 5
get_magic_quotes_gpc
Gets the current configuration setting of magic quotes gpc.Returns 0 if magic quotes gpc are off, 1 if magic quotes gpc is on.
Example:
<?php
echo get_magic_quotes_gpc(); // 1
echo $_POST['lastname']; // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly
if (!get_magic_quotes_gpc()) {
$lastname = addslashes($_POST['lastname']);
} else {
$lastname = $_POST['lastname'];
}
echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>
Note:
If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''
String functions in PHP
When working with the string we need to take care of single quotations and the backslashes. There are so many scenarios where we get error when this types of special characters raised.
There are PHP function to overcome this problems
1.addslashes
Syntax is
string addslashes ( string $str )
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
Example:
<?php
$str = "welcome to find my solutions is your name O'reilly?";
echo addslashes($str);
?>
Output for this would be
welcome to find my solutions is your name O\'reilly?
If you did not use this function it shows an error.
2. stripslashes()
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).
Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.
An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.
Example:
$stripped = 'In a given string there are three\\\ slashes';
$stripped = stripslahses($stripped);
Output of the above will be
'In a given string there are three\ slashes'
$stripped = 'In a given string there are three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));
The output would be
'In a given string there are three'
Thursday, March 12, 2009
Opening and closing files for read/write operations
PH{ has a set of functions which allows you to read / write in the file and after completing reading and writing you can close the file.
The following are the most important functions used for this type of operation:
fopen(): Opens a file
fgets(): Reads the contents of a file, normally one line at a time
fread(): Reads a specified amount of a file
fwrite(): Writes to a file
feof(): Determines whether the end of the file has been reached
rewind(): Moves an internal pointer back to the top of the file
fclose(): Closes a file.
Before creating a file is very easier, But we need to understand of how the file has been creating, There are different modes which allows file to be created.
Mode for reading and writing in a file
1. Type : readonly
Mode : I
Description: Internal pointer initially placed at beginning of file.
2. Type : Write-only
Mode : W
Description: Existing data deleted before writing. Creates a file if it
doesn’t already exist.
Mode : a
Description: Append mode. New data added at end of file. Creates a file
if it doesn’t already exist.
Mode : X
Description: Creates a file only if it doesn’t already exist, so no danger of
deleting existing data.
3. Type : Read/write
Mode : r+
Description: Read/write operations can take place in either order and
begin wherever the internal pointer is at the time. Pointer
initially placed at beginning of file. File must already exist for
operation to succeed.
Mode : w+
Description: Existing data deleted. Data can be read back after writing.
Creates a file if it doesn’t already exist.
Mode : a+
Description: Opens a file ready to add new data at end of file. Also
permits data to be read back after internal pointer has been
moved. Creates a file if it doesn’t already exist.
Mode : x+
Description: Creates a new file, but fails if a file of the same name already
exists. Data can be read back after writing.
Choose the wrong mode, and you could end up overwriting or deleting valuable data. You also need to be careful about the position of the internal pointer. If the pointer is at the end of the file, and you try to read the contents, you’ll end up with nothing. On the other hand, if the pointer is at the beginning of the file, and you start writing, you’ll overwrite the equivalent amount of any existing data.
You will need to pass two arguements when working with the FOPEN() method
1. The pathname to the file you want to open
2. Mode of the file.
Example:
$file = fopen('C:/test/test.txt', 'r');
Reading a file with FOPEN()
<?php
// store the pathname of the file
$filename = 'C:/test/test01.txt';
// open the file in read-only mode
$file = fopen($filename, 'r');
// read the file and store its contents
$contents = fread($file, filesize($filename));
// close the file
fclose($file);
// display the contents
echo nl2br($contents);
?>
Here in the above example we used fread() instead of file_get_contents(), One thing we need to know when we use the fread() is we need to know how much content we need to read, So for that case we will be supplying the second arguement as number of bytes which are to be read
The nl2br() function in the final line converts new line characters to XHTML
tags.
The other way to read the contents of a file with fopen() is to use the fgets() function, which retrieves one line at a time. This means that you need to use a while loop in combination with feof() to read right through to the end of the file. This is done by replacing this line
$contents = fread($file, filesize($filename));
with this (the full script is in fopen_readloop.php)
// create variable to store the contents
$contents = '';
// loop through each line until end of file
while (!feof($file)) {
// retrieve next line, and add to $contents
$contents .= fgets($file);
}
The while loop uses fgets() to retrieve the contents of the file one line at a time—
!feof($file) is the same as saying until the end of $file—and stores them in $contents.
Note: you need to use either fread() or fgets() if you want to read the contents of a file at the same time as writing to it.
Monday, March 9, 2009
Calculating difference between two dates in PHP
In php we need to calculate the difference between the days. For example, In a form we have provided user to enter the two date where we need to calculate the difference between the two dates.
$date1="07/11/2007";
$date2="09/04/2009";
Here we will be calculating the how many days are there in between the above dates.
Php code :
$date1="07/11/2007";
$date2="09/04/2009";
print "If we minus " . $date1 . " from " . $date2 . " we get " . dateDiff("/", $date2, $date1) . ".";
function dateDiff($dformat, $endDate, $beginDate)
{
$date_parts1=explode($dformat, $beginDate);
$date_parts2=explode($dformat, $endDate);
$start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
return $end_date - $start_date;
}
The dateDiff() functions uses two PHP functions viz., explode() and gregoriantojd(). The explode() function is used mostly to convert strings into arrays.
gregoriantojd(): It changes the date into a big number from which another number (obtained from another date) can be deducted.
Sunday, March 8, 2009
Writing a File PHP
We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go
Example:
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "The file $filename is not writable";
}
?>
Note: On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
2.fwrite() returns the number of bytes written, or FALSE on error.
handle:A file system pointer resource that is typically created using fopen().
String:The string that is to be written.
Length:
If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string .
Note: If writing twice to the file pointer, then the data will be appended to the end of the file
Saturday, March 7, 2009
Calculate No of Days between two dates
When we need to calcualate the no of days between two days. We convert the current date and the previous date into the time and calculate the no of days.
Php code :
<?php
$century = mktime(12, 0, 0, 1, 1, 2001);
$today = time();
$difference = $today - $century;
echo 'This century started ';
echo floor($difference / 84600);
$difference -= 84600 * floor($difference / 84600);
echo ' days, ';
echo floor($difference / 3600);
$difference -= 3600 * floor($difference / 3600);
echo ' hours, ';
echo floor($difference / 60);
$difference -= 60 * floor($difference / 60);
echo " minutes, and $difference seconds ago.";
?>
Here in the above example you can count the days difference between 2 days and minutes and seconds also.
Tuesday, March 3, 2009
Reading a text file into an array PHP
Simply write to code as below to read the text file into an array.
Create a PHP file called file.php inside the filesystem folder. Insert the following
code, Before we start coding we need to know is "Text files can be used as a flat-file database—where each record is stored on a separate line, with a tab, comma, or other delimiter between each field"
<?php
// read the file into an array called $users
$users = file('C:/private/filetest03.txt');
?>
<pre>
<?php print_r($users); ?>
</pre>
This draws the contents of filetest03.txt into an array called $users, and then
passes it to print_r() to display the contents of the array. The <pre> tags simply
make the output easier to read in a browser.
Or you can write as following if you have more data seperated by "," operator
<?php
// read the file into an array called $users
$users = file('C:/private/filetest03.txt');
// loop through the array to process each line
for ($i = 0; $i < count($users); $i++) {
// separate each element and store in a temporary array
$tmp = explode(', ', $users[$i]);
// assign each element of the temporary array to a named array key
$users[$i] = array('name' => $tmp[0], 'password' => $tmp[1]);
}
?>
<pre>
<?php print_r($users); ?>
</pre>
Here the above code means, The count() function returns the length of an array, so in this case the value of count($users) is 2. This means the first line of the loop is equivalent to this:
for ($i = 0; $i < 2; $i++) {
The loop continues running while $i is less than 2. Since arrays are always counted
from 0, this means the loop runs twice before stopping.
Inside the loop, the current array element ($users[$i]) is passed to the explode()
function, which converts a string into an array by splitting the string each time it
encounters a separator. In this case, the separator is defined as a comma followed
by a space (', '). However, you can use any character or sequence of characters:
using "\t" as the first argument to explode() turns a tab-separated string into an array.
The first line in filetest03.txt looks like this for example:
james, jamespassword
When this line is passed to explode(), the result is saved in $tmp, so $tmp[0] is
david, and $tmp[1] is codeslave. The final line inside the loop reassigns $tmp[0] to
$users[0]['name'], and $tmp[1] to $users[0]['password'].
The next time the loop runs, $tmp is reused, and $users[1]['name'] becomes
gayle, and $users[0]['password'] becomes gaylepassword.
Output will be :
Array{
[0] => Array
{
[name] => james
[password] => jamespassword
}
[1] => Array
{
[name] => gayle
[password] => gaylepassword
}
}
In one word you can write as
$users[$i] = array('name' => $tmp[0], 'password' => rtrim($tmp[1]));
Reading files in PHP to a string
Since PHP 4.3.0, the simplest way to read the entire contents of a text file is to use the file_get_contents() function.
Steps for reading a text file and store it to a string.
1. Create a text file in your private folder, type some text into it, and save it as
test01.txt (or use the version in the download files).
2. Create a new folder called filesystem in your phpsolutions site root, and create
a PHP file called file_get_contents.php in the new folder. Insert the following
code inside a PHP block (the download file file_get_contents01.php shows the
code embedded in a web page, but you can use just the PHP for testing purposes):
echo file_get_contents('C:/private/test01.txt');
3. Save file_get_contents.php and view it in a browser. Depending on what you wrote
in test01.txt, you should see somethinglike the screenshot to the left.
using file_get_contents() looks no different from using an include command. However, file_get_contents() treats the external file as a string, which means that you can store the contents in a variable and manipulate it in a way that’s impossible with an include file.
Till here we can sucessfully read the contents in the TXT files, But if you have any errors in the txt file this may execute with warning. So before executing this code we need to check whether the existing Txt file is valid file or not.
Example:
$contents = file_get_contents('C:/private/filetest01.txt');
if ($contents === false) {
echo 'Sorry, there was a problem reading the file.';
}
else {
// convert contents to uppercase and display
echo strtoupper($contents);
}
If the file_get_contents() function can’t open the file, it returns false. Often,
you can test for false by using the negative operator like this:
if (!$contents) {
Here why i used the "===" (identical operator)
The reason I haven’t used that shortcut here is because the external file might be
empty, or you might want it to store a number,an empty string and 0 also equate to false. So, in this case, I’ve used the identical operator (three equal signs), which ensures that both the value and the data type are the same.
Here you can also the write the function as
$contents = @ file_get_contents('C:/private/filetest0.txt');
This is an ideal place to use the error control operator(@). Insert an @
mark immediately in front of the call to file_get_contents().
The output will be... If the filetest0.txt contains a valid data then the data is shown. If the filestest0.txt contains any invalidata then an default error message is shown "Sorry.. There was a problem reading a file".
Note:
Always add the error control operator only after testing the rest of a script. When developing, error messages are your friends. You need to see them to understand why something isn’t working the way you expect.
Sunday, March 1, 2009
Uploading Files in PHP
When working with the Uploading Files in PHP we need to consider the following things:
1.Understanding how PHP handles file uploads
2.Restricting the size and type of uploads
3.Preventing files from being overwritten
4.Organizing uploads into specific folders
5.Handling multiple uploads
The way that PHP handles file uploads makes it relatively simple to restrict the
type and size of files accepted. What it cannot do is check the suitability of the content. It’s therefore always a good idea to implement a strategy that prevents indecent or illegal material from being automatically displayed on your site. One way is to store uploaded material in a nonpublic directory until it has been approved. Another way is to restrict uploads to registered and trusted users by placing the upload form in a password protected area. A combination of both approaches is even more secure.
How PHP handles file uploads
The term “upload” means moving a file from one computer to another, but as far as PHP
is concerned, all that’s happening is that a file is being moved from one location to
another. This means you can test all the scripts in this chapter on your local computer
without the need to upload files to a remote server.
PHP supports file uploads by default, but hosting companies can restrict the size of
uploads or disable them altogether. Before going any further, it’s a good idea to check the
settings on your remote server.
The first and most important thing to check before file upload is "Checking whether your server supports uploads"
You can check by the following command. Type this is your editor and save it as .PHP and run it. Now you must satisfy the below conditions.
Directive
Default value
Description
The definition for the below description
max_execution_time -- Directive
30 -- Default value
The maximum number of seconds that a PHP script can run. If the script takes longer, PHP generates a fatal error.
max_input_time
60
The maximum number of seconds that a PHP script is allowed to parse the $_POST and $_GET arrays, and file uploads. Very large uploads are likely to run out of time.
post_max_size
8M
The maximum permitted size of all $_POST data, including file uploads.Although the default is 8MB, hosting companies may impose a smaller limit.
upload_tmp_dir
This is where PHP stores uploaded files until your script moves them toa permanent location. If no value is defined in php.ini, PHP uses the system default temporary directory.
upload_max_filesize
2M
The maximum permitted size of a single upload file. Although the default is 2MB,
hosting companies may impose a smaller limit. A number on its own indicates the
number of bytes permitted. A number followed by K indicates the number of kilobytes permitted.
It’s important to note the limit imposed by post_max_size. Even though the default
values theoretically permit the simultaneous upload of four 2MB files, the upload is likely to fail because the content of the $_POST array would bring the total to more than 8MB.
If the Local Value of file_uploads is Off, uploads have been disabled. There is nothing you
can do about it, other than ask your hosting company if it offers a package with file
uploading enabled. Your only alternatives are to move to a different host or to use a different solution, such as uploading files by FTP.
Simple for with File upload option
<form action="" method="post" enctype="multipart/form-data"
name="uploadImage" id="uploadImage">
<p>
<label for="image">Upload image:</label>
<input type="file" name="image" id="image" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
The PHP code for Uploading files is:
<?php
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', 'path/to/upload_test/');
// move the file to the upload folder and rename it
move_uploaded_file($_FILES['image']['tmp_name'],
UPLOAD_DIR.$_FILES['image']['name']);
}
?>
Inspecting the $_FILES array
In above code before writing the Uploading code just add below code to under what the $_FILES array contains:
<pre>
<?php
if (array_key_exists('upload', $_POST)) {
print_r($_FILES);
}
?>
</pre>
</body>
checks whether the $_POST array contains upload, the name attribute of the submit
button. If it does, you know the form has been submitted, so you can use
print_r() to inspect the $_FILES array. The <pre> tags make the output easier
to read.
O/P is:
Array {
[image] => Array
{
[name] = testimage.jpg
[type] = image/jpeg
[tmp_name] = c:\window\temp\phpt3.tmp
[error] = 0
[size] = 9603
}
}
You can see that the $_FILES array is actually a multidimensional array. The key (or
name) of the top-level array comes from the name attribute of the file input field—
in this case, image. The image subarray consists of five elements, namely
name: The original name of the uploaded file
type: The uploaded file’s MIME type
tmp_name: The location of the uploaded file
error: An integer indicating any problems with the upload
size: The size of the uploaded file in bytes
Meaning of the different error levels in the $_FILES array
Error level Meaning
0 Upload successful
1 File exceeds maximum upload size specified in php.ini (default 2MB)
2 File exceeds size specified by MAX_FILE_SIZE embedded in the form
3 File only partially uploaded
4 Form submitted with no file specified
5 Currently not defined
6 No temporary folder (PHP 4.3.10 and 5.0.3 and above)
7 Cannot write file to disk (PHP 5.1.0 and above)
Another important error/warning message is:
Another frequent source of confusion is the question of file ownership and how PHP runs on a web server. If you’re testing in Windows, an upload script that has been working perfectly may confront you with a message like this when you transfer it to your remote server:
Warning: move_uploaded_file(/home/user/htdocs/testarea/kinkakuji.jpg)
[function.move-uploaded-file]: failed to open stream: Permission
denied in /home/user/htdocs/testarea/upload_test.php on line 3
Since 777 is the least secure setting, you need to adopt a cautious approach to file
uploads. Begin by testing upload scripts with a setting of 700. If that doesn’t work, try 770, and use 777 only as a last resort. Your upload directory doesn’t need to be within your site root; it can be anywhere on the server. If your hosting company gives you a private directory outside the site root, the most secure solution is to create a subdirectory for uploads inside the private one. Alternatively, create a directory inside your site root, but don’t link to it from any web pages. Give it an innocuous name, such as lastyear
here you can define the folder path where you can upload the files by Define function:
define('UPLOAD_DIR', 'C:/upload_test/');
Note:
If a file of the same name already exists in the upload folder, the new file will
overwrite it without warning.
You may come across scripts that use copy() instead of move_uploaded_file().
Without other checks in place, copy() can expose your website to serious security
risks. Always use move_uploaded_file(); it’s much more secure.
Removing spaces from filenames
Windows and Mac OS X allow you to create long filenames with spaces in them. It makes
them easier to recognize, but spaces in filenames can wreak havoc on Linux servers. Even if your remote server runs on Windows, you should remove all spaces in the names of files likely to be used in web pages, and replace them with hyphens or underscores. This is easily done with a function called str_replace(), which searches for all occurrences of a string within a string, and replaces them with another. The search string can consist of one or more characters, and the replacement string can be zero or more characters. (Using zero characters in the replacement string—a pair of quotes with nothing between them — effectively removes the search string from the target string.) Although you may not think of a space as being a string, it’s just the same as any other character to PHP.
define('UPLOAD_DIR', 'C:/upload_test/');
// replace any spaces in original filename with underscores
// at the same time, assign to a simpler variable
$file = str_replace(' ', '_', $_FILES['image']['name']);
The function str_replace() takes the following three arguments:
The character or substring that you want to replace—in this case, a space
The character or substring that you want to insert—in this case, an underscore
The string that you want to update—in this case, $_FILES['image']['name']
You’ll need to make frequent references to the filename later, so it’s a good idea to
assign the updated filename to a simpler variable, $file, at the same time.
You can make use of the shorter variable right away by amending the line that
moves the uploaded file as follows:
Rejecting large files
The ability to upload files is not enough on its own: you need to make your form more
secure. The first step is to set a maximum size for file uploads. Even if your hosting company sets a lower limit than the 2MB default, you may want to set a much lower limit yourself. At the same time, it’s a good idea to make your form more user-friendly by reporting whether the upload was successful. You can do this easily by checking the error level reported by the $_FILES array
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR.$file);
Code:
Here we need to convert the file size to KB
$kilobytes = MAX_FILE_SIZE/1024;
$formatted = number_format($kilobytes, 1);
$max = $formatted.'KB';
The final code :
// check that file is within the permitted size
if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <=
MAX_FILE_SIZE) {
$sizeOK = true;
}
if ($sizeOK) {
switch($_FILES['image']['error']) {
case 0:
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['image']['tmp_name'],
UPLOAD_DIR.$file);
if ($success) {
$result = "$file uploaded successfully";
}
else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
$result = "Error uploading $file. Please try again.";
default:
$result = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['image']['error'] == 4) {
$result = 'No file selected';
}
else {
$result = "$file cannot be uploaded. Maximum size: $max.";
}
}