Пользователь загружает изображения в определенные каталоги - PullRequest
0 голосов
/ 18 марта 2011

Таким образом, в основном у меня есть сайт, на котором некоторым участникам разрешено загружать изображения (страницы комиксов) в свои галереи изображений (в определенные комиксы). У меня есть успешный скрипт загрузки изображений, который я использовал для загрузки профилей / аватаров для каждого участника, но теперь, когда я хочу загрузить файлы в более конкретное место, у меня возникли небольшие проблемы.

Вот что у меня есть:

(это то, что появляется вверху страницы)

<?php
session_start();
$toplinks = "";
if (isset($_SESSION['id'])) {
    // Put stored session variables into local php variable
    $userid = $_SESSION['id'];
    $username = $_SESSION['username'];
    $toplinks = '<a href="member_profile.php?id=' . $userid . '">' . $username . '</a> &bull; 
    <a href="member_account.php">Account</a> &bull; 
    <a href="logout.php">Log Out</a>';
} else {
    $toplinks = '<a href="join_form.php">Register</a> &bull; <a href="login.php">Login</a>';
}
?>

(Это скрипт загрузки)

<?php
// Here we run a login check
if (!isset($_SESSION['id'])) { 
   echo 'Please <a href="login.php">log in</a> to access your account';
  exit(); 
} 
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
    // Run error handling on the file
    // Set Max file size limit to somewhere around 120kb
    $maxfilesize = 400000;
    // Check file size, if too large exit and tell them why
    if($_FILES['uploadedfile']['size'] > $maxfilesize ) { 
        echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
        <a href=\"upload_comic.php\">click here</a> to try again";
        unlink($_FILES['uploadedfile']['tmp_name']); 
        exit();
    // Check file extension to see if it is .jpg or .gif, if not exit and tell them why
    } else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
        echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
        <a href=\"upload_comic.php\">click here</a> to try again";
        unlink($_FILES['uploadedfile']['tmp_name']);
        exit();
        // If no errors on the file process it and upload to server 
    } else { 
        // Rename the pic
        $newname = ""; //numbers only, so they show up sequentially
        // Set the direntory for where to upload it, use the member id to hit their folder 
        // Upload the file
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "comics/$comicid/".$newname)) {
            echo "Success, the image has been uploaded and will display to visitors!<br /><br />
            <a href=\"member_account.php\">Click here</a> to return to your profile edit area";
            exit();
        } else {
            echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
            <a href=\"member_account.php\">Click here</a> to return to your profile edit area";
            exit();
        }
    } // close else after file error checks
} // close if post the form
?>

В идеале я хотел бы иметь возможность загрузить изображение, например так: comics / comic_id / chapter_id / uploaded_file.extension

С загрузчиком изображения профиля пользователя я смог получить $ ID из переменной $ _Session ['id'], но с комиксами я не знаю, как получить эту информацию и использовать ее для установки каталог comic_id (chapter_id будет выбран в форме, поэтому я не слишком беспокоюсь об этом).

Есть мысли?

Ответы [ 2 ]

0 голосов
/ 19 марта 2011

Вы можете загрузить файл куда угодно.Это сохранит комикс в папке с его идентификатором и главой, но сохранит имя файла.Если вы хотите использовать комический идентификатор в качестве имени файла, я уверен, что вы можете решить это.

$basepath = "/home/path/to/www/comics/member_" . $member_id . "/";

function construct_path($chapter_id,$comic_id) 
{
   $saveimagepath = $basepath . $comic_id . $chapter
}

if (!isset($_SESSION['id'])) { 
   echo 'Please <a href="login.php">log in</a> to access your account';
  exit(); 
} 
// Place Session variable 'id' into local variable
$id = $_SESSION['id'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
    // Run error handling on the file
    // Set Max file size limit to somewhere around 120kb
    $maxfilesize = 400000;
    // Check file size, if too large exit and tell them why
    if($_FILES['uploadedfile']['size'] > $maxfilesize ) { 
        echo "<br /><br />Your image was too large. Must be 400kb or less, please<br /><br />
        <a href=\"upload_comic.php\">click here</a> to try again";
        unlink($_FILES['uploadedfile']['tmp_name']); 
        exit();
    // Check file extension to see if it is .jpg or .gif, if not exit and tell them why
    } else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['uploadedfile']['name'] ) ) {
        echo "<br /><br />Your image was not .gif, .jpg, or .png and it must be one of those three formats.<br />
        <a href=\"upload_comic.php\">click here</a> to try again";
        unlink($_FILES['uploadedfile']['tmp_name']);
        exit();
        // If no errors on the file process it and upload to server 
    } else { 
        // Rename the pic
        $newname = $saveimagepath . $_FILES['uploadedfile']['tmp_name']; 
//numbers only, so they show up sequentially
        // Set the direntory for where to upload it, use the member id to hit their folder 
        // Upload the file
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $newname)) {
            echo "Success, the image has been uploaded and will display to visitors!<br /><br />
            <a href=\"member_account.php\">Click here</a> to return to your profile edit area";
            exit();
        } else {
            echo "There was an error uploading the file, please try again. If it continually fails, contact us by email. <br /><br />
            <a href=\"member_account.php\">Click here</a> to return to your profile edit area";
            exit();
        }
    } // close else after file error checks
} // close if post the form
?>
0 голосов
/ 18 марта 2011

Переменная $ _SESSION доступна на любом сайте, который вы начали с помощью session_start (). Поэтому, если идентификатор установлен сразу после входа в систему, вы можете получить доступ к этому значению на любой другой странице таким же образом с помощью $ _SESSION ['id']. Убедитесь, что значение id не убьет вашу файловую систему и не приведет к проблемам с безопасностью!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...