Problem with uploading files to the server

Asked

Viewed 4,358 times

-1

I’m learning to use a server cloud and I’m having trouble uploading files.

I made a code with simple PHP and HTML:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<input type="text" name="titu" placeholder="Titulo" />
<input class="lal" type="submit" name="cadastrar" value="Cadastrar" >    
</form>

<?php
  require_once 'conexao.php';
  if(isset($_POST['cadastrar'])){

    /* IMAGEM */
    $img    = $_FILES['img'];
    $name   = $img ['name'];
    $tmp    = $img ['tmp_name'];
    $size   = $img ['size'];
    $ext    = end(explode('.',$name));      
    $pasta    = "../imagem/";
    $maxSize    = 1024 * 1024;
    $permiti    = array('jpg', 'jpeg', 'png');         
    $titu         = filter_input(INPUT_POST, 'titu');

    if(empty($titu)){echo "Informe um titulo";  
    }else{      

      $name = uniqid().'.'.$ext;
      try{    
          $stmte = $pdo->prepare("INSERT INTO post(TITULO, IMAGEM) VALUES (:1, :2)");
          $stmte->bindParam(":1", $titu  , PDO::PARAM_STR);
          $stmte->bindParam(":2", $name  , PDO::PARAM_STR);   
          $executa = $stmte->execute();

          if($executa){        
            echo 'Dados inseridos com Sucesso';
            $upload   = move_uploaded_file($tmp, $pasta.$name);   
          }
          else{
            echo 'Erro ao inserir os dados';
          }
        }
    catch(PDOException $e){
    echo $e->getMessage();
    }}}
?> 

And the comic book record is going perfectly, so much so that I can get into phpMyAdmin and see there the newly added record as well as updating the home page where the posts are displayed.

But as you can see, I’m uploading an image file but, although the record is being successfully inserted into the BD, the move_uploaded_file does not move the temporary file as it should.

And that’s my problem because I have to display the post with the image, but as this is not being sent, it does not exist.

I don’t understand why, since if I run the code on my PC, with WAMP, both the registration and the upload work normally. And the server appears to work, since it does not return any error message, but the upload is not performed.

I don’t think it’s any wrong code because I’ve used that same code several times on shared servers and it’s always worked. The problem is only on this server cloud.

I believe that the problem may lie in the very configuration of cloud, because I’ve even changed the folder’s permission images for 777 and nothing.

I also changed some PHP.INI directives as shown in the image below:

inserir a descrição da imagem aqui

Would anyone know the cause?

  • They are not the same. The one on my pc is Windows. The one on the server is linux Ubuntu 10.04

  • avoid using <code>'</code> or <code>/</code> where you refer to?

  • is yes @lost, I thought it had worked, but not working no. It was just my illusion. However now the problem is clearer. Take a look at the bars? what bars?

  • But @lost switch the bars in case they are wrong will help me in what? Because in the case when I run the code by serve it does not even register in the BD, now register locally it enters the information in the BD, but does not transfer the image and/or video pro serve

  • 3

    So it gets hard, you’re changing the question completely, including stuff I put in the answer. And the worst, the most important things I’ve posted, which are the right paths, it seems to me you haven’t used. PS: I think it’s good for the person to start with the simplest possible and get better with each step until they get into trouble, just don’t think it’s cool to change everything after it’s posted. Anyway, if it’s to test, I would suggest starting from scratch and testing the connection with DB even before having FORM. Then do the FORM without UPLOAD, and then put the UPLOAD.

  • The question still has the same basis. the code is registering everything in the database of the serve but it is not transferring the media files. My difficulty is not in registering things in BD but transferring the files to the server. This code I added is the same as before, but much simpler, only with the necessary, this is a test to see if I can download pro serves at least one image! only I’m not even getting it.

  • 4

    Ivan, is that when you enter into the question information that was in one of the answers, you invalidate the answer at least partially.

  • @Bacco already did it. I’ve dissected the whole code. I have tested the connection, the tables, the posting code without the upload and all these tests gave 100%, there was no error. But the problem is only in sending media to the server. Because now I’m uploading and is even registering, but the image I select does not go to folder.

  • Guys, I rephrased the question. If you could reopen it, I’d appreciate it!

  • I had a good improvement in the newsroom, let’s see if it helps.

Show 6 more comments

1 answer

5


Note: This answer was posted before the author of the question changed the code.
To later question, on the basis of screenshot, may be the cause of the problem.

Anyway, I’ll leave it here because it may (eventually) be useful to someone.



Missed in the question the form send to see if everything is ok.


Adjusting PHP to show errors

Put these 3 lines at the beginning of your PHP

   ini_set('display_startup_errors',1);
   ini_set('display_errors',1);
   error_reporting(E_ALL);

But be careful: once everything is up and running, remember to remove them.

