2

I've been trying to get a file-upload working for a website I'm working on. I'm doing this outside of a form, and after days of searching I finally found something that fits my method from the answer on this question:

The thing is, as soon as I applied the code to my own script, I got 'Undefined index' errors, and when I removed it, everything went fine.

Here is my code:

HTML

<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>

jQuery

function newsItem(action){
    var thumbnail = $('#newsitem-thumbnail')[0].files[0];
    var fileReader = new FileReader();
    fileReader.readAsText(thumbnail, 'UTF-8');
    fileReader.onload = shipOff;

    function shipOff(e){
        var r = e.target.result;
        if(action == "insert"){
            $.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
                                              thumbnail:thumbnail.name,
                                              action:action,
                                              data:r},
            function(result){
                console.log(result);
                console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
                if(result == "succes"){
                    window.location.reload();
                }else{
                    $(".error-msg").html(result);
                }
            });
        }else if(action == "delete"){
            //To be implemented when I get the submit working D:
        }
    }
}

PHP (Please excuse the mess -needs serious cleaning)

<?php
    include("../assets/libs/SQLLib.php");
    DB_Connect("test");

    echo print_r($_POST);
    echo var_dump($_POST);
    $message = $_POST['message'];
    $action = $_POST['action'];
    $thumbnail = $_POST['thumbnail'];
    $data = $_POST['data'];

    $serverFile = time().$thumbnail;
    $fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
    fwrite($fp, $data);
    fclose($fp);
    $returnData = array("serverFile" => $serverFile);
    echo json_encode($returnData);

    if($_POST['message'] != ""){
        $canPost = true;
    }else{
        echo "The message can not be empty.";
    }

    if($action == "insert" && $canPost){
        $sql = "insert into newsitems
                (date, message, thumbnail)
                values
                (NOW(),'".$message."', '".$thumbnail."')";
        $result = mysql_query($sql);
        if(!$result){
            echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
        }else{
            echo "succes";
        }
    }else if($action == "delete"){
        $sql = "";
    }
?>

Does anybody see what's going wrong here? Or does anyone have an alternative option?

I hope someone can help me out with this issue.

Community
  • 1
  • 1
Zubaja
  • 251
  • 3
  • 18
  • 1
    `console.log(result);` check the values first, than chk what is the result of `print_r($_POST);` – devpro Apr 04 '16 at 09:37
  • Thanks for the swift answer @devpro While adding **console.log()** to my code, I noticed I had a double-declared variable, but even renaming one of those two did not fix anything. I've updated my code above, with the **console.log()** invocations -one dumps my error messages, and the other freezes my inspector view. – Zubaja Apr 04 '16 at 09:50
  • 1
    What 'undefined index' errors do you get exactly? I couldn't reproduce any such errors. – ImClarky Apr 04 '16 at 10:58
  • @ImClarky PHP errors such as **Notice: Undefined index: message** And the likes. It only happens when I have the file-upload code uncommented. When I have those pieces commented (basically a post-action but without the thumbnail), everything works fine and the news items are put inside the database. – Zubaja Apr 04 '16 at 12:36
  • @ImClarky Here's an image of the full screen: https://www.dropbox.com/s/pz3sy21jfq2cioq/PHP_Errors.png?dl=0 – Zubaja Apr 04 '16 at 12:42

3 Answers3

0

Change it like this:

include("../assets/libs/SQLLib.php");
DB_Connect("test");

print_r($_POST); //Dont echo, what is already echoed
var_dump($_POST); //Dont echo, what is already echoed
$message = !empty($_POST['message'])?$_POST['message']:'';
$action = !empty($_POST['action'])?$_POST['action']:'';
$thumbnail = !empty($_POST['thumbnail'])?$_POST['thumbnail']:'';
$data = !empty($_POST['data'])?$_POST['data']:'';
if(!empty($thumbnail) && !empty($data)){

$serverFile = time().$thumbnail;
    $fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
    fwrite($fp, $data);
    fclose($fp);
    $returnData = array("serverFile" => $serverFile);
    echo json_encode($returnData);
} else {
echo json_encode(array('error'=>'No data and thumbnail assigned'));
}

if($message != ""){
    $canPost = true;
}else{
    echo "The message can not be empty.";
}

