Php 是否将图像上载存储在文件夹=到会话id?

Php 是否将图像上载存储在文件夹=到会话id?,php,image,session,upload,Php,Image,Session,Upload,我有一个脚本可以将照片上传到“file/”目录。 我想这样做,以便在“文件”目录中有另一个文件夹,该文件夹标记为登录用户的会话id。因此,如果用户“1”上传照片,它将转到“file/1/default.jpg”,如果用户“2”上传照片,则转到“file/2/default.jpg” 谁能告诉我怎么做。谢谢 html: $('#sampleform')。提交(函数(e){ e、 预防默认值(); $.ajax({ url:$(this.attr('action'), 类型:'post', 数据:

我有一个脚本可以将照片上传到“file/”目录。 我想这样做,以便在“文件”目录中有另一个文件夹,该文件夹标记为登录用户的会话id。因此,如果用户“1”上传照片,它将转到“file/1/default.jpg”,如果用户“2”上传照片,则转到“file/2/default.jpg”

谁能告诉我怎么做。谢谢

html:


$('#sampleform')。提交(函数(e){
e、 预防默认值();
$.ajax({
url:$(this.attr('action'),
类型:'post',
数据:$(this).serialize(),
数据类型:'json',
成功:功能(r){
$(“#表单结果”)。追加(
'标题:'+r.Title+''
,“描述:”+r.Description+“”
,“图像/文件:”
+''
+''
);
}
});
});
//调用jQuery“droparea”插件
$('.droparea').droparea({
“init”:函数(结果){
//log('custominit',result);
},
“开始”:函数(区域){
area.find('.error').remove();
},
“错误”:函数(结果、输入、区域){
$('').html(result.error).prependTo(区域);
返回0;
//console.log('customerror',result.error);
},
“完成”:函数(结果、文件、输入、区域){
if((/image/i.test(file.type)){
area.find('img').remove();
//area.data('value',result.filename);
面积。追加($('
upload.php:

<?php

// LOG
$log = '=== ' . @date('Y-m-d H:i:s') . ' ===============================' . "\n"
        . 'FILES:' . print_r($_FILES, 1) . "\n"
        . 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('upload-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);


// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');


// Maximum file size
$maxsize = 10; //Mb
// File size control
if ($_FILES['xfile']['size'] > ($maxsize * 1048576)) {
    $r->error = "Max file size: $maxsize Kb";
}


// Uploading folder
$folder = 'files/';
if (!is_dir($folder))
    mkdir($folder);
// If specifics folder 
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
    mkdir($folder);


// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {

    $filename = $_POST['value'] ? $_POST['value'] :
            $folder . '_default.jpg';
} else {

    $tld = split(',', $_FILES['xfile']['name']);
    $tld = $tld[count($tld) - 1];
    $filename = $_POST['value'] ? $_POST['value'] :
            $folder . '_default.jpg';
}


// Supporting image file types
$types = Array('image/png', 'image/gif', 'image/jpeg');
// File type control
if (in_array($_FILES['xfile']['type'], $types)) {
    // Create an unique file name    
    // Uploaded file source
    $source = file_get_contents($_FILES["xfile"]["tmp_name"]);
    // Image resize
    imageresize($source, $filename, $_POST['width'], $_POST['height'], $_POST['crop'], $_POST['quality']);
} else
// If the file is not an image
if (in_array($_FILES['xfile']['type'], $types)) 
    move_uploaded_file($_FILES["xfile"]["tmp_name"], $filename);



// File path
$path = str_replace('upload.php', '', $_SERVER['SCRIPT_NAME']);

// Result data
$r->filename = $filename;
$r->path = $path;
$r->img = '<img src="' . $path . $filename . '" alt="image" />';

// Return to JSON
echo json_encode($r);

// Image resize function with php + gd2 lib
function imageresize($source, $destination, $width = 0, $height = 0, $crop = false, $quality = 80) {
    $quality = $quality ? $quality : 80;
    $image = imagecreatefromstring($source);
    if ($image) {
        // Get dimensions
        $w = imagesx($image);
        $h = imagesy($image);
        if (($width && $w > $width) || ($height && $h > $height)) {
            $ratio = $w / $h;
            if (($ratio >= 1 || $height == 0) && $width && !$crop) {
                $new_height = $width / $ratio;
                $new_width = $width;
            } elseif ($crop && $ratio <= ($width / $height)) {
                $new_height = $width / $ratio;
                $new_width = $width;
            } else {
                $new_width = $height * $ratio;
                $new_height = $height;
            }
        } else {
            $new_width = $w;
            $new_height = $h;
        }
        $x_mid = $new_width * .5;  //horizontal middle
        $y_mid = $new_height * .5; //vertical middle
        // Resample
        error_log('height: ' . $new_height . ' - width: ' . $new_width);
        $new = imagecreatetruecolor(round($new_width), round($new_height));
        imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $w, $h);
        // Crop
        if ($crop) {
            $crop = imagecreatetruecolor($width ? $width : $new_width, $height ? $height : $new_height);
            imagecopyresampled($crop, $new, 0, 0, ($x_mid - ($width * .5)), 0, $width, $height, $width, $height);
            //($y_mid - ($height * .5))
        }
        // Output
        // Enable interlancing [for progressive JPEG]
        imageinterlace($crop ? $crop : $new, true);

        $dext = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
        if ($dext == '') {
            $dext = $ext;
            $destination .= '.' . $ext;
        }
        switch ($dext) {
            case 'jpeg':
            case 'jpg':
                imagejpeg($crop ? $crop : $new, $destination, $quality);
                break;
            case 'png':
                $pngQuality = ($quality - 100) / 11.111111;
                $pngQuality = round(abs($pngQuality));
                imagepng($crop ? $crop : $new, $destination, $pngQuality);
                break;
            case 'gif':
                imagegif($crop ? $crop : $new, $destination);
                break;
        }
        @imagedestroy($image);
        @imagedestroy($new);
        @imagedestroy($crop);
    }
}

?> 

post.php:

<?php

// LOG
$log = '=== ' . @date('Y-m-d H:i:s') . ' ===============================' . "\n"
        . 'FILES:' . print_r($_FILES, 1) . "\n"
        . 'POST:' . print_r($_POST, 1) . "\n";
$fp = fopen('post-log.txt', 'a');
fwrite($fp, $log);
fclose($fp);


// Result object
$r = new stdClass();
// Result content type
header('content-type: application/json');


$data = $_POST['thumbnail'];
unset($_POST['thumbnail']);

if($data){

    // Uploading folder
    $folder = 'files/';
    if (!is_dir($folder))
        mkdir($folder);
    // If specifics folder 
    $folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
    if (!is_dir($folder))
        mkdir($folder);


    $filename = $_POST['value'] ? $_POST['value'] :
            $folder . sha1(@microtime() . '-' . $_POST['name']) . '.jpg';


    $data = split(',', $data);
    file_put_contents($filename, base64_decode($data[1]));

}
die(json_encode(array_merge(array('url' => $filename), $_POST)));

?>

文件名应为:

$filename = $_POST['value'] ? $_POST['value'] :
        $newDir . '_default.jpg';


编辑:我在
upload.php中未找到
session\u start()
,如果会话中存储了用户的session\u id变量,请使用
session\u start()
位于文件顶部。

谢谢,但这不会改变任何事情。图像仍在上载到“files/”中,并且没有创建具有会话id的目录。您是否也可以显示HTML部分,以确保有关POST值的信息。

哪里是
$\u POST['value',$\u POST['folder']
在你的HTML部分??指的是你的
值,文件夹
?我不太清楚它为什么使用这些值。我把session_start()放在upload.php文件的顶部,它现在创建了一个带有会话id的文件夹,但它把它放在“files/”之外,图像仍然存储在“files/”
@date('Y-m-d H:i:s')
--真的吗
// Uploading folder
$folder = 'files/';
if (!is_dir($folder))
    mkdir($folder);

// If specifics folder 
$folder .= $_POST['folder'] ? $_POST['folder'] . '/' : '';
if (!is_dir($folder))
    mkdir($folder);

// PASS USER_ID HERE
$folder2 = $_SESSION['user_id'] . '/';
if (!is_dir($folder2))
    mkdir($folder2);

// New directory with 'files/USER_SESSION_ID/'
$newDir = $folder . $folder2;
$filename = $_POST['value'] ? $_POST['value'] :
        $newDir . '_default.jpg';
// Uploading folder
$folder = 'files/'.$_SESSION['user_id'];
if (!is_dir($folder))
    mkdir($folder);


// If the file is an image
if (preg_match('/image/i', $_FILES['xfile']['type'])) {
    // $_FILES['xfile']['name'] .'_default.jpg' /* prevent the conflict with the same name */
    $filename = $folder . '/'. $_FILES['xfile']['name'] .'_default.jpg';
} else {

    $tld = split(',', $_FILES['xfile']['name']);
    $tld = $tld[count($tld) - 1];
    $filename = $folder . '/'. $_FILES['xfile']['name'] .'_default.jpg';
}