Package upload image interface on thinkphp3.2 basis

Source: Internet
Author: User
Tags control label curl rar save file custom name ftp protocol in domain to domain

Parameter configuration:::
		
		/* Picture Upload related configuration * * *
		picture_upload ' => Array (
		
				' savename ' => array (' uniqid ', ')
			,//	' RootPath ' => UPLOAD,//save path
				' maxSize '  => 10*1024*1024,//upload file size limit (0-do not limit)
				' exts '     => array (' jpg ', ' gif ', ' PNG ', ' jpeg ', ' rar ', ' zip ', ' txt ', ' swf '),///allow uploaded file suffix
				' autosub '  => true,//Auto subdirectory save file
				' thumb ' => False,//whether thumbnail processing of the picture file is required, default to False
				' SubName ' => array (' Date ', ' YMD '),
				' replace '  => true,// Whether the existence of the same name overrides
				' callback ' => false,//detect whether the file has a callback function, if there is a return file information array
		,//Picture upload related configuration (file upload class configuration)
		

Interface:::

<?php namespace Upload\controller;


Use Think\controller;
	
	Class Uploadfilecontroller extends controller{private $error _msg = ';//Upload error message Private $return = Array ();//Return Data
		Public Function Index () {$_get= array_change_key_case ($_get);//Parameter conversion lowercase $site = I (' get.site/s ', ' Default ');//Site $savename = i (' get.savename/s ', ' auto ');/upload file save rule $subname = I (' get.subname/s ', ')//Upload subdirectory save rule $size = I (' get.size/d ', ', ' int ')//upload file size limit int unit: M $output = i (' get.output/s ', ');//Data return format default array, optional JSON $is _secret = I (' get.is_secret/d ' , 0, ' int ');/whether upload to confidential path, 1 is, 0 No, default 0//definition upload main path if (!in_array ($site, C (' site ')) {//whether in the site allowed to upload $this->return
		
			
			= Array (' Status ' => ' error ', ' content ' => ' upload image site does not allow or set error ');
			if ($output = = ' json ') {$this->ajaxreturn ($this->return, ' json ');
			}else{var_dump ($this->return); exit; }else{//Judge to upload a normal directory or upload a private directory if ($is _secret = = 1) {//Upload a private directory C (' Picture_upload.rootpath ', pri_upload. $sitE. "
				
			/"); }else{//upload Normal directory C (' Picture_upload.rootpath ', UPLOAD. $site. "
				
			/");
					
			!is_dir (C (' Picture_upload.rootpath ')) {//Automatically create subdirectories mkdir (' Picture_upload.rootpath '), 0777,true);
		///Custom Save subdirectory (default date) if (!empty ($subname)) {C (' picture_upload.subname ', $subname); //define the save name of the uploaded file (default savename= ' auto ' unique generate/savename= ' string ' Custom name/savename= ' origin ', using the original name) if ($savename = = ' auto ') {
		Use unique to generate C (' picture_upload.savename ', ' uniqid ');
		}elseif ($savename = = ' origin ') {C (' picture_upload.savename ', ');
		}else{C (' Picture_upload.savename ', $savename); //define the size of the upload file (default maxsize=10m, custom size not exceeding 10M) if (!empty ($size) && $size <=10) {C (' picture_upload.maxsize ', $
		size*1024*1024);

		/* Call File Upload component Upload file/$info = $this->upload_file (' picture_upload ');
			
		/* Record picture information */if ($info) {$this->return=array (' status ' => ' success ', ' content ' => $info); else {$this->return= array (' StATUs ' => ' error ', ' content ' => $this->error_msg);
		} if ($output = = ' json ') {/* Returns the JSON data * * * * $this->ajaxreturn ($this->return, ' json ');
		}else{var_dump ($this->return); exit;  /** * File Upload * @param array $files The list of files to upload (usually $_files array) * @param array $setting File upload configuration * @param String $driver Upload driver name * @param array $config upload driver configuration * @return The information after successful upload of the array file */Public function UPL
		Oad_file ($config) {* * * Upload file/import (' ORG.Net.UploadFile ');
		
		$upload = new \think\upload ($config)///Instantiate upload class//upload file $info = $upload->upload ();
			if (! $info) {//Upload error message error messages $this->error_msg = $upload->geterror ();
		return false;

		}else{//Upload successfully uploaded file information return $info; }}}?>

Read private path Picture::

<?php/** * Access to private files * * * * * * * namespace Download\controller;


Use Think\controller; 	Class Downloadfilecontroller extends controller{private $status = ' ERROR ';		Return the state private $type = ' text/html ';//Return the MIME type of the data private $content = '; Returns the data content//Entry public Function index () {$path = i (' path/s ', ');//need to read the file path under private folder $timestamp = I ('
			Timestamp ', 0, ' int ');//user Invoke interface timestamp (for authentication) if (empty ($path)) {//Validate request path $this->content = "Missing request file path";
		$this->flush ();
			
			}//Authentication if ($this->checksignature ($path, $timestamp)) {//authentication successful $full _path = Pri_upload. $path;//Request File full path if (Is_file ($full _path)) {//request file exists $mime = $this->get_mime ($full _path);//Get file MIME type $content = f
				Ile_get_contents ($full _path);//file contents $this->status = ' success ';
				$this->type = $mime;
				
				$this->content= $content;
			
			$this->flush ();
				}else{$this->content = "No requested file found";
			$this->flush (); }}else{//validation failed $this->content = "validation Failed";
		$this->flush (); }/** Verify request is legitimate * $path the requested private file path * $timestamp user-carried timestamp/private function Checksignatur E ($path, $timestamp) {$key = C (' key ');//Key $signature =i (' signature/s ', ');//use interface to handle these three parameters in the same way. Construct validation string//encryption/ The verification process is as follows://1. Sort key, path, timestamp three parameters in dictionary order//2. Concatenation of three parameter strings into a string for SHA1 encryption//3.   The developer obtains the encrypted string to compare with the signature, identifies the request source to allow $TMPARR = Array ($key, $path, $timestamp);               The parameters are grouped into groups of sort ($TMPARR, sort_string);             Dictionary order $tmpStr = implode ($TMPARR);
			
		
		Concatenation of three parameter strings into a string for SHA1 encryption $TMPSTR = SHA1 ($TMPSTR);
		if ($tmpStr = = = $signature) {//Verify successful return true;
		}else{//validation failed return false; }/** * OUTPUT (serialized) * Status State Success Successful/ERROR failure * Type return data MIME types * Content return Data contents * * PR ivate function Flush () {$return =array (' status ' => $this->status, ' type ' => $this->type, ' Conten T ' => $this->content);
		Echo Serialize ($return);
	Exit /** * Get File Mime-type * $full _path Request File Full path */Private Function Get_mime ($full _path) {$ext = Strtolow
				ER (pathinfo ($full _path, pathinfo_extension))//Get file suffix name switch ($ext) {case ' jpg ': return ' image/jpeg ';
			Break
				Case ' JPEG ': return ' image/jpeg ';
			Break
				Case ' PNG ': return ' image/png ';
			Break
				Case ' gif ': return ' image/gif ';
			Break
				Case ' Zip ': return ' application/octet-stream ';
			Break
				Case ' rar ': return ' application/octet-stream ';
			Break
				Case ' SWF ': return ' Application/x-shockwave-flash ';
			Break
				Case ' txt ': return ' text/plain ';
			Break
						
		Default:return ' text/html '; }}}?>

Call Get private picture simple::

<?php//Sample Code SDK//Call http://www.upload.com/Download/DownloadFile/index.html interface $key = ' 5dbb068f303f8d60076c9a8a4b  6bad8c ';						  Authentication key $timestamp =time ();					  Time stamp $path =$_get[' path ']; The path of the request file, Default/test/test.jpg relative to the private folder $url = "Http://www.upload.com/Download/DownloadFile/index.html";
	Interface URL if (empty ($path)) {return false; ///combination verification condition//encryption/verification process as follows://1. Sort key, path, timestamp three parameters in dictionary order//2. Concatenation of three parameter strings into a string for SHA1 encryption//3.
	The developer obtains the encrypted string to compare with the signature, identifies the request source to allow $TMPARR = Array ($key, $path, $timestamp);
	Sort ($TMPARR, sort_string);
	$TMPSTR = implode ($TMPARR);
		
	$signature = SHA1 ($TMPSTR); Curl->post Data $data = Array (' key ' => $key, ' timestamp ' => $timestamp, ' path ' => $path, ' signature ' =
	
	
	
	> $signature);
	Gets the data and deserializes $res = Cpost ($url, $data);
	
	$data = Unserialize ($res);
		
	if ($data [' Status ']== ' ERROR ') {//Read file failure echo $data [' content ']; }else{//Success if ($data [' type ']== ' application/octet-sTream ') {///If it is rar zip etc, download it as an attachment $ext = Strtolower (PathInfo ($path, pathinfo_extension)); $file _name = ' dowload. '					$ext; Download the file name Header at save time ("content-disposition:attachment;
		
		Filename= ". $file _name);
		Header ("content-type:{$data [' Type ']}");
		
		
	echo $data [' content '];

	
	
	} exit; * * Curl post Analog submit data function/functions Cpost ($url, $data, $timeout =10) {$curl = Curl_init ();//Start a Curl session Curl_seto PT ($curl, Curlopt_url, $url); Address curl_setopt ($curl, curlopt_useragent, $_server[' http_user_agent ') to be accessed; Analog user-used browser curl_setopt ($curl, curlopt_followlocation, 1); Use automatic jump curl_setopt ($curl, Curlopt_autoreferer, 1); Automatically set Referer curl_setopt ($curl, Curlopt_post, 1); Send a regular POST request curl_setopt ($curl, Curlopt_postfields, Http_build_query ($data)); Post-Submitted packet curl_setopt ($curl, Curlopt_timeout, $timeout); Set timeout limit to prevent dead loop curl_setopt ($curl, Curlopt_header, 0); Displays the contents of the header area returned curl_setopt ($curl, Curlopt_returntransfer, 1); Gets the information toThe form of the file stream returns $tmpInfo = Curl_exec ($curl); Execute action if (Curl_errno ($curl)) {echo ' errno: '. Curl_error ($curl);//Catch Exception} curl_close ($curl); Closes the curl session return $tmpInfo; Return Data}?>


When it comes to uploading images across domains, there is a problem with security issues, security sandbox conflicts: this is caused by the security of flash data across domains.

Flash cross-domain policy file crossdomain.xml configuration detailed

0x01 Introduction

Configuration of 0x02 Crossdomain.xml

0X03 Summary

0x01 Introduction

The only limiting policy for flash when it is Cross-domain is the Crossdomain.xml file, which limits whether Flash can read and write data across domains and where to allow data to be read and written across domains.

SWF files located in the www.a.com domain to access www.b.com files, the SWF first checks to see if there are crossdomain.xml files in the www.b.com server directory, and if not, the access is unsuccessful; If the Crossdomain.xml file exists and the inside setting allows www.a.com domain access, then communication is normal. So to enable flash to transfer data across the domain, the key is crossdomain.xml.

This article will focus on the configuration method of crossdomain.xml files and the effects of different configurations on Flash cross-domain.

configuration of 0x02 crossdomain.xml

 

Placement of 2.1 crossdomain.xml

Since Flash 10, if cross-domain access is required, the Crossdomain.xml file must be placed under the root directory of the target domain, and the configuration file under that root is called the Master policy file . If no master policy file exists, the domain will prohibit flash Cross-domain requests from any third party domain.

The Master policy file controls the Cross-domain access to the entire station.

You can also place a crossdomain.xml configuration file that takes effect only on the path and its subpath in a single path, which needs to be loaded using the following statement in the Flash as script: [Specific load permission restrictions will be affected by the Site-control policy in the following text]

Security.loadpolicyfile ("Http://www.xxx.com/subdir/crossdomain.xml")

the Collocation method and influence of 2.2 crossdomain.xml

Crossdomain.xml must strictly adhere to the XML syntax, have and only one root node cross-domain-policy, and does not contain any attributes. only the following child nodes can be included under this root node: Site-control, Allow-access-from, Allow-access-from-identity, Allow-http-request-headers-from. The four child nodes are described separately below:

2.2.1site-control: Verify that you can allow additional policy files to be loaded by checking the attribute values for that node. [This node is automatically ignored if the policy file is not a master policy file]

 

Each Site-control label has and has only attribute permitted-cross-domain-policies, which specifies the load policy relative to other policy files that are not the main policy file. The Permitted-cross-domain-policies property value has the following conditions:

None: No policy files are allowed to be loaded using the Loadpolicyfile method, including this master policy file.

master-only: only the main policy file [default value] is allowed.

By-content-type: Only the Loadpolicyfile method is allowed to load the HTTP/HTTPS protocol Content-type to text/ X-cross-domain-policy file as a cross-domain policy file.

by-ftp-filename: Only use the Loadpolicyfile method to load files with file name Crossdomain.xml under the FTP protocol as a Cross-domain policy file.

All : You can use the Loadpolicyfile method to load any file on the target domain as a cross-domain policy file, or even a JPG can be loaded as a policy file. [Use this option to be xx.] ]

If you need to make a separate flash cross-domain restriction policy for a subdirectory of a Web site, you must make the appropriate Site-control settings in the main policy file.

The following example configures the Site-control policy to load other text/x-cross-domain-policy files on this server as a Cross-domain policy file.

<cross-domain-policy>

<site-control permitted-cross-domain-policies= "By-content-type"/>

</cross-domain-policy>

2.2.2 Allow-access-from: Verify the source domain of the Flash file that can read the contents of this domain by checking the attribute value of the node.

The Allow-access-from label has three properties:

Domain: This property specifies an exact IP address, an exact domain, or a wildcard value field (any domain). Only domains specified in domain have permissions to read content in this domain through flash.

You can use one of the following two ways to represent a wildcard value field:

1 a single asterisk (*), such as: <allow-access-fromdomain= "*"/>, to match all domains and all IP addresses, at which point any domain can access the contents of this domain across domains. [This is extremely unsafe.] ]

2 followed by the asterisk of the suffix, indicating that only those fields that end with the specified suffix are matched, such as *.qq.com can match game.qq.com, qq.com. An invalid configuration, such as www.q*.com or www.qq.*.

Tips: when domain is designated as the IP address, only accept requests to use the IP as a URL to access the source request [at this time the IP address is also equivalent to a domain name], When domain is set to 192.168.1.100, it is permissible to use http://192.168.1.100/flash.swf to request the content of the field, but to access it using the domain name www.a.com pointing to 192.168.1.100 [http ://www.a.com/flash.swf] will be rejected because Flash does not know DNS resolution:)

to-ports: This property value indicates that the socket connection port range that reads the contents of this domain is allowed to be accessed. You can use a form such as to-ports= "1100,1120-1125" to qualify a port range, or you can use a wildcard character (*) to indicate that all ports are allowed.

Secure: This property value indicates whether the information is transmitted encrypted. Secure defaults to True when the Crossdomain.xml file is loaded with HTTPS. Flash is not allowed to transmit non-HTTPS encrypted content at this time. If set to false manually, it allows flash to transmit non-HTTPS encrypted content.

The following example is configured to allow all level two domain names [including qq.com itself] under all qq.com to access content in this domain through HTTPS.

<cross-domain-policy>

<allow-access-from domain= "*.qq.com" secure= "true"/>

</cross-domain-policy>

2.2.3allow-access-from-identity: This node configures a Cross-domain access policy to allow a source with a specific certificate to access resources on this domain across domains. Each allow-access-from-identity node can contain up to one signatory child node. Shaped like:

<allow-access-from-identity>

<signatory>

<certificate

Fingerprint= "01:23:45:67:89:ab:cd:ef:01:23:45:67:89:ab:cd:ef:01:23:45:67"

fingerprint-algorithm= "Sha-1"/>

</signatory>

</allow-access-from-identity>

2.2.4allow-http-request-headers-from: This node authorizes the third party domain flash to send a user-defined HTTP header to this domain.

The Allow-access-from node authorizes the third domain to extract data from this domain, while the Allow-http-request-headers-from node authorizes the Third-party domain to send the data to the domain as an HTTP header. [In short, allow-access-from is to control Read permissions, Allow-http-request-headers-from is to control write permissions in the form of HTTP headers]

Allow-http-request-headers-from contains three properties:

domain: the function and parameter format is similar to domain in the Allow-access-from node.

headers: A comma-separated list of HTTP headers that are allowed to be sent. The available wildcard characters (*) represent all HTTP headers.

Secure: function and usage are the same as secure in allow-access-from nodes.

In the following example, any field can send SOAPAction headers to the current domain:

<cross-domain-policy>

<allow-http-request-headers-from domain= "*" headers= "SOAPAction"/>

</cross-domain-policy>

0x03 Summary

Incorrect crossdomain.xml policies can lead to serious security issues, such as information disclosure, CSRF, and so on. As can be seen from the foregoing, we should focus on the following points when conducting security assessments:

1 allow-access-from Label domain attribute detection: The domain attribute should be set on demand according to the minimized principle, allowing only trusted sources to request the contents of this field across domains. prohibit setting this property value to " * ".

2 allow-http-request-headers-from Label domain attribute detection: Domain property should be set on demand according to the minimized principle, allowing only trusted sources to send content across domains in this domain. prohibit setting this property value to " * ".

3 Site-control Label permitted-cross-domain-policies attribute detection: According to the actual needs and feasibility of the business, the property to make the appropriate settings. prohibit setting this property value to " All ".

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE cross-domain-policy SYSTEM
"HTTP://WWW.MACROMEDIA.COM/XML/DTDS/CROSS-DOMAIN-POLICY.DTD" >
< cross-domain-policy>
<site-control permitted-cross-domain-policies= "master-only"/>
< Allow-access-from domain= "*"/> <allow-http-request-headers-from domain= "*" headers=
"*"/>
</ Cross-domain-policy>


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.