很多站长朋友们都不太清楚php上传类跨域,今天小编就来给大家整理php上传类跨域,希望对各位有所帮助,具体内容如下:
本文目录一览: 1、 php手把手教你做网站(二十九)thinkphp6部署多个数据库 2、 PHP如何写一个给外人上传数据的接口? 3、 PHP跨域上传的几种方法 4、 用webuploader怎么解决跨域上传文件的问题 php手把手教你做网站(二十九)thinkphp6部署多个数据库前边介绍了负载均衡,mysql同步,接下来介绍tp6分布式部署多个数据库,实现读写分离。
tp6的分布式部署读和写仍然是一个系统,这里我们分开操作,给用户展示的就是从数据库,后端添加文章就是主库,然后同步到从库。
1、配置数据库链接参数
目标:实现随机使用数据库展示信息,只是读操作。
测试:前台可以读取表中内容(存放的不一致),查看是否是随机显示的。
打开.env文件进行编辑
说明:
2、编辑database.php
找到deploy设置为1分布式部署,下边不要改,都是读,写入的也就是后端的我们单独建站连接主库。
配置完成,tp6使用的是mt_rand取随机数判断使用哪个数据库。
3、数据库交互写操作
比如浏览量没必要每次都去更新数据库,可以先使用redis缓存,存够1000的整数倍,再去更新数据库。
4、后台独立,也就是写
可以前后端分离,单独做一个网站(没有前端)使用ip访问或者独立的域名连接后台。
5、上传附件(jquery ajax跨域上传)
使用了nginx负载均衡,肯定是多个一样的网站,如果图片存放到一个站,别的就不能访问了,可以单独设置一个附件(压缩包,图片等)服务器,可以使用二级域名连接,这就要求我们上传附件的时候,是上传到附件服务器。
jqueryURL
API控制器apdpic方法
说明:
也可以先传到后台服务器然后使用(php)ftp上传,或者是通过curl上传到附件服务器,感觉那样毕竟麻烦,直接设置跨域会比较简单。
也测试了使用jsonp跨域,但是不能上传附件。
6、thinkphp6实现读写分离(在一个站点)
我个人是不喜欢这样的,负载均衡应该是均衡地读,也就是前台单独一个站点,后端的写是另一个独立的站点,看个人喜好吧。
独立后台的优点:可以提升安全性,因为我们的后台网址是不公开的,避免用户猜测一些后台的信息。
.env配置按照1所述编辑,默认第一个是主库。
database.php
愿大家在新的一年心想事成,万事如意!!!
PHP如何写一个给外人上传数据的接口?接口的流程.
建立控制器(访问地址)->审核访问者身份(token)->验证提交数据是否符合类型(validate
)->处理接收数据(逻辑流程)->返回结果(json字符串).
其中要注意是否存在跨域,如果跨域要做跨域处理,例如返回jsonp.
PHP跨域上传的几种方法方法一:
文件夹:/home/web/attachments
虚拟二级目录到/home/web/zxsv/下(支持同局域网的服务器)
这样多个子域名进行上传的设计时,只需要attachments目录映射为相关的域名的二级目录,这样就可实现多个子域名共享一个附件服务器了,这种方法最好是用局域网中的附件服务器,这样流量是分开的,当然访问附件的域名是apache,ngixn,IIS等的虚拟二级目录就不说了,好处是现有程序不做任何修改,唯一坏处就是两台服务器必须在一个局域网中,当然你用单台也就没这个问题了
方法二:FTP同步更新
PHP是支持FTP的,给个FTP类里面(不是我写的,只是加了个建立多级目录),自己看着办吧,上传后调用FTP类,同步到FTP服务器中,好处是现有程序只需要在上传那段加上FTP上传就行了,坏处就是一定要支持FTP
<?php
$ftp=new Ftp;
//print_r($ftp->nlist(”"));
$ftp->makedir(”3″);
//$ftp->put(”comment.php”,”1.txt”);
$ftp->bye();
//R FTP 处理;
class ftp {
var $ftpUrl = ‘’;
var $ftpUser = ‘zxsv’;
var $ftpPass = ‘111111′;
var $ftpDir = ‘/zxsv/’;
var $ftpR = ”; //R ftp资源;
var $status = ”;
//R 1:成功;2:无法连接ftp;3:用户错误;
function ftp() {
if ($this->ftpR = ftp_connect($this->ftpUrl, 21)) {
if (ftp_login($this->ftpR, $this->ftpUser, $this->ftpPass)) {
if (!empty($this->ftpDir)) {
ftp_chdir($this->ftpR, $this->ftpDir);
}
ftp_pasv($this->ftpR, true);//R 启用被动模式;
$status = 1;
} else {
$status = 3;
}
} else {
$status = 2;
}
}
//R 切换目录;
function cd($dir) {
return ftp_chdir($this->ftpR, $dir);
}
//建立目录
function mkdir($dir){
return ftp_mkdir($this->ftpR, $dir);
}
function makedir($dir) {
if(!$dir) return 0;
$dir = str_replace( “\\”, “/”, $dir );
$mdir = “”;
foreach(explode( “/”, $dir ) as $val ) {
$mdir .= $val.”/”;
if( $val == “..” || $val == “.” ) continue;
if(!@mkdir($mdir)){
echo “创建目录 [".$mdir."]失败.”;
//exit;
}
}
return true;
}
//删除目录
function rmdir($dir){
return ftp_rmdir($this->ftpR, $dir);
}
//R 返回当前路劲;
function pwd() {
return ftp_pwd($this->ftpR);
}
//R 上传文件;
function put($localFile, $remoteFile = ”) {
if ($remoteFile == ”) {
$remoteFile = end(explode(’/', $localFile));
}
$res = ftp_nb_put($this->ftpR, $remoteFile, $localFile, FTP_BINARY);
print_r($res);
while ($res == FTP_MOREDATA) {
$res = ftp_nb_continue($this->ftpR);
}
if ($res == FTP_FINISHED) {
return true;
} elseif ($res == FTP_FAILED) {
return false;
}
}
//R 下载文件;
function get($remoteFile, $localFile = ”) {
if ($localFile == ”) {
$localFile = end(explode(’/', $remoteFile));
}
if (ftp_get($this->ftpR, $localFile, $remoteFile, FTP_BINARY)) {
$flag = true;
} else {
$flag = false;
}
return $flag;
}
//R 文件大小;
function size($file) {
return ftp_size($this->ftpR, $file);
}
//R 文件是否存在;
function isFile($file) {
if ($this->size($file) >= 0) {
return true;
} else {
return false;
}
}
//R 文件时间
function fileTime($file) {
return ftp_mdtm($this->ftpR, $file);
}
//R 删除文件;
function unlink($file) {
return ftp_delete($this->ftpR, $file);
}
function nlist($dir = ‘/service/resource/’) {
return ftp_nlist($this->ftpR, $dir);
}
//R 关闭连接;
function bye() {
return ftp_close($this->ftpR);
}
}
?>
用webuploader怎么解决跨域上传文件的问题最近研究了下大文件上传的方法,找到了webuploader js 插件进行大文件上传,大家也可以参考这篇文章进行学习:《Web Uploader文件上传插件使用详解》使用使用webuploader分成简单直选要引入<!--引入CSS--> <link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css"> <!--引入JS--> <script type="text/javascript" src="webuploader文件夹/webuploader.js"></script> HTML部分<div id="uploader" class="wu-example"> <!--用来存放文件信息--> <div id="thelist" class="uploader-list"></div> <div class="btns"> <div id="picker">选择文件</div> <button id="ctlBtn" class="btn btn-default">开始上传 </button> </div> </div> 初始化Web UploaderjQuery(function() { $list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', uploader; uploader = WebUploader.create({ // 不压缩image resize: false, // swf文件路径 swf: 'uploader.swf', // 文件接收服务端。 server: upload.php, // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: '#picker', chunked: true, chunkSize:2*1024*1024, auto: true, accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); upload.php处理以下是根据别人的例子自己拿来改的php 后台代码header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit; // finish preflight CORS requests here } if ( !empty($_REQUEST[ 'debug' ]) ) { $random = rand(0, intval($_REQUEST[ 'debug' ]) ); if ( $random === 0 ) { header("HTTP/1.0 500 Internal Server Error"); exit; } } // header("HTTP/1.0 500 Internal Server Error"); // exit; // 5 minutes execution time @set_time_limit(5 * 60); // Uncomment this one to fake upload time // usleep(5000); // Settings // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload"; $targetDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material_tmp'; $uploadDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material'; $cleanupTargetDir = true; // Remove old files $maxFileAge = 5 * 3600; // Temp file age in seconds // Create target dir if (!file_exists($targetDir)) { @mkdir($targetDir); } // Create target dir if (!file_exists($uploadDir)) { @mkdir($uploadDir); } // Get a file name if (isset($_REQUEST["name"])) { $fileName = $_REQUEST["name"]; } elseif (!empty($_FILES)) { $fileName = $_FILES["file"]["name"]; } else { $fileName = uniqid("file_"); } $oldName = $fileName; $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName; // Chunking might be enabled $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1; // Remove old temp files if ($cleanupTargetDir) { if (!is_dir($targetDir) !$dir = opendir($targetDir)) { die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); } while (($file = readdir($dir)) !== false) { $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; // If temp file is current file proceed to the next if ($tmpfilePath == "{$filePath}_{$chunk}.part" $tmpfilePath == "{$filePath}_{$chunk}.parttmp") { continue; } // Remove temp file if it is older than the max age and is not the current file if (preg_match('/\.(partparttmp)$/', $file) (@filemtime($tmpfilePath) < time() - $maxFileAge)) { @unlink($tmpfilePath); } } closedir($dir); } // Open temp file if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } if (!empty($_FILES)) { if ($_FILES["file"]["error"] !is_uploaded_file($_FILES["file"]["tmp_name"])) { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } // Read binary input stream and append it to temp file if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } } else { if (!$in = @fopen("php://input", "rb")) { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } } while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($out); @fclose($in); rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part"); $index = 0; $done = true; for( $index = 0; $index < $chunks; $index++ ) { if ( !file_exists("{$filePath}_{$index}.part") ) { $done = false; break; } } if ( $done ) { $pathInfo = pathinfo($fileName); $hashStr = substr(md5($pathInfo['basename']),8,16); $hashName = time() . $hashStr . '.' .$pathInfo['extension']; $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName; if (!$out = @fopen($uploadPath, "wb")) { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } if ( flock($out, LOCK_EX) ) { for( $index = 0; $index < $chunks; $index++ ) { if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) { break; } while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($in); @unlink("{$filePath}_{$index}.part"); } flock($out, LOCK_UN); } @fclose($out); $response = [ 'success'=>true, 'oldName'=>$oldName, 'filePaht'=>$uploadPath, 'fileSize'=>$data['size'], 'fileSuffixes'=>$pathInfo['extension'], 'file_id'=>$data['id'], ]; die(json_encode($response)); } // Return Success JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); 以上就是本文的全部内容,希望对大家的学习有所帮助。
关于php上传类跨域的介绍到此就结束了,不知道本篇文章是否对您有帮助呢?如果你还想了解更多此类信息,记得收藏关注本站,我们会不定期更新哦。
查看更多关于php上传类跨域 php设置跨域访问的详细内容...