avtar
avtar

Reputation: 13

File Upload not Working in PHP

I am new to PHP and am trying to create a page to upload a jpeg file. The webpage seems to run fine and it appears the file is uploading, however the file is not appearing on the server. Any help you can provide will be great.

The PHP code is:

<?php
    $target_dir="/var/www/html/";
    $fileName=$_FILES['file']['name'];
    $target_file=$target_dir . basename($fileName);
    $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
    $fileTempName=$_FILES["file"]["tmp_name"];
    $fileType=$_FILES["file"]["type"];
    $fileSize=$_FILES["file"]["size"];
    $fileError=$_FILES["file"]["error"];
    if(($fileType=="image/jpeg")&&($fileSize<100000)){
            if($fileError>0){
                    echo "Return Code: " . $fileError . "<br />";
            }
            else{
                    echo "Upload: " .$fileName . "<br />";
                    echo "Type: " . $fileType . "<br />";
                    echo "Size: " . ($fileSize / 1024) . " kb<br />";
                    echo "Temp file: " . $fileTempName . "<br />";
            if (file_exists($fileName)){
                    unlink($fileName);
            }
            move_uploaded_file($fileTempName,$target_file);
            echo "<br><br>File Temp Name: " .$fileTempName."\r\n <br>";
            echo "Uploaded file stored as : " .$target_file ."<br><br>";
            }       
    }
    else{
            echo "File is not a JPEG or too big.";
    }
?>

And the HTML code is as follows:

 <html>
       <body>
       <form action="save2web.php" method="post" enctype="multipart/form-data">
       <label for="file">Filename:</label>
       <input type="file" name="file" id="file"/>
       <br/>
       <input type="submit" name="submit" value="Upload"/>
       </form>
       </body>
       </html>

Upvotes: 0

Views: 106

Answers (3)

P Clegg
P Clegg

Reputation: 697

Presuming your server is linux from the path, you may need to change the permissions of the folder your trying to upload to, try changing the folder owner to www-data, this fixed the same issue for me.

Upvotes: 0

Munshi Azhar
Munshi Azhar

Reputation: 317

Change your target directory like this. Add a .(dot) before the directory name.

$target_directory = './var/www/html';

Upvotes: 0

Yang
Yang

Reputation: 8701

The problem is that, you don't check the returned value of move_uploaded_file() at all. But looks like, you're running your script on the host, and since most host disallow relative paths, you'd better provide an absolute.

So try, replacing:

$target_dir = "/var/www/html/"; // <- This is relative, which might be blocked due to security reasons

with

$target_dir = dirname(__FILE__) . "/var/www/html/"; // dirname(__FILE__) is a path to root

And then, make sure that the file was uploaded:

if (!move_uploaded_file(...)) {
  // error
}

Upvotes: 1

Related Questions