PHP move_uploaded_file不能工作

时间:2015-07-01 17:25:19

标签: php ios

我搜索了谷歌,我找到的答案都没有帮助我。我试图在php中使用函数move_uploaded_file,所有我得到这些错误:

Notice: Undefined index: file in /Applications/XAMPP/xamppfiles/htdocs/photos.php on line 53

Notice: Undefined index: file in /Applications/XAMPP/xamppfiles/htdocs/photos.php on line 57

当我使用此代码时:

<?php

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

if (!empty($_POST['firstName']) ) {
$firstname = htmlentities($_POST['firstName']);
echo $firstName;
} elseif (isset($_POST['lastName']) ) {
$lastname = htmlentities($_POST['lastName']);
echo $lastName;
}
if (isset($_POST['userId']) ) {
$userID = htmlentities($_POST['userId']);

echo $userId;
}



$target_dir = "wp-content/uploads/2015/02";
if(!file_exists($target_dir))
{
//chdir($target_dir);
mkdir($target_dir, 0777, true);
}







$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);



$moveResult =  (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) ;

if ($moveResult == true) {

echo json_encode([
"Message" => "The file ". basename($_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
]);

} else {
  if (isset($_REQUEST['userId']) ) {
  $user = $_REQUEST['userId'];
  }
echo json_encode([
//  echo filename;
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",

//"userId" => $user,
]);


}





?>

或者我在使用此代码时始终返回false:

<?php

if (!empty($_POST['firstName']) ) {
$firstname = htmlentities($_POST['firstName']);
echo $firstName;
} elseif (isset($_POST['lastName']) ) {
$lastname = htmlentities($_POST['lastName']);
echo $lastName;
}
if (isset($_POST['userId']) ) {
$userID = htmlentities($_POST['userId']);

echo $userId;
}



$target_dir = "wp-content/uploads/2015/02";
if(!file_exists($target_dir))
{

mkdir($target_dir, 0777, true);
}





$target_dir = $target_dir . "/" . basename("filename");



$moveResult =  (move_uploaded_file('filename', $target_dir)) ;

if ($moveResult == true) {

echo json_encode([
"Message" => "The file ". basename($_FILES["filename"]). " has been   uploaded.",
"Status" => "OK",
"userId" => $_REQUEST["userId"]
 ]);

  } else {
  if (isset($_REQUEST['userId']) ) {
  $user = $_REQUEST['userId'];
  }
echo json_encode([
//  echo filename;
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",

//"userId" => $user,
]);


}


?>

PS我已经尝试过将代码显示我的错误,但它没有报告任何内容。

我正在使用它为我的iOS应用程序制作服务器,这是我的快速代码:

import UIKit

class photogetupload: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {



    @IBOutlet weak var myImageView: UIImageView!
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func uploadButtonTapped(sender: AnyObject) {

        myImageUploadRequest()

    }

    @IBAction func selectPhotoButtonTapped(sender: AnyObject) {

        var myPickerController = UIImagePickerController()
        myPickerController.delegate = self;
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary

        self.presentViewController(myPickerController, animated: true, completion: nil)

    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])

    {
        myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        self.dismissViewControllerAnimated(true, completion: nil)

    }

    func myImageUploadRequest()
    {

        let myUrl = NSURL(string: "http://localhost:490/photos.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";

        let param = [
            "firstName" : "Nathan",
            "lastName" : "Huns",
            "userId" : "9"
        ]

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)

        if(imageData==nil) { return; }

        request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)

        myActivityIndicator.startAnimating();

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if error != nil {
                println("error=\(error)")
                return
            }

            // You can print out response object
            println("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("****** response data = \(responseString!)")

            dispatch_async(dispatch_get_main_queue(),{
                self.myActivityIndicator.stopAnimating()
                self.myImageView.image = nil;
            });

        }

        task.resume()

    }

    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {

        var body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("–-\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "user--profile.jpg"

        let mimetype = "image/jpg"

        body.appendString("–-\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey)
        body.appendString("\r\n")

        body.appendString("–-\(boundary)–-\r\n")

        return body
    }

    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }

}

extension NSMutableData {
    func appendString(string: String) {
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        appendData(data!)
    }
}

我没有收到任何错误,这就是它记录的内容

******* response = <NSHTTPURLResponse: 0x7f8f485a8e60> { URL: http://localhost:490/photos.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Length" = 77;
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Wed, 01 Jul 2015 16:54:31 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = "Apache/2.4.12 (Unix) OpenSSL/1.0.1m PHP/5.6.8 mod_perl/2.0.8-dev Perl/v5.16.3";
    "X-Powered-By" = "PHP/5.6.8";
} }
****** response data = {"Message":"Sorry, there was an error uploading your file.","Status":"Error"}

任何解决方案? 谢谢!

1 个答案:

答案 0 :(得分:0)

* First of all make sure that your folder is having permission for read and write 
* Secondly input type="file" name="file" size="50 
check size of input and change it accordingly.

您的代码正常运行,请确保以上两点

<head>

    <title>A simple example of uploading a file using PHP script</title>

</head>

<body>

    <b>Simple example of uploading a file</b><br />

    Choose a file to be uploaded<br />

    <form action="upload_file.php" method="post" enctype="multipart/form-data">

        <input type="file" name="file" size="500" />

        <br />

        <input type="submit" value="Upload" />

    </form>

</body>

现在在upload_file.php中确保$ target_dir具有正确的文件夹路径来上传文件

enter code here
    <?php

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

if (!empty($_POST['firstName'])) {
    $firstname = htmlentities($_POST['firstName']);
    echo $firstName;
} elseif (isset($_POST['lastName'])) {
    $lastname = htmlentities($_POST['lastName']);
    echo $lastName;
}
if (isset($_POST['userId'])) {
    $userID = htmlentities($_POST['userId']);

    echo $userId;
}

$target_dir = "C:/xampp/htdocs/test/";
if (!file_exists($target_dir)) {
//chdir($target_dir);
    mkdir($target_dir, 0777, true);
}

$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);

$moveResult = (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir));

if ($moveResult == true) {

    echo json_encode([
        "Message" => "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.",
        "Status" => "OK",
        "userId" => $_REQUEST["userId"]
    ]);
} else {
    if (isset($_REQUEST['userId'])) {
        $user = $_REQUEST['userId'];
    }
    echo json_encode([
//  echo filename;
        "Message" => "Sorry, there was an error uploading your file.",
        "Status" => "Error",
//"userId" => $user,
    ]);
}
?>