Изображение не загружается при реализации, но когда я пытаюсь использовать только PHP-скрипт с изображением, оно загружается нормально - PullRequest
0 голосов
/ 11 ноября 2010

У меня есть скрипт загрузки изображений, изначально я хранил его в файле с именем upload.php, который ПРОСТО содержал скрипт загрузки PHP и простой файловый браузер и кнопку отправки. Это отлично работает, изображение загружается без проблем и попадает в каталог «images / uploads».

Тем не менее, когда я пытаюсь внедрить это в другую страницу, все идет в тупик и не загружается. Я пробовал разные вещи, но я начинаю понимать свои знания PHP, поэтому решил спросить здесь.

Вот код для страницы index.php (страницы, на которой я пытаюсь реализовать скрипт изображения):

<code><?php
    error_reporting(E_ALL);
    session_start();
    if(session_is_registered("username")) {

    include("includes/config.php");
    mysql_connect($host, $dbusername, $dbpassword) or die("Could not connect to database" . mysql_error());
    mysql_select_db($database);

    if(isset($_POST['update'])) {
        $result = mysql_query("UPDATE items SET name='" . $_POST['name'] . "', price='" . $_POST['price'] . "', description='" . $_POST['description'] . "', hidden='" . $_POST['hidden'] . "' WHERE id='" . $_POST['id'] . "'") or die("Could not update" . mysql_error());
    }

    if(isset($_POST['delete'])) {
        $result = mysql_query("DELETE FROM items WHERE id='" . $_POST['id'] . "'") or die(mysql_error());
        header("Location: index.php?p=edit&c=" . $c);
    }

    if(isset($_POST['add'])) {
        $result = mysql_query("INSERT INTO items (name, price, description, category, hidden) VALUES('" . $_POST['name'] . "', '" . $_POST['price'] . "', '" . $_POST['description'] . "', '" . $_POST['category'] . "', '" . $_POST['hidden'] . "')") or die(mysql_error());
    }

    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","100");

    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }

    //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['submit'])) {
    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image) {
    //get the original name of the file from the clients machine
    $filename = stripslashes($_FILES['image']['name']);
    //get the extension of the file in a lower case format
    $extension = getExtension($filename);
    $extension = strtolower($extension);
    //if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
    //print error message
    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else
    {
    //get the size of the image in bytes
    //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
    $size=filesize($_FILES['image']['tmp_name']);

    //compare the size with the maxim size we defined and print error if bigger
    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    //we will give an unique name, for example the time in unix time format
    $image_name=time().'.'.$extension;
    //the new name will be containing the full path where will be stored (images folder)
    $newname="../images/uploads/".$image_name;
    //we verify if the image has been uploaded, and print error instead
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}}

    //If no errors registred, print the success message
    if(isset($_POST['submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully! Try again!</h1>";
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
 <head profile="http://gmpg.org/xfn/11">
    <title>Silverdale Buxton Ltd | Admin CP</title>
    <link rel="stylesheet" type="text/css" media="screen" href="css/admin.css" />
    <link rel="stylesheet" href="css/formalize.css" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
 </head>

 <body>
    <div id="container">
        <div id="header">
            <a href="index.php"><img src="../images/elements/sd-logo.jpg" alt="Silverdale Buxton Ltd" border="0" /></a>
            <ul>
                <li class="title">Admin CP</li>
                <li><a href="../">View website</a></li>
                <li><a href="login.php?do=logout">Log-out <pre><?php echo $_SESSION['username']; ?>
Добавить новый элемент Просмотр / редактирование элементов
<? php if (! isset ($ p)) {// ПОСМОТРЕТЬ СТРАНИЦУ ПО УМОЛЧАНИЮ НА INDEX.PHP?>

Добро пожаловать в панель управления администратора

Эта панель управления позволяет управлять (добавлять / изменять / удалять) предметами для продажи из базы данных Silverdale.

Это достаточно просто для использования; просто нажмите одну из кнопок в правом верхнем углу страницы.

Если у вас есть какие-либо проблемы, пожалуйста, свяжитесь со мной по 01782 269494 (спросите о Chrish) или напишите мне на chrish [at] albionmedia [dot] biz .

<? php} else if ($ p == "add") {// ДОБАВИТЬ СТРАНИЦУ НОВЫХ ПУНКТОВ?>

Добавить новый предмет

<? PHP $ result = mysql_query ("SELECT * FROM Categories"); ?> <выберите имя = "категория"> <? PHP while ($ row = mysql_fetch_array ($ result)) { echo "<option value = \" ". $ row ['catname']." \ ">". $ row ['catname']. " \ n"; } эхо "\ n"; ?>
Шоу Спрятать
" />

"> & LARR; Вернуться назад

<? php} else if ($ p == "edit") {// ПРОСМОТР / РЕДАКТИРОВАНИЕ СТРАНИЦЫ ЭЛЕМЕНТОВ?>

Просмотр / редактирование элементов

<? php if (! isset ($ c)) {?>

Пожалуйста, выберите категорию.

<? php} else if (isset ($ c) &&! isset ($ id)) {?>

Элементы в категории: <? Php echo $ c; ?>

& LARR; Вернуться назад

<? PHP } else if (isset ($ id)) { $ result = mysql_query ("SELECT * FROM items WHERE category = '". $ c. "' AND id = '". $ id. "'"); $ row = mysql_fetch_array ($ result); if ($ row ['hidden'] == 1) { $ vis = "скрытый"; } еще { $ vis = "visible"; } ?> "> " /> " />
Шоу /> Спрятать />
" />

"> & LARR; Вернуться назад

<? }?> ?

Ошибка 404:

URL страницы не распознан. Пожалуйста нажмите здесь .

<? php}?>

Авторские права и копия; 2010 Альбион Медиа. Все права защищены.

albionmedia.biz

<? php if ($ p == "edit") {?> $ (документ) .ready (function () { $ ('. delete'). click (function () { if (подтвердите («Вы уверены, что хотите удалить этот элемент? Это приведет к удалению всей информации и изображений, связанных с ним, и НЕ МОЖЕТ быть не выполнено!»)) { вернуть истину; } еще { вернуть ложь; } }); }); <? Php}?> <? PHP } еще { заголовок («Location: login.php»); } ?>

И это скрипт upload.php, который отлично работает:

<?php
    //define a maxim size for the uploaded images in Kb
    define ("MAX_SIZE","100");

    //This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
    function getExtension($str) {
        $i = strrpos($str,".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
        return $ext;
    }

    //This variable is used as a flag. The value is initialized with 0 (meaning no error found) and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.
    $errors=0;
    //checks if the form has been submitted
    if(isset($_POST['submit'])) {
    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];
    //if it is not empty
    if ($image) {
    //get the original name of the file from the clients machine
    $filename = stripslashes($_FILES['image']['name']);
    //get the extension of the file in a lower case format
    $extension = getExtension($filename);
    $extension = strtolower($extension);
    //if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
    if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
    //print error message
    echo '<h1>Unknown extension!</h1>';
    $errors=1;
    }
    else
    {
    //get the size of the image in bytes
    //$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
    $size=filesize($_FILES['image']['tmp_name']);

    //compare the size with the maxim size we defined and print error if bigger
    if ($size > MAX_SIZE*1024)
    {
    echo '<h1>You have exceeded the size limit!</h1>';
    $errors=1;
    }

    //we will give an unique name, for example the time in unix time format
    $image_name=time().'.'.$extension;
    //the new name will be containing the full path where will be stored (images folder)
    $newname="../images/uploads/".$image_name;
    //we verify if the image has been uploaded, and print error instead
    $copied = copy($_FILES['image']['tmp_name'], $newname);
    if (!$copied)
    {
    echo '<h1>Copy unsuccessfull!</h1>';
    $errors=1;
    }}}}

    //If no errors registred, print the success message
    if(isset($_POST['submit']) && !$errors)
    {
    echo "<h1>File Uploaded Successfully! Try again!</h1>";
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
 <head profile="http://gmpg.org/xfn/11">
    <title>Image Upload | Admin CP</title>
    <link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
 </head>

 <body>
    <form name="newad" method="post" enctype="multipart/form-data" action="">
    <table>
        <tr><td><input type="file" name="image"></td></tr>
        <tr><td><input name="submit" type="submit" value="Upload image"></td></tr>
    </table>
    </form>
 </body>
</html>

Вероятно, следует также отметить, что я не получаю никаких ошибок на этой странице, даже когда я отправляю ее.

1 Ответ

0 голосов
/ 11 ноября 2010

Вам не хватает

enctype="multipart/form-data"

в вашей реализации измените форму на:

    <form method="post" name="editor" enctype="multipart/form-data" action="">

                ...
                <label for="image">Image Upload</label>
                <input type="file" name="image" />

с сайта W3C :

Указав значение энктипа "multipart / form-data", каждый файл содержимое будет упаковано для представление в отдельном разделе составной документ.

...