Home > Article > Backend Development > PHP image upload function_PHP tutorial
[html]
admin_upfile.php
[php]
date_default_timezone_set('PRC');
//Upload here $upsize determines the size of the uploaded file
$uppath = isset($_REQUEST["upPath"]) ? $_REQUEST["upPath"] : "/attached/"; //File upload path
$formName = isset($_REQUEST["formName"]) ? $_REQUEST["formName"] : "myform"; //Return to the Name of the Form where the edit box on the previous page is located
$editName = isset($_REQUEST["editName"]) ? $_REQUEST["editName"] : $_REQUEST["editName"]; //Return to the Name of the edit box on the previous page
//Convert the path to the root directory
If (strpos($uppath, "/") == 0) {
$i = 0;
$thpath = $_SERVER["SCRIPT_NAME"];
$thpath = substr($thpath, 1, strlen($thpath));
while (strripos($thpath, "/") !== false) {
$thpath = substr($thpath, strpos($thpath, "/") + 1, strlen($thpath));
$i = ++$i;
}
$pp = "";
for ($j = 0; $j < $i; ++$j) {
$pp .="../";
}
$uppaths = $pp . substr($uppath, 1, strlen($thpath));
}
$filename = date("y-m-d");
If (is_dir($uppaths . $filename) != TRUE)
mkdir($uppaths . $filename, 0777);
// if(is_dir($filename."/".$ctime)!=TRUE) mkdir($filename."/".$ctime,0777);
$f = $_FILES['file1'];
if ($f["type"] != "image/gif" && $f["type"] != "image/pjpeg" && $f["type"] != "image/jpeg" && $f[ "type"] != "image/x-png") {
echo "<script>alert('Only files in image format can be uploaded');window.close()</script>";
//echo $f['type'];
return false;
}
//Get file extension
$temp_arr = explode(".", $f["name"]);
$file_ext = array_pop($temp_arr);
$file_ext = trim($file_ext);
$file_ext = strtolower($file_ext);
//New file name
$new_file_name = md5(date("YmdHis")) . '.' . $file_ext;
//$new_file_name = md5(date("YmdHis") . '_' . rand(10000, 99999)) . '.' . $file_ext;
$dest = $uppaths . $filename . "/" . date("ymdhis") . "_" . $new_file_name; //Set the file name to date plus file name to avoid duplication Upload directory
$dest1 = $uppath . $filename . "/" . date("ymdhis") . "_" . $new_file_name; //Set the file name to date plus file name to avoid duplication
$r = move_uploaded_file($f['tmp_name'], $dest);
If ($f['size'] > 0) {
echo "<script>window.opener.document." . $formName . "." . $editName . ".value='" . $dest1 . "'</script>";
echo "<script>alert('Picture uploaded successfully');window.close()</script>";
}
?>
admin_upload.php
[php]