簡體   English   中英

如何保護 CKEditor 文件上傳 PHP 腳本免受未經授權的訪問?

[英]How to protect a CKEditor file upload PHP script against unauthorized access?

我在受密碼保護的環境中使用以下 CKEditor 文件上傳 PHP 腳本:

$accepted_origins = array( 'http://localhost', 'http://192.168.1.1', 'http://example.com', 'http://www.example.com' );
$upload_folder = '../uploads/';

if ( isset( $_FILES['upload'] ) ) {

    // Required: anonymous function reference number as explained above.
    $funcNum = $_GET['CKEditorFuncNum'] ;

    // Optional: instance name (might be used to load a specific configuration file or anything else).
    $CKEditor = $_GET['CKEditor'] ;

    // Optional: might be used to provide localized messages.
    $langCode = $_GET['langCode'] ;

    // Optional: compare it with the value of `ckCsrfToken` sent in a cookie to protect your server side uploader against CSRF.
    // Available since CKEditor 4.5.6.
    $token = $_POST['ckCsrfToken'] ;

    if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
        // same-origin requests won't set an origin. If the origin is set, it must be valid.
        if ( in_array( $_SERVER['HTTP_ORIGIN'], $accepted_origins ) ) {
            header( 'Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN'] );
        } else {
            $error = 'Origin denied';
        }
    }

    // Sanitize input
    if ( preg_match( "/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $_FILES['upload']['name'] ) ) {
        $error = 'Invalid file name';
    }

    // Verify extension
    if ( !in_array( strtolower( pathinfo( $_FILES['upload']['name'], PATHINFO_EXTENSION ) ), array( 'gif', 'jpg', 'png', 'pdf' ) ) ) {
        $error = 'Invalid extension';
    }

    // Check if filename already exists
    $file_info = pathinfo( $_FILES['upload']['name'] );
    $i = 0;
    do {
        $target_filename = $file_info['filename'] . ( $i ? "_$i" : '' ) . '.' . $file_info['extension'];
        $i++;
        $target_file = $upload_folder . $target_filename;
    } while ( file_exists( $target_file ) );

    // Process file upload
    $tmp_file = $_FILES['upload']['tmp_name']; 
    move_uploaded_file( $tmp_file, $target_file );
    $protocol = ( $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off' ) ? 'https://' : 'http://';
    $url = 'uploads/' . basename( $target_file );

    echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$error');</script>";

}

該腳本通過config.filebrowserUploadUrl設置從 JS 文件 ( config.js ) 調用,該設置不知道任何 PHP session。 我的問題是,是否可以保護它免受未經授權的訪問? 如果是這樣,怎么做?

提前致謝

只需將此語句更改為:

if ( isset( $_FILES['upload'] ) ) {

對此:

if ( isset( $_FILES['upload'] )  && isset( $_SESSION['user_id'] ) ) {

如果您確實設置了$_SESSION變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM