0

i've done many things on fileupload project but there are problem that make the project stop when i upload image it don't give any problems or any errors but the image that get uploaded don't show in the '/uploads folder

the code that i use

<html>
<head>
     <title>image uploader</title>
</head>
<body>

<form action="upload.php" method="POST" enctype="multipart/form-data">
   image selector :
<input type="file" name="uploadsrc" /> <input type="submit" value="Upload">
</form>

<style type="text/css">
body{;
                font-family: sans-serif;
            }

<?php
//connected to database
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("meinimages") or die(mysql_error());

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

 <?php

// file properties
@$file = $_FILES['image']['tmp_name'];

if (!isset($file))
    echo "please select an image.";
else
{
 $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));  
 $image_name = addslashes($_FILES['image']['name']);
 $image_size = getimagesize($_FILES['image']['tmp_name']);

if ($image_size==FALSE)
     echo "you try upload nonimage.";
else
 {
    if (!$insert = mysql_query("INSERT INTO store VALUES ('','$image_name','$image')"))
      echo "problem while upload the $image.";
    else
    {
      $lastid = mysql_insert_id();
      echo "image is uploaded.<p />your image:<p /><img src=get.php?id=$lastid>";
    }
 }

}

ps : is this an error on my code or error on the database/phpmyadmin ?

3
  • $_FILES["pictures"]? The form field is called uploadsrc not pictures Commented Jun 12, 2017 at 5:55
  • i ve try it days ago but its not work Commented Jun 12, 2017 at 5:58
  • You are also using the deprecated mysql class so if you are using PHP 7+ then the db calls will fail as the mysql routines are no longer part of php. Use mysqli instead so you can utilise prepared statements. The code suggests multiple files but the form element allows only a single due to the lack of multiple attribute Commented Jun 12, 2017 at 6:05

1 Answer 1

1

As I suggested in the comments your php code was looking for a form element called pictures but the form itself had a field called uploadsrc so regardess of any other problems it would never actually process the upload. The code also suggests multiple files being uploaded but the form itself does not have the multiple attribute set on the file field so would only permit a single file. The code below is for a single file upload - though to convert to accept multiple is relatively straight forward. Hopefully the following will be useful - but you really ought to look at using mysqli so that you can use prepared statements

<?php

    mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("meinimages") or die(mysql_error());

    /* utility function to return error message during upload processing */
    function uploaderror( $code ){ 
        switch( $code ) { 
            case UPLOAD_ERR_INI_SIZE: return "The uploaded file exceeds the upload_max_filesize directive in php.ini"; 
            case UPLOAD_ERR_FORM_SIZE: return "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; 
            case UPLOAD_ERR_PARTIAL: return "The uploaded file was only partially uploaded"; 
            case UPLOAD_ERR_NO_FILE: return "No file was uploaded"; 
            case UPLOAD_ERR_NO_TMP_DIR: return "Missing a temporary folder"; 
            case UPLOAD_ERR_CANT_WRITE: return "Failed to write file to disk"; 
            case UPLOAD_ERR_EXTENSION: return "File upload stopped by extension"; 
            default: return "Unknown upload error";
        }
    }

    /* The form file field name */
    $field='uploadsrc';
?>

<html>
<head>
     <title>image uploader</title>
    <style type="text/css">
        body{font-family: sans-serif;}
    </style>
</head>
<body>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
       image selector :<input type="file" name="uploadsrc" />
        <input type="submit" value="Upload">
    </form>
<?php

    /* Only process for POST requests */
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES[ $field ] ) ){

        /* Restrict file extensions possibly */
        $permitted=array('jpg','jpeg','png','gif');

        /* Define a maximum allowed file size perhaps */
        $maxfilesize=pow(1024,2) * 2.5; /* 2.5Mb */

        /* placeholder array to receive errors during processing */
        $errors=array();

        /* target location to save images */
        $uploads_dir = '/uploads';


        /* Get the upload properties */
        $obj=(object)$_FILES[ $field ];
        $name=$obj->name;
        $tmp=$obj->tmp_name;
        $size=$obj->size;
        $error=$obj->error;
        $type=$obj->type;


        if( $error == UPLOAD_ERR_OK && is_uploaded_file( $tmp ) ){

            /* define the full path to save the image to */
            $targetfile = $uploads_dir . DIRECTORY_SEPARATOR . $name;

            /* Get properties of the uploaded image */
            $ext=pathinfo( $name, PATHINFO_EXTENSION );
            $imgsize=getimagesize( $tmp );

            /* rudimentary error checks */
            if( !in_array( $ext, $permitted ) ) $errors[]='File type is not allowed';
            if( !$imgsize ) $errors[]='Not an image';
            if( $size > $maxfilesize ) $errors[]='Image is too large';

            /* Attempt to move the file to it's final location */
            $status = empty( $errors ) ? move_uploaded_file( $tmp, $targetfile ) : false;


            if( $status ){
                /*
                    Generally it is not considered a good idea to store the actual file contents
                    in the database due to the size implications. The db will likely grow very large
                    and become more unstable potentially. Better to simply store the path to the uploaded
                    file!
                */
                $data = addslashes( file_get_contents( $targetfile ) );
                $sql="insert into `store` values ('','$name','$data');";

                $status = mysql_query( $sql );
                $lastid = $status ? mysql_insert_id() : false;

                echo $status ? "problem while uploading image" : "image is uploaded. <p>Your image:</p><img src=get.php?id=$lastid>";

            } else {
                /* Display any error messages */
                foreach( $errors as $err ){
                    echo $err . '<br />';
                }
            }

        } else {
            if( !$error == UPLOAD_ERR_OK ){
                exit( uploaderror( $error ) );
            }
        }
    }

?>
Sign up to request clarification or add additional context in comments.

9 Comments

its ok , but find a problem still think that is comming from my db maybe Notice: Undefined variable: uploads in C:\xampp\htdocs\imgfox\upload.php on line 40
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES[ $filedname ] ) ){
? whats the answer?
I had erronously used $fieldname where it should be if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_FILES[ $field ] ) ){ ~ the variable $field is near the top of the code, below the function uploaderror and should be the name of the FILE field in the HTML form
thx its work but i think there is an error in move_to_upload its unable to move the image to the uploads/files Warning: move_uploaded_file(/uploads\4tGCag7.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\imgforce\upload.php on line 75 Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpAD9A.tmp' to '/uploads\4tGCag7.jpg' in C:\xampp\htdocs\imgforce\upload.php on line 75 line 75 :$status = empty( $errors ) ? move_uploaded_file( $tmp, $targetfile ) : false;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.