codingtcher.com
Theme Night
Home
Login

File upload in php code

Home » Tutorial Post » File upload in php code

Use this function and easily upload a file.

<?php
function localfileUpload($inputsize=false){
    if(isset($_POST['commit'])){
    $checkFileName = $_FILES["file_name"]["name"];
    if(!$checkFileName){
    die('Choose a file...');
    exit;}
    $exsion = array('pdf','txt','php');
    if(isset($checkFileName)){
    $checkEx = explode('.',$checkFileName);
    $checkExten = end($checkEx);
    }
    if(isset($checkFileName) && !in_array(strtolower($checkExten),$exsion)){
    die('Extension error...');
    exit;
    }
    $pathlocation = str_replace(str_split('\@!#`~$%^*()+=[]{}|:;",<>?'), '', trim($_POST['pathlocation']));
    $dir = $_SERVER["DOCUMENT_ROOT"].'/'.trim($pathlocation,'/');
    if(trim($pathlocation)){
        if(is_dir($dir)){
        $pathfile = '/'.trim($pathlocation,'/');}
        else{die('Path not available');exit;}
    }else{$pathfile = '';}
    $filenamereplace = str_replace(str_split('\\/@!#`~$%^*+=|:;"<>?'), '', trim($_POST['rename_file_name']));
    if(trim($filenamereplace)){
        $str = pathinfo(trim($filenamereplace));
        $filepath = $_SERVER["DOCUMENT_ROOT"].''.$pathfile.'/'.$str['filename'].'.'.strtolower($checkExten);
    }else{$filepath = $_SERVER["DOCUMENT_ROOT"].''.$pathfile.'/'.$_FILES["file_name"]["name"];}
    if(is_dir($dir)){
    move_uploaded_file($_FILES["file_name"]["tmp_name"], $filepath);}
    if(is_file($filepath)){$msg='File uploaded';}else{$msg='File not uploaded';}
    header("Location: ".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?msg=".$msg."");
    }
    if($inputsize){
    $size = $inputsize;
    }else{$size = '20';}
    $html = '';
    if(isset($_GET['msg'])){$html .= '<span>'.$_GET['msg'].'</span>';}
    $html .= '<form name="Files" enctype="multipart/form-data" method="post" action="">';
    $html .= 'New File: <input type="file" name="file_name" id="file_name" value="" size="'.$size.'" /><br/>
    Rename: <input type="text" name="rename_file_name" id="rename_file_name" value="" size="'.$size.'" /><br/>
    Store Path: <input type="text" name="pathlocation" id="pathlocation" value="" size="'.$size.'" /><br/>';
    $html .= '<input type="submit" name="commit" value="Upload" />
    </form>';
    return $html;
 }
?>

Calling function

echo localfileUpload();

Related Post