简体   繁体   中英

PHP file upload image not loading to server

I am attempting to upload a image file via php and it is not working:

<?php
$target_dir = "/home/NAME/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);

$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

print_r($_FILES);
?>

This is what is returned, but no file actually uploads. Anyone know what is going on? Thanks

Array ( [fileToUpload] => Array ( [name] => followers.png [type] => image/png [tmp_name] => /tmp/phpKsuz1B [error] => 0 [size] => 127008 ) )

Change:

  move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir);

To:

  move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)

Change move_uploaded_file($_FILES['fileToUpload']['name'], $target_dir); to move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_dir);

move_uploaded_file needs the temporary file name in order for it to upload, not the original name of the file, since it needs a resource to move.

The uploaded file is actually $_FILES['fileToUpload']['tmp_name'] , this is the file you need to move.

A good way to go about this is:

$tempFile = $_FILES['fileToUpload']['tmp_name'];    
$destFile = '/dest/directory/' . $_FILES['fileToUpload']['name'];

// You'll now have your temp file in destination directory, with the original image's name
move_uploaded_file($tempFile, $destFile);

A good practice is to keep your file names unique, because you never know when different images may be named image01.jpg (more often than one would hope).

$tempFile = $_FILES['fileToUpload']['tmp_name'];    

$destDir  = '/dest/directory/';
$destName = uniqid() . '_' . $_FILES['fileToUpload']['name'];
$destFile = $destDir . $destName;

// Temp file is now in destination directory, with a unique filename  
move_uploaded_file($tempFile, $destFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM