Monthly Archives: May 2012

How to upload a file in PHP

The code to upload file in PHP is very simple, but we need to understand the flow which is a below.

  • Browse the file from a local system
  • Upload to server
  • Server keeps it on a temporary path
  • Copy from temporary to permanent path

Create a file upload form

<html>

<body>

<form action=”upload-file.php” method=”post” enctype=”multipart/form-data”>

<label for=”file”>Filename:</label>

<input type=”file” name=”file” id=”file” />

<br />

<input type=”submit” name=”submit” value=”Submit” />

</form>

</body>

</html>

Note:

  • An enctype attribute of the <form> tag has been specified. This attribute  specifies which content-type to use when submitting the form
  • We have used “multipart/form-data” to upload binary data, like the contents of a file, to be uploaded
  • If proper enctype is not provided, upload will not work.
  • File upload is a huge security risk so you must check what type of files are being uploade

Create a file upload script (upload-file.php)

<?php

$my_folder = “./uploads/”;

copy($_FILES["file"]["tmp_name"],$my_folder.$_FILES["file"]["name"]);

echo “File uploaded.”;

?>

This will upload the file to the specified path.

Note:

  • The default file upload size using a browser is usually 2MB so files larger than this size may not upload. You will have to alter the file upload setting on the server.
  • You need to set write permission to the folder where file needs to be upload. In our case, the “uploads” folder needs to have a 777 permission on a linux/unix server.

 

 

How to fill a dropdown combo box in PHP from MySQL database table

This is an easy to use code to select records from MySQL database table and display in dropdown combo box using PHP.

$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = "SELECT field_name FROM table_name";
$rs = mysql_query($sql) or die(mysql_error());
echo "<select>";
while($row = mysql_fetch_array($rs)){
echo "<option value='".$row["field_name"]."'>".$row["field_name"]."</option>";
}mysql_free_result($rs);
echo "</select>";

How to send HTML mail in PHP

To send HTML mail in PHP, you need to use some additional headers. Below is the code to send HTML mail in PHP.

$to = “recipient@domain.com“;
$subject= “Subject of email”;
$message= “This is <h1>HTML</h1> mail.”;
$fromName = “Name of the sender”;
$fromEmail = “sender@domain.com“;

// To send HTML mail, the Content-type header must be set
$headers  = “MIME-Version: 1.0″ . “\r\n”;
$headers .= “Content-type: text/html; charset=iso-8859-1″ . “\r\n”;

// Additional headers
$headers .=”From: $fromName <$fromEmail>”.”\r\n”;

//Mail function
mail($to, $subject, $message, $headers);