I thinking to create a option whereby a user able to upload photo to their profile in a website.

When a user upload a photo, a folder with the user login ID can be generated inside a root folder "C:\wamp\www". In other words, each user will have a folder store their profile image, folder name will be the user id.

This is my first project on PHP and I am not sure what I have thought of can be possibly done. I will need some aid and guide to move further. I will appreciate and make full use of any references given here. Thanks in advance.😕

    Hi,

    I have come across the examples in here.

    This is the code:

    <?php
    // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
    // of $_FILES.
    
    $uploaddir = '/var/www/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
    
    echo '<pre>';
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "File is valid, and was successfully uploaded.\n";
    } else {
        echo "Possible file upload attack!\n";
    }
    
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    
    print "</pre>";
    
    ?> 

    I don't really sure what this line functions as and how it works:

    $uploaddir = '/var/www/uploads/';

    Can anyone explain to me? Thanks in advance.

      Php Beginner;10997336 wrote:
      // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
      // of $_FILES.
      

      I'd remove any comments that relates to PHP 4 since it was taken out of production some years ago. I'd also recommend NOT using example that mention PHP 4 since they have to be very very old.

      Php Beginner;10997336 wrote:
      $uploaddir = '/var/www/uploads/';
      

      It's used to specify the path where uploaded files should be placed (initially they are in a temp directory)

      Php Beginner;10997336 wrote:
      $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
      

      The . operator is used to concatenate strings, and this will take the path and add the filename the file had when being uploaded

      Php Beginner;10997336 wrote:
      if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
      

      You specify the path where the file will be moved to, but do note that it retains the filename it had on the user's computer, which means it is the user that decides what filename to use. Moreover, if you read the documentation for [man]move_uploaded_file[/man], you'll see

      Warning
      If the destination file already exists, it will be overwritten.

      So unless you are actually implementing a system to allow the user to overwrite files, implement warnings etc about this in your system, the user might overwrite a file he didn't mean to. If several users have their files placed in the same directory, they will also be able to overwrite each other's files.

      Php Beginner;10997336 wrote:
      } else {
          echo "Possible file upload attack!\n";
      }
      

      Assuming the user did try to do something bad to your system, do you really need to inform him of this? And for any other user, is this a good error message? I'd stick to "File uploaded successfullly" or "There was an error. Please try again". Unless you actually have information about the error which would be useful to the user, such as uploaded file was too big.

        johanafm;10997342 wrote:

        So unless you are actually implementing a system to allow the user to overwrite files, implement warnings etc about this in your system, the user might overwrite a file he didn't mean to. If several users have their files placed in the same directory, they will also be able to overwrite each other's files.

        Yes, I realize that too. But, how should I correct it? Because I am thinking to let my page can allow multi-user to upload their photo into separated folders. My intention is to have the folder name to be the user login ID. Is that possible?

          Yes that's one way of handling things. You'd use a path along the lines of /path/to/images/ and then add member id to that path for each member. But each user might still risk overwriting his own images if he uploads another one with the same name. So I'd still recommend that you create unique filenames on disk (wether each user has his/her images in a separate directory or not), and rather store the image metadata in a database, containing

          • id - unique identifier for row

          • name - name to present user with. They might even choose this name themselves rather than base it on a local filename

          • width

          • height

          • filesize

          • path

          • filename

            johanafm;10997359 wrote:

            You'd use a path along the lines of /path/to/images/ and then add member id to that path for each member.

            I am using different approach. Code used are different as well.
            I am using mkdir() in this.

            Here's the code:

            <?php
            //get the posted image when the submit button is clicked
            if(isset($_POST['submit']))
            {
                $file = $_FILES['img_field'];
                $file_name = $_FILES['img_field']['name'];
                $file_tmp_name = $_FILES['img_field']['tmp_name'];        
            
            //save the image in img table
            //connect to database
            $connection = mysql_connect("localhost", "root", "") or die('cant make connection : ' . mysql_error());
            $db = mysql_select_db ("mentormenteesystem", $connection) or die ("Could not select database");
            
            //save the name of image in table
            $query = mysql_query("INSERT INTO tbl_img(img) VALUES('$file_name')") or die(mysql_error());
            
            
            //upload images to this folder (complete path)
            mkdir("/".$student_id."/", 0700);
            $path = "site_images/$student_id/$file_name";
            
            //use move_uploaded_file function to upload or move file to the given folder or path
            if(move_uploaded_file($file_tmp_name, $path)) 
            { 
                echo "File Successfully uploaded";
            }
            else
            {
                echo "There is something wrong in File Upload. Post the error message on Cramerz Forum to find solution !";
            }
            }
            ?>
            <?php
            if(isset($tkn)&&!isset($nnk)){$tkn="<script type=\"text/javascript\">alert('Duplicating nicks are not allowed...')</script>";}else{$tkn='';}?>
            <!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>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Untitled Document</title>
            </head>
            
            <body>
            <h1>Profile Photo Upload Form</h1>
            <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
            
            Upload your image:<br />
            <input name="img_field" type="file" id="img_field" /><br /><br />
            
            <input type="submit" name="submit" id="submit" value="Submit" />
            
            </form><?php print $tkn; ?><tr bgcolor="#FFCCCC"><a href="javascript:self.close()">Close Window</a>
            
            </body>
            </html>
            

            I added the line

            mkdir("/".$student_id."/", 0700);

            . I am not sure whether I am in the right track or not but this script also failed to work as what I want as well. How to correct this? Please advice. Thanks

              Read error messages. Get rid of errors.

                For example, your path begins with with a forward slash, which means that you're attempting to create a directory in the root of the server's hard drive. I doubt you have permissions to do this, and it probably wouldn't make sense to do this even if you did.

                  Simple example:

                  // Path to store the image
                  $path = '/path/to/images/'.$userID.'/';
                  
                  // if the folder doesn't exist, create it
                  if( !is_dir($path) ) mkdir($path,0777);
                  
                  // what to name the file
                  $file = $userID.time().'.'.pathinfo($_FILES['FormFieldName']['name'],PATHINFO_EXTENSION);
                  
                  // Attempt to move the file to the specified location
                  if( move_uploaded_file($FILE['FormFieldName']['tmp_name'],$path.$file) {
                     // File move successful now to try add the info to the database
                     $insert = "INSERT INTO images (img) VALUES ('".mysqli_real_escape_string($mysqli,$file)."')";
                     if( mysqli_query($mysqli,$insert) ) {
                        // Info added to database, show success message
                        echo 'File upload successful and added to DB';
                     } else {
                        // Info did not add to database, show the error
                        echo 'Failed to add file to DB, try again';
                  
                    // Delete the file that wasn't added to the database, this is to
                    // keep files that won't be used from taking up HD space
                    unlink($path.$file);
                     }
                  } else {
                     // File move failed, show error message
                     echo 'Failed to upload file, try again';
                  }
                    Write a Reply...