0

I'm trying to upload a file (image) to sql table via pathfile but I keep getting these error "undefined index : image on line 3 and line 24". I already defined the image in the userpage. I'm not using BLOB because it consumes too much space. In my sql table, I simply set the image column as vachar. I already checked the php.ini file in xampp ,the upload is on and the maximum is 2MB upload file.Please help. tq.

Below is the userpage:

<?php

//useracc-test.php

//start session
session_start();



require 'connect-test.php';
include 'upload.php';

if(isset($_POST['username'])){


    $userName = $_POST['username'];
    $query = "SELECT id, name, username, telno FROM users WHERE username = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('s', $userName);
    $stmt->execute();
    $res = $stmt->get_result(); 
    $row = $res->fetch_array();
    $_SESSION['id'] = $row['id'];
    $_SESSION['name'] = $row['name'];
    $_SESSION['username'] = $row['username'];
    $_SESSION['telno'] = $row['telno'];

}
?>



<html>
<head>
<script type="text/javascript">
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
</script>
</head>



<body>
<div id="apDiv3">
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><span class="TabbedPanelsContent">
  <?php
    echo $_SESSION['id']."<br/>";
    echo $_SESSION['name']."<br/>";
    echo $_SESSION['username']."<br/>";
    echo $_SESSION['telno']."<br/>";
