我使用HTML表单来上传文件。然后我使用文件数组将它们转换为变量,然后我试图读取这个变量。
我的代码在这里:
if(isset($_POST['upload'])) {
$image = $_FILES['sfile'];
$contents = file_get_contents($image);
$links = explode(',',$contents);
echo $links[0];
}
从以下形式
调用<html>
<head>
<title> Trial </title>
</head>
<body>
<form align="center" method="post" action="example.php" enctype="multipart/form-data">
Upload File Here : <input type="file" name="sfile"><br>
<input type="submit" name ="upload" value="Upload">
</form>
</body>
</html>
您应该从tmp_name
中读取它,参见下面的代码:
if (!empty($_FILES['sfile'])) {
$sfile = $_FILES['sfile'];
if ($sfile['error'] != UPLOAD_ERR_OK) {
// output error here
} else {
$contents = file_get_contents($sfile['tmp_name']);
$links = explode(',', $contents);
echo $links[0];
}
}
$_FILES
有这样的数组格式:
$_FILES['myfile']['name'] - the original file name
$_FILES['myfile']['type'] - the mime type
$_FILES['myfile']['size'] - the file size
$_FILES['myfile']['tmp_name'] - temporary filename
$_FILES['myfile']['error'] - error code
错误码,来自http://php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_OK值:0;没有错误,文件上传成功。
UPLOAD_ERR_INI_SIZE取值:1;上传的文件超过php.ini中的Upload_max_filesize指令。
UPLOAD_ERR_FORM_SIZE Value: 2;上传的文件超过在HTML表单中指定的MAX_FILE_SIZE指令。
UPLOAD_ERR_PARTIAL Value: 3;上传的文件只有一部分上传。
UPLOAD_ERR_NO_FILE值:4;没有文件上传。
UPLOAD_ERR_NO_TMP_DIR值:6;丢失临时文件夹。介绍了
UPLOAD_ERR_CANT_WRITE Value: 7;向磁盘写入文件失败。在PHP 5.1.0中引入。
UPLOAD_ERR_EXTENSION值:8;一个PHP扩展停止了该文件上传。PHP没有提供一种方法来确定是哪个扩展导致的文件上传停止;检查加载的扩展列表Phpinfo()可能会有所帮助。在PHP 5.2.0中引入。
查看http://php.net/manual/en/features.file-upload.post-method.php
声明$image的地方应该是$_FILES['sfile']['tmp_name'];
上传的文件在服务器上存储的临时文件名。