Ahad, Disember 08, 2013

HTML + PHP : Upload gambar, check extension dan rename nama fail gambar secara unik untuk simpanan

Form :
<html>
<head><title>Borang</title></head>
<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
  <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
    <tr>
      <td><strong>Single File Upload </strong></td>
    </tr>
    <tr>
      <td>Silih fail <input name="0xfile" type="file" id="0xfile" size="50" /></td>
    </tr>
    <tr>
      <td align="center"><input type="submit" name="Submit" value="Upload" /></td>
    </tr>
  </table>
</td>
</form>
</tr>
</table>
</body>
</html>

upload.php
<?php
$file_name = basename($_FILES['0xfile']['name']);

// random 4 digit to add to our file name 
// some people use date and time in stead of random digit 
$random_digit=rand(00000000,99999999);

//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables

// check extension
$allowed =  array('gif','png' ,'jpg');
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_file_name=$random_digit.".".$ext; //.$file_name;

//set where you want to store files
//in this example we keep file in folder upload 
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "images/".$new_file_name;
if(!in_array($ext,$allowed) ) {
    echo 'Upload only .gif, .png or .jpg file';
}else{
  if ($_FILES['0xfile']['size'] != 0)
  {
    if(copy($_FILES['0xfile']['tmp_name'], $path))
    {
      echo "Successful<BR/>"; 

      //$new_file_name = new file name
      //$HTTP_POST_FILES['ufile']['size'] = file size
      //$HTTP_POST_FILES['ufile']['type'] = type of file
      echo "File Name :".$new_file_name."<BR/>"; 
      echo "File Size :".$_FILES['0xfile']['size']."<BR/>"; 
      echo "File Type :".$_FILES['0xfile']['type']."<BR/>"; 
      echo "File URL  :"."/images/{$new_file_name}";
      $url="images/{$new_file_name}";
      echo "<img src=\"{$url}\"/>";
    }else{
      echo "Error";
    }
  }
}

?>

0 ulasan:

Catat Ulasan

Pesanan daripada penulis :
Selamat datang ke 0x2013LΣΣT. Sekiranya anda mempunyai persoalan, pandangan, permintaan, bantuan, cadangan dan sebagainya. Tinggalkan pesanan anda ke dalam kotak komen. Terima kasih !
- http://0x2013.blogspot.com -