?>




  <?php 



 if(isset($_POST['submit']))

   {

    $id = $_POST['id'];
    $name2 = $_POST['name2'];
    $color2 = $_POST['color2'];
    $hobby2 = $_POST['hobby2'];
    $radiobtn = $_POST['radiobtn'];
    $image = $_POST['image'];




    $stmt = $conn->prepare("INSERT INTO useradvert (id,name2,color2,hobby2,radiobtn,image) VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("isssss",$id,$name2,$color2,$hobby2,$radiobtn,$image);
    $stmt->execute();



   // $stmt->close();
   // $conn->close();

   //think of something later how to close and logout
  /*  <?php unset($_SESSION); 
    session_destroy(); ?> */
   } 


    ?>

</p>

<p>&nbsp;</p>
<form name="form2" 
      action="useracc-test.php" method="post" enctype="multipart/form-data">
  <p>&nbsp;</p>
  <table width="500" border="0">
    <tr>
      <td>category</td>
      <td><select name="jumpMenu" id="jumpMenu" onChange="MM_jumpMenu('parent',this,0)">
        <option value="useracc-test.php" selected>Category</option>
        <option value="useracc-test.php">Members</option>
        <option value="useracc-test2-jumpmenu.php">Non-members</option>
      </select></td>
    </tr>
    <tr>
      <td>ID:</td>
      <td><input name="id" type="text" id="id" value="<?php echo $_SESSION['id']; ?>" ></td>
    </tr>
    <tr>
      <td>Name:</td>
      <td><input type="text" name="name2" id="name2"></td>
    </tr>
    <tr>
      <td>Color</td>
      <td><input type="text" name="color2" id="color2"></td>
    </tr>
    <tr>
      <td>Hobby</td>
      <td><input type="text" name="hobby2" id="hobby2"></td>
    </tr>
    <tr>
      <td>Sex</td>
      <td>male
        <input type="radio" name="radiobtn" id="radio" value="male">
        female
        <input type="radio" name="radiobtn" id="radio2" value="female"></td>
    </tr>
    <tr>
      <td>Image</td>
      <td><input type="file" name="image" id="image"></td>
    </tr>

    <tr>
      <td>&nbsp;</td>
      <td><input type="submit" name="submit" id="submit" value="submit"></td>
    </tr>
  </table>
  <div align="center"></div>
  <p>&nbsp;</p>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>&nbsp;</p>
  <p>
</body>
               </html>

below is the upload.php file where I run the upload script.

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image or not
if(isset($_POST["submit"])) {

    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["image"]["size"] > 200000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

I'm getting error undefined index on line 3 and line 24.

error line 3 refers to below;

$target_file = $target_dir . basename($_FILES["image"]["name"]);

error line 24 refers to below;

if ($_FILES["image"]["size"] > 200000) {
  • You're trying to access `$_FILES['image']` outside `ifset($_POST['submit']`. So when the script runs before you submit the page, there's no file. – Barmar Jan 02 '16 at 15:19
  • tq @Barmar. But could you point me to the direction and post your answer in the answer section. I have a limited knowledge in PHP as I'm a newbie in this field. tq. – ml2_1jzsinglecam Jan 02 '16 at 15:23
  • @Barmar. I tried that previously. But unfortunately, it gives me more errors, undefined index on line 30, 35, 40 and 41. Any solution?. btw. tq for your help. I appreciate. – ml2_1jzsinglecam Jan 02 '16 at 15:29
  • Which lines are those? – Barmar Jan 02 '16 at 15:37
  • sorry, i pasted them back again. and enter several spaces, but i just pasted them back again as previously. now the error is if (file_exists($target_file)) { (line 39), if ($_FILES["image"]["size"] > 200000) {(line 44), if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"(line 49), && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; (line 50). I did the same thing as you suggested previously. – ml2_1jzsinglecam Jan 02 '16 at 15:43
  • What index does it say doesn't exist? Are you sure the user actually uploaded a file? – Barmar Jan 02 '16 at 15:47
  • 1
    What would the directory have to do with an undefined index? Do you understand what that error message means? – Barmar Jan 02 '16 at 15:47
  • See http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index – Barmar Jan 02 '16 at 15:48
  • Sorry my bad. yeah agree. I'm still sticking to the suggestion you gave me. But I just can't solve the problem. – ml2_1jzsinglecam Jan 02 '16 at 15:50
  • What do `var_dump($_POST)` and `var_dump($_FILES)` show? – Barmar Jan 02 '16 at 15:51
  • 1
    Do some basic debugging. When it tells you there's a problem with a variable, look at the value of the variable. – Barmar Jan 02 '16 at 15:52
  • @Barmar, as I mentioned earlier, I'm a newbie, and I don't really comprehend what you are trying to say regarding var_dump etc. Basically, all the other codes work fine. The only problem is with the upload.php. – ml2_1jzsinglecam Jan 02 '16 at 15:57
  • 1
    `var_dump` will show the contents of a variable. So if it's saying that `$_FILES['image']` is undefined, the first thing you should do is look at what's actually in `$_FILES`. – Barmar Jan 02 '16 at 15:59
  • 1
    Simple common sense, I think. – Barmar Jan 02 '16 at 16:00
  • Maybe if you can show me by correcting my mistakes in the answers section, it would be helpful since you have the experience and have gone through this before. – ml2_1jzsinglecam Jan 02 '16 at 16:07
  • How can I correct your mistakes until you answer my questions so I figure out what the problem is? – Barmar Jan 02 '16 at 16:22
  • Ok. i i tried var_dump($_POST) and var_dump($_FILES) for the first time. it showed array(3) { ["username"]=> string(14) "test2@mail.com" ["password"]=> string(8) "abcd1234" ["login"]=> string(5) "Login" } array(0) { } – ml2_1jzsinglecam Jan 02 '16 at 16:31
  • How do I relate this to undefined index and variables? – ml2_1jzsinglecam Jan 02 '16 at 16:34
  • I just noticed something. The code you posted is in `upload.php`. But the form says `action="useracc-testphp"`, so that's where the code that processes `$_FILES['image']` should be. – Barmar Jan 02 '16 at 16:41
  • I change the action="useracc-test.php" to action="upload.php" all the errors gone. Now I have to think a way how to migrate the codes in userpage to upload.php. I there anyone out there that is kind that can help me here? It seems im solving my own problem – ml2_1jzsinglecam Jan 02 '16 at 16:51
  • sorry didn't saw ur message above ..why does my pc keeps getting late response from other users – ml2_1jzsinglecam Jan 02 '16 at 16:51
  • Sorry @Barmar, didn't saw your message coming. it seems my browser or something is not alerting me when a user post comments. – ml2_1jzsinglecam Jan 02 '16 at 16:54
  • So, is action="upload.php" the correct way? @Barmar – ml2_1jzsinglecam Jan 02 '16 at 16:56
  • Correct me if I'm wrong, but for security reasons you might want to use: `if ($_SERVER['REQUEST_METHOD'] === 'POST') {` – Roko C. Buljan Jan 02 '16 at 16:57
  • @ml2 If that's the correct name of the script, it is. – Barmar Jan 02 '16 at 16:57
  • the errors are gone already, but now i can't insert the data. i have to migrate some of the scripts from userpage to upload.php. Am I correct? correct me if I'm wrong. – ml2_1jzsinglecam Jan 02 '16 at 16:57
  • @ml2 Yes, I believe that's correct. I hope you're not expecting us to do all that work for you. You're expected to understand the basics, we'll help you fix things, but not do your work for you. – Barmar Jan 02 '16 at 16:59
  • yeah.. I agree..@Barmar. – ml2_1jzsinglecam Jan 02 '16 at 17:01
  • post your comments in the answer section @Barmar. So I can accept your answer just now. tq – ml2_1jzsinglecam Jan 02 '16 at 17:02
  • Or I'll just accept the answer below. which did help. – ml2_1jzsinglecam Jan 02 '16 at 17:03
  • Hi @Roko. I'll try your suggestion later. since i'm a newbie. aren't i suppose to use isset before ($_SERVER['REQUEST_METHOD'] === 'POST') ???? please correct me. tq – ml2_1jzsinglecam Jan 02 '16 at 17:04
  • Someone didn't read the documentation... – Lightness Races in Orbit Jan 02 '16 at 17:20
  • @LightnessRacesinOrbit regarding... – Roko C. Buljan Jan 02 '16 at 17:29
  • @RokoC.Buljan: The handling of uploaded files. – Lightness Races in Orbit Jan 02 '16 at 17:32

1 Answers1

0

All the code that depends on the post parameters should be inside the if isset($_POST['submit']) block. Otherwise, none of the other $_POST or $_FILE parameters will be set.

The other problem you're having is that you're posting to the wrong script. The form should say action = "upload.php".

<?php
if(isset($_POST["submit"])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image or not

    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["image"]["size"] > 200000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["image"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>
Barmar
  • 741,623
  • 53
  • 500
  • 612