It’s supposed to be like this all the way from the beginning:

<?php
   ini_set('display_startup_errors',1);
   ini_set('display_errors',1);
   error_reporting(E_ALL);

   require_once 'conexao.php'; // Cadê o caminho correto? Solução: DOCUMENT_ROOT

   if(isset($_POST['cadastrar'])) {
   ⋮

Note that I removed one ?> and <?php unnecessary in require_once.


On the sliders to separate the directories:

One of the things is to trade the bars for DIRECTORY_SEPARATOR on these two lines:

  $pasta   = '..'.DIRECTORY_SEPARATOR.'imagens'.DIRECTORY_SEPARATOR;
  ⋮
  $mppasta   = '..'.DIRECTORY_SEPARATOR.'videos'.DIRECTORY_SEPARATOR;

Another is to take the bar of these, as they have already been defined in the variables:

  $upload   = move_uploaded_file($tmp, $pasta.$name);
  $upload   = move_uploaded_file($mptmp, $mppasta.$mpname);

(or even leave the PATH_SEPARATOR here, and take from the variables)


Improving the paths with $_SERVER['DOCUMENT_ROOT']:

Better than using '.. ', it would be the case to put the right way using $_SERVER['DOCUMENT_ROOT'], so you would have no danger of making confusion with relative paths.

  require_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'conexao.php';
  ⋮
  $pasta   = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'imagens'.DIRECTORY_SEPARATOR;
  ⋮
  $mppasta   = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'videos'.DIRECTORY_SEPARATOR;

This server variable usually returns something like this (it depends on how the server was configured, of course):

/var/www/NOMEDOSITE/httpdocs

Just be careful in the local copy to keep the same test directory structure.

Remember to adjust the intermediate folders with the full path.


About the permissions:

Normally on the server you will have to give greater permission in the folders, so that it can record the files. This is because the user who runs the server web (Apache, etc.), be different from the user who sends FTP.

  • One way would be by the FTP program itself. In Filezilla, for example, you can mark the folder with the mouse, and select "permissions". Just connect the square allowing writing to "Group" and "Other" (W/G/O).

  • The other by shell Linux, with the commands chmod 777 imagens and chmod 777 videos (the 777 allows everyone to write in the folder, it is important to know this and take proper care).


And one more fuzz to "debug" the code:

Assuming you used DIRECTORY_SEPARATOR as recommended above, swap the move_upload_file for this, to better see where the fault happens:

if($executa){
   if( is_uploaded_file( $tmp ) ) {
      if( !move_uploaded_file( $tmp, $pasta.$name ) ) {
         echo 'Arquivo 1 nao foi movido';
      }
   } else {
      echo 'Arquivo 1 nao veio pelo upload';
   }

   if( is_uploaded_file( $mptmp) ) {
      if( !move_uploaded_file( $mptmp, $mppasta.$mpname ) ) {
         echo 'Arquivo 2 nao foi movido';
      }
   } else {
      echo 'Arquivo 2 nao veio pelo upload';
   }
}
  • I changed the folder permission and changed the paths as you said. I also put to display the errors with php, but it also came to nothing. I changed the posting code. I made it simpler just for testing. However, it’s not happening. I’ll change the code in the question.

  • I took it into consideration. But as the bfavaretto said "incorporate in the question information that was in one of the answers, you invalidate the answer, at least partially", so I preferred to leave the original code. Including the part of "take-charge to "debug" I found quite interesting!

  • 1

    @ivanveloso Note that in the later you did not give the least return if it worked or not to who answered you, and did not test the temp dir. That may be the cause of the problem, for example, because if the temp_dir is not allowed, the upload does not happen (but will appear in the strip web). You need to understand that you have to be very clear when asking and testing, because it confuses even those who want to help.

  • me back yes. Look at the first comment. I said I followed your tips only that nothing had worked out! It’s okay that I didn’t go into detail. I didn’t say what had happened. But being clear now. When I followed your suggestions, did not give anything different, may have improved, but sending the image pro serves continued not happening. My sincere apologies if I seemed sloppy with your reply, but it was not my intention. I followed every hint of yours!

  • 2

    I’m talking about the other answer, not mine. I’m fine with it. What I meant was that the other person in the other question did not get a return (that question you asked from upload_temp_dir). I’m cool, and I hope you can handle it, anyway. These things we comment to improve your use of the site, and live better (it is not "scolding", it is just an observation). I even edited my comment in response, so it doesn’t look so aggressive. There are times that I also "mistake the hand", in the same way as anyone.

  • Finally I work. I believe that the exact configuration of the "/" bars was something fundamental. Thank you.

  • 1

    I’m glad you solved it. But in the next questions, try to isolate the problem, often you by simplifying will figure out yourself where the failure happens. Here are some good tips: Minimum, Complete and Verifiable Example

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.