if($action == "insert" && $canPost){
    $sql = "insert into newsitems
            (date, message, thumbnail)
            values
            (NOW(),'".$message."', '".$thumbnail."')";
    $result = mysql_query($sql);
    if(!$result){
        echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
    }else{
        echo "success";
    }
}else if($action == "delete"){
    $sql = "";
}

As well you only need to change error reporting level in .htaccess or php in order to prevent warning message to be displayed. In .htaccess:

php_flag error_reporting E_ERROR

If in .php file then

<?php error_reporting(E_RROR); //This displays only Errors, no warning and notices.
juslintek
  • 441
  • 3
  • 12
  • Thank you for the answer, and cleanup. This indeed got rid of my "Undefined index" errors, but it still doesn't post new newsitems to the database, sadly. – Zubaja Apr 04 '16 at 09:56
  • *Disabling* warnings instead of fixing them? [**NO**](http://a.fod4.com/images/GifGuide/michael_scott/The-Office-gifs-the-office-14948948-240-196.gif). Terrible answers like this are why PHP has a bad reputation. – Ian Kemp Apr 06 '16 at 07:20
0

So in the end I opted out of a full jQuery-upload, and went for something else. I am now uploading files purely through a PHP call, instead of a jQuery post event, with a small JavaScript check next to it to see if the form is submittable.

The code:

HTML

<div class='error-msg'></div>
<form method='post' action='requestPages/newsitems.php' enctype='multipart/form-data'>
    News message
    <textarea id='newsitem-message' name='newsitem-message' onchange='checkFormSubmit()'/>
    <input type='file' name='newsitem-thumbnail' id='newsitem-thumbnail' />
    <input hidden type='text' value='insert' name='newsitem-action'/>
    <input class='submit' id='newsitem-submit' type='submit' value='Post news' disabled/>
</form>

PHP

<?php
include("../assets/libs/SQLLib.php");
    DB_Connect("test");

    var_dump($_FILES);
var_dump($_POST);

$message = $_POST['newsitem-message'];
$action = $_POST['newsitem-action'];
$errors= array();
$hasFile = false;

if($action == "insert"){
    echo ($_FILES['newsitem-thumbnail'][0] == UPLOAD_ERR_NO_FILE);
    if(isset($_FILES['newsitem-thumbnail']) && $_FILES['newsitem-thumbnail']['error'] != UPLOAD_ERR_NO_FILE){
        $file_name = $_FILES['newsitem-thumbnail']['name'];
        $file_size =$_FILES['newsitem-thumbnail']['size'];
        $file_tmp =$_FILES['newsitem-thumbnail']['tmp_name'];
        $file_type=$_FILES['newsitem-thumbnail']['type'];
        $file_ext=strtolower(end(explode('.',$_FILES['newsitem-thumbnail']['name'])));

        $extensions= array("jpeg","jpg","png");

        if(!in_array($file_ext,$extensions)){
            $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }
        $hasFile = true;
    }
    if(empty($errors)){
        $sql = "insert into newsitems
                (date, message, thumbnail)
                values
                (NOW(),'".$message."', '".$file_name."')";
        $result = mysql_query($sql);
        if(!$result){
            echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
        }else{
            if($hasFile){
                if(!move_uploaded_file($file_tmp,"../assets/images/thumbnails/".$file_name)){
                    echo "Moving the file failed!";
                }
            }
        }
    }else{
        print_r($errors);
    }
}else if($action == "delete"){
    $sql = "";
}
?>

JavaScript

function checkFormSubmit(){
    if($.trim($('#newsitem-message').val()) != ""){
        $('#newsitem-submit').prop('disabled', false);
    }else{
        $('#newsitem-submit').prop('disabled', true);
    }
}
Zubaja
  • 251
  • 3
  • 18
  • So... is this code working, in which case you should mark it as the answer? Or is it still not working, in which case you should edit your question to contain the code, and delete this "answer". – Ian Kemp Apr 06 '16 at 07:21
  • @IanKemp This is the working piece of code. I couldn't mark it as an answer when I posted it (had to wait two hours) and I completely forgot about until just now. – Zubaja Apr 06 '16 at 13:52
0

Hope you have tried using isset($_POST) or isset($_POST['message']) if you get "Notice: Undefined index: message".

GunJan Mehta
  • 312
  • 2
  • 11