pdf.js 在IE10对象不支持“set”属性或方法 5C

在pdfjs官方找到是支持到ie9 但看了一些资料说对ie10里面有挺多东西支持不了。
前端时间搞了个东西,使用pdf.js加载pdf文件,在ie11下读取就没问题,但在IE10里面就有内容丢失了,显示空白
图片说明

看哪位大神可以给看看,在浏览器控制台里报了一个错,只有ie10报错了
图片说明

有没有熟悉pdf.js的可以给出一些建议和意见

自己也跟踪了一下,跟unit8Array 有关系,应该是对这个对象不怎么兼容
兼容跳到ie9 就显示其他错了。
图片说明

很着急!!!!!!!!!!!!!!!!在线等!!!!!!!!!!!!!!!

1个回答

ie10不支持,只能用api模拟但是很慢,可以降级为flashpager等替代方案显示pdf

Zlero
zlero 只有这一种解决办法么?
10 个月之前 回复
Zlero
zlero 有关于这方面的案例么?或给个思路,目前都是提问的,没有很具体的方案。
10 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

使用ajax在浏览器中内联显示PDF

<div class="post-text" itemprop="text"> <p>I know that this question is already asked many times by different ways. But still i am not able to figure out the answer. I mean i did not find a proper descriptive answer.</p> <p>I use mpdf library to generate PDF. I post some data of hidden fields to a PHP script by means of ajax.</p> <p>Following are the code snippets.</p> <pre><code>//ajax_file $("#button_id").click(function(e){ var table_clone=$("#table_id").clone(); var tableData=table_clone.prop('outerHTML');//html for pdf generation dataString='page='+tableData; $.ajax({ type: 'POST', url: 'pdfgenerator.php', data: dataString, cache: false, success: function(response) { //what to do here in order to display pdf }, error: function(............){ . . } }); }); </code></pre> <p>PHP Script</p> <pre><code>//pdfgenerator.php &lt;?php include('../mpdf/mpdf.php'); if(/*checking post items are set*/) { //retriving post items $mpdf=new mPDF('c','A4-L'); $mpdf-&gt;WriteHTML($tableData); $mpdf-&gt;output('xyz.pdf','I'); exit; } ?&gt; </code></pre> <p>Following are my constraints</p> <p>-&gt; I don't want to save file permanently on server (which is possible by means of 'F' option in output()). </p> <p>-&gt; I have to display it in browser from where it can be downloaded.</p> <p>PHP script works correctly if called without ajax. Hence it returns correct data but i am unable to display it in pdf inside the browser.</p> <p>While searching for answers i found that it is not possible by means of ajax. so is there any way around by doing something in PHP or javascript. Please provide a descriptive answer.</p> <p>Thanks,</p> </div>

如何将ajax结果保存为pdf文件?

<div class="post-text" itemprop="text"> <p>Trying to download a file which is dynamically generated by the the data posted. I have the results coming back. I'm just not sure how I can save the results into a proper file locally once the information (stream) is returned from the server. </p> <p>Here is the ajax call:</p> <pre><code>function download_pdf(){ alert("made it" + result_array); $.ajax({ type: "POST", url: "report_generation/downlaod_pdf.php", data: { result_array: result_array }, success: function(results){ alert(results); }, error: function(xmlHttpRequest, status, error){ alert(xmlHttpRequest + "| ajax failure: could not download haq report | " + status + " | error:" + error); var xmlHttpRequestStr = ""; for(var x in xmlHttpRequest) xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x]; alert(xmlHttpRequestStr); } }); } </code></pre> <p>This function is called from a hyperlink like so, and the success method is returning...</p> <pre><code>&lt;a class="haq_button" href="javascript:download_pdf()"&gt;&lt;span&gt;Download Report As PDF&lt;/span&gt;&lt;/a&gt; </code></pre> <p>UPDATE: Here is a snippet of code from the file generation in download_pdf</p> <pre><code>// set the headers, prevent caching header("Pragma: public"); header("Expires: -1"); header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0"); header("Content-Disposition: attachment; filename=\"$file_name\""); // set appropriate headers for attachment or streamed file if ($is_attachment) { header("Content-Disposition: attachment; filename=\"$output_file_name\""); } else { header('Content-Disposition: inline;'); header('Content-Transfer-Encoding: binary'); } // set the mime type based on extension, add yours if needed. $ctype_default = "application/octet-stream"; $content_types = array( "exe" =&gt; "application/octet-stream", "pdf" =&gt; "application/pdf", "zip" =&gt; "application/zip", "mp3" =&gt; "audio/mpeg", "mpg" =&gt; "video/mpeg", "avi" =&gt; "video/x-msvideo", ); $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default; header("Content-Type: " . $ctype); //check if http_range is sent by browser (or download manager) if(isset($_SERVER['HTTP_RANGE'])) { list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2); if ($size_unit == 'bytes') { //multiple ranges could be specified at the same time, but for simplicity only serve the first range //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt list($range, $extra_ranges) = explode(',', $range_orig, 2); } else { $range = ''; header('HTTP/1.1 416 Requested Range Not Satisfiable'); exit; } } else { $range = ''; } //figure out download piece from range (if set) list($seek_start, $seek_end) = explode('-', $range, 2); //set start and end based on range (if set), else set defaults //also check for invalid ranges. $seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1)); $seek_start = (empty($seek_start) || $seek_end &lt; abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0); //Only send partial content header if downloading a piece of the file (IE workaround) if ($seek_start &gt; 0 || $seek_end &lt; ($file_size - 1)) { header('HTTP/1.1 206 Partial Content'); header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size); header('Content-Length: '.($seek_end - $seek_start + 1)); } else header("Content-Length: $file_size"); header('Accept-Ranges: bytes'); set_time_limit(0); fseek($file, $seek_start); while(!feof($file)) { print(@fread($file, 1024*8)); ob_flush(); flush(); if (connection_status()!=0) { @fclose($file); exit; } } // file save was a success @fclose($file); exit; </code></pre> </div>

为什么我的pdf被重命名?

<div class="post-text" itemprop="text"> <p>I have a site that clients can upload pdf's with product information.. For some reason, the pdf's are getting renamed to the 'Office' which will not work as there are many pdf's being uploaded. How do I keep the name of the pdf being uploaded? Any advice would be appreciated.</p> <p>Here is my code.</p> <pre><code> session_start(); include('../config.php'); error_reporting(0); // SESSION CHECK SET OR NOT if(!isset($_SESSION['admin'])) { header('location:index.php'); } if(isset($_POST['submit'])) { //When no image is selected if($_FILES['image']['name']=='') { $query = "INSERT INTO `products` SET Office = ?,Description = ?,Unit = ?,Generic = ?,Category=?"; $parameters = array($_POST['Office'],$_POST['Description'],$_POST['Unit'],$_POST['Generic'],$_POST['Category']); }else{ $allowed_filetypes = array('jpg','jpeg','png','gif','pjpeg'); $ext = end((explode(".", $_FILES['image']['name']))); $imageName = $_POST['Office'].'.'.$ext; $path = "../".$path.$imageName; $tmp = $_FILES['image']['tmp_name']; if(!in_array($ext,$allowed_filetypes)) { $error = 'danger'; $errormsg = "You uploaded wrong image format"; }else { $moved = move_uploaded_file($tmp,$path); //Resize the uploaded avatar resize($path , '150', '150', $ext); $query = "INSERT INTO `products` SET Office = ?,Description = ?,Unit = ?,Generic = ?,image=?,Category=?"; $parameters = array($_POST['Office'],$_POST['Description'],$_POST['Unit'],$_POST['Generic'],$imageName,$_POST['Category']); } } // PDF UPLOAD $allowed_filetypes_pdf = array('pdf'); $ext_pdf = end((explode(".", $_FILES['pdf']['name']))); $pdfName = $_POST['Office'].'.'.$ext_pdf; $path = "../".$path_pdf.$_POST['Office']."/"; //$path_pdf = "../".$path_pdf.$pdfName; $pdf=$path_pdf.$pdfName; $tmp_pdf = $_FILES['pdf']['tmp_name']; if(!in_array($ext_pdf,$allowed_filetypes_pdf)) { $error = 'danger'; $errormsg = "You uploaded wrong image format"; }else { $moved1 = move_uploaded_file($tmp_pdf, $path_pdf); $query = "INSERT INTO `products` SET Office = ?,Description = ?,Unit = ?,Generic = ?,image=?,PDF_Path=?,Category=?"; $parameters = array($_POST['Office'],$_POST['Description'],$_POST['Unit'],$_POST['Generic'],$imageName,$pdf,$_POST['Category']); } $statement = $db-&gt;prepare($query); $statement-&gt;execute($parameters); $error = 'success'; $errormsg = "New User added successfully"; } $query = "select DISTINCT(Office) from userinfo "; $statement = $db-&gt;prepare($query); $statement-&gt;execute(); ?&gt; </code></pre> <p>HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8 lt-ie7"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7]&gt; &lt;html class="no-js lt-ie9 lt-ie8"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="no-js lt-ie9"&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html class="no-js"&gt; &lt;!--&lt;![endif]--&gt; &lt;head&gt; &lt;title&gt;Add Product&lt;/title&gt; &lt;?php include "include/head.php" ?&gt; &lt;link rel="stylesheet" href="../assets/plugins/fileupload/bootstrap-fileupload.css" type="text/css" /&gt; &lt;link rel="stylesheet" href="../assets/css/custom.css" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;?php include 'include/header.php'; ?&gt; &lt;?php include 'include/topMenu.php'; ?&gt; &lt;?php include 'include/sidebar.php'; ?&gt; &lt;div id="content"&gt; &lt;div id="content-header"&gt; &lt;h1&gt;Add New Product&lt;/h1&gt; &lt;/div&gt; &lt;!-- #content-header --&gt; &lt;div id="content-container"&gt; &lt;?php if($errormsg){ echo "&lt;div class='alert alert-$error' style='padding-left: 5px;'&gt;$errormsg&lt;/div&gt;"; }?&gt; &lt;div class="row"&gt; &lt;div class="col-sm-6"&gt; &lt;div class="portlet"&gt; &lt;div class="portlet-header"&gt; &lt;h3&gt;&lt;i class="fa fa-plus-square"&gt;&lt;/i&gt; Add Product &lt;/h3&gt; &lt;/div&gt; &lt;!-- /.portlet-header --&gt; &lt;div class="portlet-content"&gt; &lt;div id="error"&gt;&lt;/div&gt; &lt;form id="validate-basic" action="" data-validate="parsley" method="post" class="form parsley-form ajax_form" enctype="multipart/form-data"&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Office&lt;/label&gt; &lt;select class="form-control" name="Office"&gt; &lt;?php while($row = $statement-&gt;fetch(PDO::FETCH_ASSOC)) { echo "&lt;option value='{$row['Office']}'&gt;{$row['Office']}&lt;/option&gt;"; }?&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="input-group"&gt; &lt;h5 style="font-weight: 700; font-size: 13px;"&gt;Please select PDF&lt;/h5&gt; &lt;div class="input-group-btn"&gt; &lt;input type="file" name="pdf"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group" id="images"&gt; &lt;label for="avatar"&gt;Product Image&lt;/label&gt; &lt;div class="fileupload fileupload-new" data-provides="fileupload"&gt; &lt;div class="fileupload-new thumbnail" style="width: 180px; height: 150px;"&gt;&lt;img src="../images/avatar/noimage.gif" alt="Product Avatar" /&gt;&lt;/div&gt; &lt;div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 150px; max-height: 200px; line-height: 20px;"&gt;&lt;/div&gt; &lt;div&gt; &lt;span class="btn btn-default btn-file"&gt;&lt;span class="fileupload-new"&gt;Select image&lt;/span&gt;&lt;span class="fileupload-exists"&gt;Change&lt;/span&gt; &lt;input type="file" name='image' /&gt;&lt;/span&gt; &lt;a href="#" class="btn btn-default fileupload-exists" data-dismiss="fileupload"&gt;Remove&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Description&lt;/label&gt; &lt;input type="text" id="Description" name="Description" class="form-control" value="&lt;?php echo $row_user['Description'] ?&gt;"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="name"&gt;Unit&lt;/label&gt; &lt;input type="text" id="Unit" name="Unit" class="form-control" value="&lt;?php echo $_POST['Unit'] ?&gt;"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="select-input"&gt;Category&lt;/label&gt; &lt;select id="select-input" name="Category" class="form-control"&gt; &lt;option value="G"&gt;Generic&lt;/option&gt; &lt;option value="S"&gt;Stationary&lt;/option&gt; &lt;option value="E"&gt;Envelopes&lt;/option&gt; &lt;option value="M"&gt;Megazine Reprint&lt;/option&gt; &lt;option value="T"&gt;Tabs&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="select-input"&gt;Generic&lt;/label&gt; &lt;select id="select-input" name="Generic" class="form-control"&gt; &lt;option value="1"&gt;Yes&lt;/option&gt; &lt;option value="0"&gt;No&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;button type="submit" name="submit" class="btn btn-primary"&gt;&lt;i class="fa fa-check-square-o"&gt;&lt;/i&gt; Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;!--END PORTLET-CONTENT --&gt; &lt;/div&gt; &lt;!-- END PORTLET --&gt; &lt;/div&gt; &lt;!-- END COL --&gt; &lt;/div&gt; &lt;!--END ROW --&gt; &lt;/div&gt; &lt;!-- END CONTENT-CONATINER --&gt; &lt;/div&gt; &lt;!--END CONTENT --&gt; &lt;/div&gt; &lt;!--END WRAPPER --&gt; </code></pre> <p>'</p> <pre><code>// EDIT PRODUCT $allowed_filetypes_pdf = array('pdf'); $ext_pdf = end((explode(".", $_FILES['pdf']['name']))); $pdfName = $_POST['Office'].'.'.$ext_pdf; $pdf = ($_FILES['pdf']['name'])?$path_pdf.$pdfName:$_SESSION['oldpdf']; // $path = "../".$path_pdf.$_POST['Office']."/"; $path_pdf = "../".$path_pdf.$pdfName; // chmod($path_pdf, 0777); $tmp_pdf = $_FILES['pdf']['tmp_name']; $moved1 = move_uploaded_file($tmp_pdf, $path_pdf); $query = "UPDATE `products` SET Office = ?,Description = ?,Unit = ?,Generic = ?,image=?,PDF_Path=?,Category=? WHERE ID=?"; $parameters = array($_POST['Office'],$_POST['Description'],$_POST['Unit'],$_POST['Generic'],$imageName,$pdf,$_POST['Category'],$_POST['ID']); </code></pre> </div>

强制下载文件在Safari浏览器中不起作用

<div class="post-text" itemprop="text"> <p>I'm downloading a file from cross-domain and its working both in chrome and Firefox but not working in safari. Both Chrome and Firefox are downloading where as Safari is playing the song. It's safari bug but solved by somebody and I didn't quite get it. Please do help me.</p> <p>Note: Giving a small error : <code>Failed to load resource: Frame load interrupted</code></p> <p>Clientside code:</p> <pre><code>var url = "http://www.example.com/song.mp3"; var xhr = createCORSRequest('GET', url); if (!xhr) { alert('CORS not supported'); return; } xhr.responseType = 'blob'; xhr.onload = function() { var a = document.createElement('a'); a.href = window.URL.createObjectURL(xhr.response); a.download = 'FileName.mp3'; a.style.display = 'none'; document.body.appendChild(a); a.click(); delete a; }; xhr.onerror = function() { alert('Woops, there was an error making the request.'); }; xhr.send(); } function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safari. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // XDomainRequest for IE. xhr = new XDomainRequest(); xhr.open(method, url); } else { // CORS not supported. xhr = null; } return xhr; } </code></pre> <p>ServerSide Code:</p> <p>.htaccess file</p> <pre><code>&lt;FilesMatch "\.('mp3')$"&gt; ForceType application/octet-stream Header set Content-Disposition attachment &lt;/FilesMatch&gt; </code></pre> </div>

TCPDF条形码问题

<div class="post-text" itemprop="text"> <p>I am using the following code to generate 1D Barcode.</p> <pre><code>//set standard size for label 174mmx100mm, dont pass orientation as that seems to break things $pdf = new tcpdf('', PDF_UNIT, array(174,100), true, 'UTF-8', false); $pdf-&gt;IncludeJS("print(true);"); $pdf-&gt;SetFontSize(10); // remove default header/footer $pdf-&gt;setPrintHeader(false); $pdf-&gt;setPrintFooter(false); //set image scale factor $pdf-&gt;setImageScale(1.53); //turn off auto page breaks which aren't useful here $pdf-&gt;SetAutoPageBreak(false); //set some language-dependent strings $pdf-&gt;setLanguageArray($l); // set JPEG quality $pdf-&gt;setJPEGQuality(100); // set default monospaced font $pdf-&gt;SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf-&gt;SetDisplayMode('real', 'SinglePage'); $style = array( 'position' =&gt; '', 'align' =&gt; 'C', 'stretch' =&gt; false, 'fitwidth' =&gt; true, 'cellfitalign' =&gt; '', 'border' =&gt; false, 'padding' =&gt; 0, 'hpadding' =&gt; 'auto', 'vpadding' =&gt; 'auto', 'fgcolor' =&gt; array(0,0,0), 'bgcolor' =&gt; false, //array(255,255,255), 'font' =&gt; 'helvetica', 'fontsize' =&gt; 8, 'stretchtext' =&gt; 4 ); $pdf-&gt;Text(self::pxtomm(124), self::pxtomm(206), $la_barcodedata['barcode']); //tall 1d barcode $pdf-&gt;write1DBarcode('2245950000007601AKL001AS', 'C128B', self::pxtomm(72), self::pxtomm(226), self::pxtomm(279), self::pxtomm(57), 0.4, $style, 'N'); // The conversion method just for reference private function pxtomm($pi_pixels) { return $pi_pixels * 0.264583333; } </code></pre> <p>Now the issue is the generate pdf document looks different in IE, FF, Chrome. All barcodes printed from IE cannot be scanned because the barcode lines overlaps and make it look like a single block. If I zoom in and out I can see the distinct lines but not on the actual page fit size. </p> <p>What is the best way to avoid that and make it look consistant across all browsers ?</p> </div>

“脏”.htaccess文件? [关闭]

<div class="post-text" itemprop="text"> <p>Heads up - I am a rather inexperienced techy, but certainly more technical than my companions! We have a WordPress site, and have installed/removed various plugins.</p> <p>The reason for this post is that we're suffering significant wait/TTFB issues on our website. The site is hosted on an Apache VPS, and I read that the .htaccess file can be problematic for such setups.</p> <p>Any advice/guidance will be greatly appreciated! We wanted to really just check that our .htaccess file looks "Ok"? To the untrained eye it looks like there is some repetition towards the bottom, and there is also the statement "AddType x-httpd-php54 .php" - which I wanted to make sure was necessary at this level. The .htaccess file is stored in the public_html folder.</p> <pre><code># BEGIN WpFastestCache &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} ^www.example.com [NC] RewriteRule ^(.*)$ http\:\/\/example\.com\/$1 [R=301,L] RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{HTTPS} !=on RewriteCond %{REQUEST_URI} !(\/){2}$ RewriteCond %{QUERY_STRING} !.+ RewriteCond %{HTTP:Cookie} !^.*(comment_author_|wordpress_logged_in|wp_woocommerce_session).*$ RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC] RewriteCond %{HTTP_USER_AGENT} !^.*(iphone|midp|sony|symbos|nokia|samsung|mobile|epoc|ericsson|panasonic|philips|sanyo|sharp|sie-|portalmmm|blazer|avantgo|danger|palm|series60|palmsource|pocketpc|android|blackberry|playbook|ipad|ipod|iemobile|palmos|webos|googlebot-mobile|bb10|xoom|p160u|nexus|touch|SCH-I800|opera\smini|SM-G900R4|LG-|HTC|GT-I9505|WAP-Browser|Nokia309|Casper_VIA).*$ [NC] RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/all/$1/index.html -f [or] RewriteCond /var/sites/b/example.com/public_html/wp-content/cache/all/$1/index.html -f RewriteRule ^(.*) "/wp-content/cache/all/$1/index.html" [L] &lt;/IfModule&gt; &lt;FilesMatch "\.(html|htm)$"&gt; AddDefaultCharset UTF-8 &lt;ifModule mod_headers.c&gt; FileETag None Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Mon, 29 Oct 1923 20:30:00 GMT" &lt;/ifModule&gt; &lt;/FilesMatch&gt; # END WpFastestCache # BEGIN GzipWpFastestCache &lt;IfModule mod_deflate.c&gt; AddType x-font/woff .woff AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE font/opentype font/ttf font/eot font/otf &lt;/IfModule&gt; # END GzipWpFastestCache # BEGIN LBCWpFastestCache &lt;FilesMatch "\.(?i:ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)(\.gz)?$"&gt; &lt;IfModule mod_expires.c&gt; ExpiresActive On ExpiresDefault A0 ExpiresByType image/gif A2592000 ExpiresByType image/png A2592000 ExpiresByType image/jpg A2592000 ExpiresByType image/jpeg A2592000 ExpiresByType image/ico A2592000 ExpiresByType image/svg+xml A2592000 ExpiresByType text/css A2592000 ExpiresByType text/javascript A2592000 ExpiresByType application/javascript A2592000 &lt;/IfModule&gt; &lt;IfModule mod_headers.c&gt; Header set Expires "max-age=2592000, public" Header unset ETag Header set Connection keep-alive FileETag None &lt;/IfModule&gt; &lt;/FilesMatch&gt; # END LBCWpFastestCache # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress #Gzip AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript text/javascript #End Gzip AddType x-httpd-php54 .php </code></pre> </div>

需要将htaccess文件转换为php.ini

<div class="post-text" itemprop="text"> <p>I am moving a website from 1 host to another but this new host is configured differently and the htaccess password doesn't work. They have informed me that the settings need to be done via php.ini rather than htaccess.</p> <p>Quoting part of the hosts message: "errors include attempting to use php_value directives in your .htaccess file, which will not work as we run PHP as CGI"</p> <p>I am not very well versed with these files, i have included my htaccess file below and wondered if someone could explain which bits are incorrect? URL has been replaced.</p> <pre><code># ---------------------------------------------------------------------- # Better website experience for IE users # ---------------------------------------------------------------------- # Force the latest IE version, in various cases when it may fall back to IE7 mode # github.com/rails/rails/commit/123eb25#commitcomment-118920 # Use ChromeFrame if it's installed for a better experience for the poor IE folk &lt;IfModule mod_headers.c&gt; Header set X-UA-Compatible "IE=Edge,chrome=1" # mod_headers can't match by content-type, but we don't want to send this header on *everything*... &lt;FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|xpi|safariextz|vcf)$" &gt; Header unset X-UA-Compatible &lt;/FilesMatch&gt; &lt;/IfModule&gt; # &lt;IfModule mod_headers.c&gt; # Header set Access-Control-Allow-Origin "*" # &lt;/IfModule&gt; &lt;FilesMatch "\.(svg|ttf|ttc|otf|eot|woff|font.css)$"&gt; &lt;IfModule mod_headers.c&gt; Header set Access-Control-Allow-Origin "*" &lt;/IfModule&gt; &lt;/FilesMatch&gt; # ---------------------------------------------------------------------- # Proper MIME type for all files # ---------------------------------------------------------------------- # JavaScript # Normalize to standard type (it's sniffed in IE anyways) # tools.ietf.org/html/rfc4329#section-7.2 AddType application/javascript js # Audio AddType audio/ogg oga ogg AddType audio/mp4 m4a # Video AddType video/ogg ogv AddType video/mp4 mp4 m4v AddType video/webm webm # SVG. # Required for svg webfonts on iPad # twitter.com/FontSquirrel/status/14855840545 AddType image/svg+xml svg svgz AddEncoding gzip svgz # Webfonts AddType application/vnd.ms-fontobject eot AddType application/x-font-ttf ttf ttc AddType font/opentype otf AddType application/x-font-woff woff # Assorted types AddType image/x-icon ico AddType image/webp webp AddType text/cache-manifest appcache manifest AddType text/x-component htc AddType application/x-chrome-extension crx AddType application/x-xpinstall xpi AddType application/octet-stream safariextz AddType text/x-vcard vcf # ---------------------------------------------------------------------- # Gzip compression # ---------------------------------------------------------------------- &lt;IfModule mod_deflate.c&gt; # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/ &lt;IfModule mod_setenvif.c&gt; &lt;IfModule mod_headers.c&gt; SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding &lt;/IfModule&gt; &lt;/IfModule&gt; # HTML, TXT, CSS, JavaScript, JSON, XML, HTC: &lt;IfModule filter_module&gt; FilterDeclare COMPRESS FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css FilterProvider COMPRESS DEFLATE resp=Content-Type $text/plain FilterProvider COMPRESS DEFLATE resp=Content-Type $text/xml FilterProvider COMPRESS DEFLATE resp=Content-Type $text/x-component FilterProvider COMPRESS DEFLATE resp=Content-Type $application/javascript FilterProvider COMPRESS DEFLATE resp=Content-Type $application/json FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/xhtml+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/rss+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/atom+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/vnd.ms-fontobject FilterProvider COMPRESS DEFLATE resp=Content-Type $image/svg+xml FilterProvider COMPRESS DEFLATE resp=Content-Type $application/x-font-ttf FilterProvider COMPRESS DEFLATE resp=Content-Type $font/opentype FilterChain COMPRESS FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no &lt;/IfModule&gt; &lt;IfModule !mod_filter.c&gt; # Legacy versions of Apache AddOutputFilterByType DEFLATE text/html text/plain text/css application/json AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE text/xml application/xml text/x-component AddOutputFilterByType DEFLATE application/xhtml+xml application/rss+xml application/atom+xml AddOutputFilterByType DEFLATE image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype &lt;/IfModule&gt; &lt;/IfModule&gt; &lt;IfModule mod_expires.c&gt; ExpiresActive on # Perhaps better to whitelist expires rules? Perhaps. ExpiresDefault "access plus 1 month" # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5) ExpiresByType text/cache-manifest "access plus 0 seconds" # Your document html ExpiresByType text/html "access plus 0 seconds" # Data ExpiresByType text/xml "access plus 0 seconds" ExpiresByType application/xml "access plus 0 seconds" ExpiresByType application/json "access plus 0 seconds" # Feed ExpiresByType application/rss+xml "access plus 1 hour" ExpiresByType application/atom+xml "access plus 1 hour" # Favicon (cannot be renamed) ExpiresByType image/x-icon "access plus 1 week" # Media: images, video, audio ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType video/ogg "access plus 1 month" ExpiresByType audio/ogg "access plus 1 month" ExpiresByType video/mp4 "access plus 1 month" ExpiresByType video/webm "access plus 1 month" # HTC files (css3pie) ExpiresByType text/x-component "access plus 1 month" # Webfonts ExpiresByType font/truetype "access plus 1 month" ExpiresByType font/opentype "access plus 1 month" ExpiresByType application/x-font-woff "access plus 1 month" ExpiresByType image/svg+xml "access plus 1 month" ExpiresByType application/vnd.ms-fontobject "access plus 1 month" # CSS and JavaScript ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" &lt;IfModule mod_headers.c&gt; Header append Cache-Control "public" &lt;/IfModule&gt; &lt;/IfModule&gt; &lt;IfModule mod_headers.c&gt; Header unset ETag &lt;/IfModule&gt; FileETag None Options -MultiViews AddDefaultCharset utf-8 AddCharset utf-8 .html .css .js .xml .json .rss .atom Options -Indexes &lt;IfModule php5_module&gt; php_value session.cookie_httponly true php_flag short_open_tag on &lt;/IfModule&gt; &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteRule "(^|/)\." - [F] RewriteCond %{HTTP_HOST} ^xxxxxxxxxxxxxx.com$ [NC] RewriteRule (.*) http://www.xxxxxxxxxxxxxx.com/$1 [R=302,L,QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?p=$1 [QSA] &lt;/IfModule&gt; </code></pre> </div>

内部服务器错误 - Opencart

<div class="post-text" itemprop="text"> <p>I've downloaded an opencart installation in my local server in order to use it as a test and i'm not able to view the site. When i use the default htaccess file the browser returns a 500 error and when i remove the htaccess file the seo - links do not work. (404)</p> <p>Any ideas?</p> <p>My .htaccess file</p> <pre><code># 1.To use URL Alias you need to be running apache with mod_rewrite enabled. # 2. In your opencart directory rename htaccess.txt to .htaccess. # For any support issues please visit: http://www.opencart.com Options +FollowSymlinks # Prevent Directoy listing Options -Indexes # Turn on Expires and set default to 0 ExpiresActive On ExpiresDefault A0 # Set up caching on media files for 5 weeks &lt;FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$"&gt; ExpiresDefault A3024000 Header append Cache-Control "public" &lt;/FilesMatch&gt; # Set up caching on media files for 5 weeks &lt;FilesMatch "\.(gif|jpg|jpeg|png|swf)$"&gt; ExpiresDefault A3024000 Header append Cache-Control "public" &lt;/FilesMatch&gt; # Set up 1 day caching on commonly updated files &lt;FilesMatch "\.(xml|txt|html|js|css)$"&gt; ExpiresDefault A86400 Header append Cache-Control "proxy-revalidate" &lt;/FilesMatch&gt; # Force no caching for dynamic files &lt;FilesMatch "\.(php|cgi|pl|htm)$"&gt; ExpiresActive Off Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform" Header set Pragma "no-cache" &lt;/FilesMatch&gt; &lt;IfModule mod_deflate.c&gt; &lt;filesMatch "\.(js|css|html|php)$"&gt; SetOutputFilter DEFLATE &lt;/filesMatch&gt; &lt;/IfModule&gt; # Prevent Direct Access to files &lt;FilesMatch "\.(tpl|ini|log)"&gt; Order deny,allow Deny from all &lt;/FilesMatch&gt; # SEO URL Settings RewriteEngine On # If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/ RewriteBase / RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L] RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L] RewriteRule ^download/(.*) /index.php?route=error/not_found [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css) RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA] ### Additional Settings that may need to be enabled for some servers ### Uncomment the commands by removing the # sign in front of it. ### If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that. # 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it: # php_flag register_globals off # 2. If your cart has magic quotes enabled, This may work to disable it: # php_flag magic_quotes_gpc Off # 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try # php_value upload_max_filesize 999M # 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields # php_value post_max_size 999M # 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields # php_value max_execution_time 200 # 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields # php_value max_input_time 200 # 7. disable open_basedir limitations # php_admin_value open_basedir none </code></pre> </div>

如何为所有页面提供静态文件,而不仅仅是少数

<div class="post-text" itemprop="text"> <p>I'm having a problem with my Go project where one route handles CSS fine and another route's CSS is broken. The CSS used to work on both pages, but now it isn't loading for /login.html.</p> <p>I know that I'm properly stripping the prefix for the /static/ folder because it's working in once place and not another. I also directly copied and pasted the header code from the working page to the not-working page (being careful to use the correct css file).</p> <p>Negroni is showing that the application is making the call to the correct location: </p> <pre><code>999.3µs | localhost:8080 | GET /static/css/splash.css </code></pre> <p>The correctly working html file index.html:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt; &lt;title&gt;Pando&lt;/title&gt; &lt;link rel="stylesheet" href="/static/css/index.css" type="text/css" /&gt; &lt;link href="https://fonts.googleapis.com/css?family=Bitter|Nunito:400,700" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="sidebar"&gt; &lt;p id="logo"&gt;&lt;img src="/static/img/logo.svg" height="14px"&gt;Pando&lt;/p&gt; &lt;span id="all-files" class="selected"&gt;All Files&lt;/span&gt; &lt;p id="shared-collections"&gt;Shared Collections&lt;img src="/static/img/gear.svg" /&gt;&lt;/p&gt; &lt;div class="collections"&gt; &lt;span&gt;Collection 1&lt;/span&gt; &lt;span&gt;Collection 2&lt;/span&gt; &lt;/div&gt; &lt;p id="my-collections"&gt;My Collections&lt;img src="/static/img/gear.svg" /&gt;&lt;/p&gt; &lt;div class="collections"&gt; &lt;span&gt;Collection 1&lt;/span&gt; &lt;span&gt;Collection 2&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="header"&gt; &lt;input type="button" id="upload-launch-button" value="Upload" onclick="showUploadDialog()"&gt;&lt;/button&gt; &lt;form id="search"&gt; &lt;input type="search" placeholder="Search.."&gt; &lt;input type="button"&gt;&lt;img src="/static/img/search.svg"&gt;&lt;/button&gt; &lt;/form&gt; &lt;div id="user"&gt; &lt;img src="/static/img/user.svg"&gt;{{.User}}&lt;a href="/logout"&gt;(Log out)&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- &lt;span id="filter"&gt;Latest Files&lt;/span&gt; --&gt; &lt;div id="results"&gt; {{range .Files}} &lt;div class="img-container"&gt; &lt;img src="/files/{{.Name}}" id="file-{{.PK}}"&gt; &lt;div class="hover-actions"&gt; &lt;a href="/files/{{.Name}}" download&gt;&lt;img src="/static/img/download.svg"&gt;&lt;/a&gt; &lt;img src="/static/img/edit.svg"&gt; &lt;img src="/static/img/delete.svg" onclick="deleteFile('/files/{{.Name}}', {{.PK}})"&gt; &lt;/div&gt; &lt;/div&gt; {{end}} &lt;/div&gt; &lt;div class="dialog" id="upload-dialog"&gt; &lt;div class="dialog-name"&gt;Upload&lt;/div&gt; &lt;form id="upload" enctype="multipart/form-data" action="/upload" method="post"&gt; &lt;input type="file" id="selectedFile" name="file" /&gt; &lt;!--multiple later display none--&gt; &lt;input id="upload-button" type="submit" value="Upload" onclick="hideUploadDialog()" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="/static/js/script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Login.html:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge" /&gt; &lt;title&gt;Pando&lt;/title&gt; &lt;link rel="stylesheet" href="/static/css/splash.css" type="text/css" /&gt; &lt;link href="https://fonts.googleapis.com/css?family=Bitter|Nunito:400,700" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;section class="section-a"&gt; &lt;div id="logo"&gt;&lt;img src="/static/img/logo.svg"&gt;Pando&lt;/div&gt; &lt;p id="welcome"&gt;Join Pando.&lt;/p&gt; &lt;div id="buttoncont"&gt; &lt;a href="/static/html/index.html"&gt;&lt;span id="enter" class="button"&gt;Enter&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;/section&gt; &lt;section class="section-b"&gt; &lt;form id="login-form"&gt; &lt;div&gt; &lt;label&gt;Email&lt;/label&gt;&lt;input type="email" name="username" required&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Password&lt;/label&gt;&lt;input type="password" name="password" required&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="submit" value="Register" name="register"&gt; &lt;input type="submit" value="Log In" name="login"&gt; &lt;/div&gt; &lt;div id="error"&gt;{{.Error}}&lt;/div&gt; &lt;/form&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The complete go file:</p> <pre><code>package main import ( "database/sql" "fmt" "html/template" "io/ioutil" "os" "path/filepath" "strconv" "time" "net/http" "gopkg.in/gorp.v1" _ "github.com/go-sql-driver/mysql" "encoding/json" "golang.org/x/crypto/bcrypt" sessions "github.com/goincremental/negroni-sessions" "github.com/goincremental/negroni-sessions/cookiestore" gmux "github.com/gorilla/mux" "github.com/urfave/negroni" ) /*File struct PK primary key Name is the original name of the file; new file location at /files/{name} File Type is the extension of the file; valid file types are image formats, PDF, .AI, .PSD, and MS Word docs Upload Date is a static value indicating when the file was uploaded Last Modified records if any changes are made to the file while it's on the server User is the uploading user Eventually I will probably want to refactor this so that I can allow for files with the same name to coexist. Not sure how to do that right now elegantly. */ type File struct { PK int64 `db:"pk"` Name string `db:"name"` FileType string `db:"type"` UploadDate string `db:"uploadtime"` LastModified string `db:"modtime"` User string `db:"user"` } // Tag struct type Tag struct { PK int64 `db:"pk"` FilePK int64 `db:"filepk"` Name string `db:"name"` } // Collection struct type Collection struct { PK int64 `db:"pk"` Name string `db:"name"` ContentName string `db:"contentname"` ContentType string `db:"type"` } // User struct type User struct { Username string `db:"username"` Secret []byte `db:"secret"` } // Page struct type Page struct { Files []File Filter string User string } // LoginPage struct type LoginPage struct { Error string } // UploadPage struct type UploadPage struct { Error string } var db *sql.DB var dbmap *gorp.DbMap func main() { initDb() index := template.Must(template.ParseFiles("html/index.html")) login := template.Must(template.ParseFiles("html/login.html")) upload := template.Must(template.ParseFiles("html/upload.html")) mux := gmux.NewRouter() defer db.Close() mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) mux.PathPrefix("/css/").Handler(http.StripPrefix("/css/", http.FileServer(http.Dir("css")))) mux.PathPrefix("/img/").Handler(http.StripPrefix("/img/", http.FileServer(http.Dir("img")))) mux.PathPrefix("/files/").Handler(http.StripPrefix("/files/", http.FileServer(http.Dir("files")))) // Login mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { var p LoginPage if r.FormValue("register") != "" { secret, _ := bcrypt.GenerateFromPassword([]byte(r.FormValue("password")), bcrypt.DefaultCost) user := User{r.FormValue("username"), secret} if err := dbmap.Insert(&amp;user); err != nil { p.Error = err.Error() } else { sessions.GetSession(r).Set("User", user.Username) http.Redirect(w, r, "/", http.StatusFound) return } } else if r.FormValue("login") != "" { user, err := dbmap.Get(User{}, r.FormValue("username")) if err != nil { p.Error = err.Error() } else if user == nil { p.Error = "No user account exists for the username " + r.FormValue("username") } else { u := user.(*User) if err = bcrypt.CompareHashAndPassword(u.Secret, []byte(r.FormValue("password"))); err != nil { p.Error = err.Error() } else { sessions.GetSession(r).Set("User", u.Username) http.Redirect(w, r, "/", http.StatusFound) return } } } if err := login.ExecuteTemplate(w, "login.html", p); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }) // Upload mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) { var p UploadPage // Checks filesize against max upload size (10MB) if err := r.ParseMultipartForm(10 &lt;&lt; 20); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // reads file fileType := r.PostFormValue("type") file, header, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer file.Close() fileBytes, err := ioutil.ReadAll(file) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // checks the filetype against expected mime types mimetype := http.DetectContentType(fileBytes) if mimetype != "image/jpeg" &amp;&amp; mimetype != "image/jpg" &amp;&amp; mimetype != "image/gif" &amp;&amp; mimetype != "image/png" &amp;&amp; mimetype != "application/pdf" &amp;&amp; mimetype != "image/vnd.adobe.photoshop" &amp;&amp; mimetype != "application/illustrator" &amp;&amp; mimetype != "image/vnd.microsoft.icon" &amp;&amp; mimetype != "application/msword" &amp;&amp; mimetype != "application/x-photoshop" &amp;&amp; mimetype != "application/photoshop" &amp;&amp; mimetype != "application/psd" { http.Error(w, err.Error(), http.StatusInternalServerError) return } filename := header.Filename newPath := filepath.Join("files/", filename) fmt.Printf("FileType: %s, File: %s ", fileType, newPath) t := time.Now().String() currentTime, _ := time.Parse(time.Stamp, t) // Creates a File struct-type object out of the file information from f := File{ PK: -1, Name: filename, FileType: fileType, UploadDate: currentTime.String(), LastModified: currentTime.String(), User: getStringFromSession(r, "User"), } // Inserts the file information into the database if err = dbmap.Insert(&amp;f); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } newFile, err := os.Create(newPath) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer newFile.Close() if _, err := newFile.Write(fileBytes); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // w.Write([]byte("SUCCESS")) if err := upload.ExecuteTemplate(w, "upload.html", p); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }).Methods("POST") // Sort mux.HandleFunc("/files", func(w http.ResponseWriter, r *http.Request) { var b []File if !getFileCollection(&amp;b, r.FormValue("sortBy"), getStringFromSession(r, "Filter"), getStringFromSession(r, "User"), w) { return } sessions.GetSession(r).Set("sortBy", r.FormValue("sortBy")) if err := json.NewEncoder(w).Encode(b); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } }).Methods("GET").Queries("sortBy", "{sortBy:title|author|classification}") // Default page mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { p := Page{Files: []File{}, Filter: getStringFromSession(r, "Filter"), User: getStringFromSession(r, "User")} if !getFileCollection(&amp;p.Files, getStringFromSession(r, "SortBy"), getStringFromSession(r, "Filter"), p.User, w) { return } if err := index.ExecuteTemplate(w, "index.html", p); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }).Methods("GET") mux.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) { sessions.GetSession(r).Set("User", nil) sessions.GetSession(r).Set("Filter", nil) http.Redirect(w, r, "/login", http.StatusFound) }) // Deletes file from database; currently not working :( mux.HandleFunc("/files/{name}", func(w http.ResponseWriter, r *http.Request) { pk, _ := strconv.ParseInt(gmux.Vars(r)["pk"], 10, 64) fmt.Printf("pk is %d", pk) var f File if err := dbmap.SelectOne(&amp;f, "select * from files where pk=?", pk); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } if _, err := dbmap.Delete(&amp;f); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) }).Methods("DELETE") // Session management n := negroni.Classic() n.Use(sessions.Sessions("pando", cookiestore.New([]byte("hubert88")))) n.Use(negroni.HandlerFunc(verifyDatabase)) n.Use(negroni.HandlerFunc(verifyUser)) n.UseHandler(mux) n.Run(":8080") } // end main // Opens the database connection to SQL and creates tables if they don't exist func initDb() { db, _ = sql.Open("mysql", "root:secret@tcp(127.0.0.1:3306)/pando") dbmap = &amp;gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}} // creates tables, specifies the fields on the struct that map to table primary keys dbmap.AddTableWithName(File{}, "files").SetKeys(true, "pk") dbmap.AddTableWithName(Tag{}, "tags").SetKeys(true, "pk") dbmap.AddTableWithName(Collection{}, "collections").SetKeys(true, "pk") dbmap.AddTableWithName(User{}, "users").SetKeys(false, "username") dbmap.CreateTablesIfNotExists() } // Checks to make sure the database is alive func verifyDatabase(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { if err := db.Ping(); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } next(w, r) } func getStringFromSession(r *http.Request, key string) string { var strVal string if val := sessions.GetSession(r).Get(key); val != nil { strVal = val.(string) } return strVal } func verifyUser(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { if r.URL.Path == "/login" { next(w, r) return } if username := getStringFromSession(r, "User"); username != "" { if user, _ := dbmap.Get(User{}, username); user != nil { next(w, r) return } } http.Redirect(w, r, "/login", http.StatusTemporaryRedirect) } </code></pre> <p>I'm at my wits end trying to debug this, and all the search results I get only talk about stripping prefixes (which I'm already doing).</p> <p>In the Networking tab of my browser, the CSS and image files are returning a 307 Temporary Redirect error.</p> <p>Running colminator's curl command gave this output:</p> <pre><code>HTTP/1.1 307 Temporary Redirect Content-Type: text/html; charset=utf-8 Location: /login Date: Sun, 05 May 2019 22:16:17 GMT Content-Length: 42 </code></pre> <p>This is how I'm handling my static files.</p> <pre><code>mux.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) </code></pre> </div>

Magento显示除主页以外的所有页面的404错误

<div class="post-text" itemprop="text"> <p>I freshly installed magento 2 and deploy static content so my homepage is looking fine but all other pages showing 404 error. It works if I add index.php before url.</p> <p>My admin is also not working</p> <p>OS : Ubuntu &amp; using Lamp Installed inside subdirectory "m2" location /var/www/html/m2</p> <p>My mod_rewrite module is enabled I check and here is my htaccess file :</p> <pre><code>############################################ ## overrides deployment configuration mode value ## use command bin/magento deploy:mode:set to switch modes # SetEnv MAGE_MODE developer ############################################ ## uncomment these lines for CGI mode ## make sure to specify the correct cgi php binary file name ## it might be /cgi-bin/php-cgi # Action php5-cgi /cgi-bin/php5-cgi # AddHandler php5-cgi .php ############################################ ## GoDaddy specific options # Options -MultiViews ## you might also need to add this line to php.ini ## cgi.fix_pathinfo = 1 ## if it still doesn't work, rename php.ini to php5.ini ############################################ ## this line is specific for 1and1 hosting #AddType x-mapp-php5 .php #AddHandler x-mapp-php5 .php ############################################ ## default index file DirectoryIndex index.php &lt;IfModule mod_php5.c&gt; ############################################ ## adjust memory limit php_value memory_limit 756M php_value max_execution_time 18000 ############################################ ## disable automatic session start ## before autoload was initialized php_flag session.auto_start off ############################################ ## enable resulting html compression #php_flag zlib.output_compression on ########################################### ## disable user agent verification to not break multiple image upload php_flag suhosin.session.cryptua off &lt;/IfModule&gt; &lt;IfModule mod_php7.c&gt; ############################################ ## adjust memory limit php_value memory_limit 756M php_value max_execution_time 18000 ############################################ ## disable automatic session start ## before autoload was initialized php_flag session.auto_start off ############################################ ## enable resulting html compression #php_flag zlib.output_compression on ########################################### ## disable user agent verification to not break multiple image upload php_flag suhosin.session.cryptua off &lt;/IfModule&gt; &lt;IfModule mod_security.c&gt; ########################################### ## disable POST processing to not break multiple image upload SecFilterEngine Off SecFilterScanPOST Off &lt;/IfModule&gt; &lt;IfModule mod_deflate.c&gt; ############################################ ## enable apache served files compression ## http://developer.yahoo.com/performance/rules.html#gzip # Insert filter on all content ###SetOutputFilter DEFLATE # Insert filter on selected content types only #AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json image/svg+xml # Netscape 4.x has some problems... #BrowserMatch ^Mozilla/4 gzip-only-text/html # Netscape 4.06-4.08 have some more problems #BrowserMatch ^Mozilla/4\.0[678] no-gzip # MSIE masquerades as Netscape, but it is fine #BrowserMatch \bMSIE !no-gzip !gzip-only-text/html # Don't compress images #SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary # Make sure proxies don't deliver the wrong content #Header append Vary User-Agent env=!dont-vary &lt;/IfModule&gt; &lt;IfModule mod_ssl.c&gt; ############################################ ## make HTTPS env vars available for CGI mode SSLOptions StdEnvVars &lt;/IfModule&gt; ############################################ ## workaround for Apache 2.4.6 CentOS build when working via ProxyPassMatch with HHVM (or any other) ## Please, set it on virtual host configuration level ## SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 ############################################ &lt;IfModule mod_rewrite.c&gt; ############################################ ## enable rewrites Options +FollowSymLinks RewriteEngine on ############################################ ## you can put here your magento root folder ## path relative to web root #RewriteBase /magento/ ############################################ ## workaround for HTTP authorization ## in CGI environment RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] ############################################ ## TRACE and TRACK HTTP methods disabled to prevent XSS attacks RewriteCond %{REQUEST_METHOD} ^TRAC[EK] RewriteRule .* - [L,R=405] ############################################ ## redirect for mobile user agents #RewriteCond %{REQUEST_URI} !^/mobiledirectoryhere/.*$ #RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC] #RewriteRule ^(.*)$ /mobiledirectoryhere/ [L,R=302] ############################################ ## never rewrite for existing files, directories and links RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l ############################################ ## rewrite everything else to index.php RewriteRule .* index.php [L] &lt;/IfModule&gt; ############################################ ## Prevent character encoding issues from server overrides ## If you still have problems, use the second line instead AddDefaultCharset Off #AddDefaultCharset UTF-8 AddType 'text/html; charset=UTF-8' html &lt;IfModule mod_expires.c&gt; ############################################ ## Add default Expires header ## http://developer.yahoo.com/performance/rules.html#expires ExpiresDefault "access plus 1 year" ExpiresByType text/html A0 ExpiresByType text/plain A0 &lt;/IfModule&gt; ########################################### ## Deny access to root files to hide sensitive application information RedirectMatch 403 /\.git &lt;Files composer.json&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files composer.lock&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files .gitignore&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files .htaccess&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files .htaccess.sample&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files .php_cs.dist&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files .travis.yml&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files CHANGELOG.md&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files COPYING.txt&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files Gruntfile.js&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files LICENSE.txt&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files LICENSE_AFL.txt&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files nginx.conf.sample&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files package.json&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files php.ini.sample&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files README.md&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files auth.json&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; &lt;Files magento_umask&gt; &lt;IfVersion &lt; 2.4&gt; order allow,deny deny from all &lt;/IfVersion&gt; &lt;IfVersion &gt;= 2.4&gt; Require all denied &lt;/IfVersion&gt; &lt;/Files&gt; # For 404s and 403s that aren't handled by the application, show plain 404 response ErrorDocument 404 /pub/errors/404.php ErrorDocument 403 /pub/errors/404.php ################################ ## If running in cluster environment, uncomment this ## http://developer.yahoo.com/performance/rules.html#etags #FileETag none # ###################################################################### # # INTERNET EXPLORER # # ###################################################################### # ---------------------------------------------------------------------- # | Document modes | # ---------------------------------------------------------------------- # Force Internet Explorer 8/9/10 to render pages in the highest mode # available in the various cases when it may not. # # https://hsivonen.fi/doctype/#ie8 # # (!) Starting with Internet Explorer 11, document modes are deprecated. # If your business still relies on older web apps and services that were # designed for older versions of Internet Explorer, you might want to # consider enabling `Enterprise Mode` throughout your company. # # https://msdn.microsoft.com/en-us/library/ie/bg182625.aspx#docmode # http://blogs.msdn.com/b/ie/archive/2014/04/02/stay-up-to-date-with-enterprise-mode-for-internet-explorer-11.aspx &lt;IfModule mod_headers.c&gt; Header set X-UA-Compatible "IE=edge" # `mod_headers` cannot match based on the content-type, however, # the `X-UA-Compatible` response header should be send only for # HTML documents and not for the other resources. &lt;FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt[cf]|txt|vcard|vcf|vtt|webapp|web[mp]|webmanifest|woff2?|xloc|xml|xpi)$"&gt; Header unset X-UA-Compatible &lt;/FilesMatch&gt; &lt;/IfModule&gt; </code></pre> </div>

使用PHP从FormData检索文件

<div class="post-text" itemprop="text"> <p>I am attempting to send an image from the client to a PHP file that will upload the image into a preset directory. I am not sure why I cannot seem to get the following code to accomplish this task.</p> <p>JS File:</p> <pre><code>function update_avatar(){ var file = document.getElementById('avatar'); var formData = new FormData(file); //formData.append("avatar",file); if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (this.readyState==4 &amp;&amp; this.status==200) { var r = JSON.parse(this.responseText); console.log(r); if(r.status === 'GOOD'){ document.getElementById('pForm_response').innerHTML = 'Your Avatar Was Updated Successfully!'; setTimeout(function(){ document.getElementById('pForm_response').innerHTML = ''; },5000); //Change Avatar Image URL... document.getElementById('avatarPreview').href = r.newURL; window.scrollTo(0, 0); }else{ document.getElementById('pForm_error').innerHTML = 'There was an error processing your request...'; setTimeout(function(){ document.getElementById('pForm_error').innerHTML = ''; },5000); window.scrollTo(0, 0); } } } xmlhttp.open("POST","user-settings/php/update-avatar.php",true); xmlhttp.setRequestHeader('Content-Type','multipart/form-data'); //xmlhttp.setRequestHeader('Content-type', 'application/x-www-form- urlencoded'); xmlhttp.send(formData); } </code></pre> <p>PHP File:</p> <pre><code> &lt;?php include '../../assets/php/connection.php'; $eMessages = ''; print_r($_POST); print_r($_FILES); //echo $_FILES['avatar']['size'];//For DeBug ONLY... if($_FILES['avatar']['size'] != 0) { $id = rand(100000,1000000); //Document Parsing $target_dir = "../../assets/img/avatars/"; $target_file2 = $target_dir . basename($_FILES["avatar"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file2,PATHINFO_EXTENSION); $target_file = $target_dir . $_SESSION['user_id'] . "_avatarImg_" . $id . "." . $imageFileType; // Check if image file is a actual image or fake image $check = getimagesize($_FILES["avatar"]["tmp_name"]); if($check !== false) { // echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { $eMessages .= "File is not an image."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" &amp;&amp; $imageFileType != "png" &amp;&amp; $imageFileType != "jpeg" &amp;&amp; $imageFileType != "gif" &amp;&amp; $imageFileType != "JPG" &amp;&amp; $imageFileType != "PNG" ) { $eMessages .= "&lt;br&gt;ERROR!- only JPG, JPEG, PDF, PNG &amp; GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { $eMessages .= "&lt;br&gt;ERROR!- your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["avatar"]["tmp_name"], $target_file)) { //INSERT FILE PATH INTO DATABASE $file_name_1 = 'http://' . $_SERVER['HTTP_HOST'] . '/toolbox/assets/img/avatars/' . $_SESSION['user_id'] . '_docImg_' . $id . '.' . $imageFileType; //echo '&lt;br&gt;File was moved to the right location!'; } } }else{ //Set URL to empty if no file was selected to upload... $file_name_1 = ''; $uploadOk = 0; $eMessages .= 'Size of Image not detected!'; }//End if file was uploaded //echo $eMessages; $q = "UPDATE `users` SET `avatar_url` = '" . $file_name_1 . "' WHERE `ID` = '" . $_SESSION['user_id'] . "'"; if($uploadOK != 0){ mysqli_query($ign_conn, $q) or die($ign_conn-&gt;error); $x-&gt;status = 'GOOD'; $x-&gt;response = 'Avatar Updated Successfully...'; $x-&gt;newURL = $file_name_1; }else{ $x-&gt;status = 'BAD'; $x-&gt;response = $eMessages; } $response = json_encode($x); echo $response; ?&gt; </code></pre> <p>I am using <code>$_FILES['avatar']['size']</code> to try and detect the image and I get nothing...</p> <p>EDIT: When I use this code in the PHP file:</p> <pre><code>print_r($_POST); print_r($_FILES); </code></pre> <p>The output is:</p> <pre><code>Array ( ) Array ( ) </code></pre> <p>I am still not sure why my values are empty?</p> <p>Additionally, this is my Request Payload:</p> <pre><code>------WebKitFormBoundaryzBMoLRhnxawwcEQR-- </code></pre> </div>

如何缓存图像一年,但html / php只有24小时

<div class="post-text" itemprop="text"> <p>I'm new here so sorry if this is in the wrong category or something like that. Now getting to my problem. I have a website: www.windowstaan.pe.hu which also opens on a mobile app so in order to make it load fast I have enabled caching in <code>.htaccess</code> and here's its code:</p> <pre><code>## EXPIRES CACHING ## &lt;IfModule mod_expires.c&gt; ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 day" ExpiresByType text/html "access 1 day" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 1 month" &lt;/IfModule&gt; ## EXPIRES CACHING ## </code></pre> <p>Now what happens here is that any page I load in the browser can also be loaded offline which is what I wanted, but if I make any changes to the html then I'm not sure how its going to update here.</p> <p>My html files are saved as <code>index.php</code>, PHP because they have some PHP code in them mainly include header, footer and a small mysql line.</p> <p>Now what I want is for this homepage and every other html/php page to reload every day.</p> <p>Please tell me what I need to do in <code>.htaccess</code> to set it like that.</p> <p>I have tried setting html / css to 1 day there but that is not working perfectly as my app still loads the old cache. (My app is just a browser of windowsphone 8.1, IE11 probably.) </p> <p>Thanks in advance. </p> </div>

使用mySql DB创建PHP按钮

<div class="post-text" itemprop="text"> <p>I have a database with three tables "Cantiere "Affidataria "SubAffidataria" "Cantiere" has a 1 to N relationship with Affidataria "Affidataria" has a 1 to N relationship with subAffidataria so in Affidataria there is a fk of "Cantiere" called "fkIdCantiere" and in subAffidataria there is a fk of "Affidataria" called "fkIDAffidataria" my problem is to go from a "function" to the id of fkIdAffidataria in fact, if you notice in the screenshot you see the carers but not the sub-delegates. so I have to make sure to save the fkIdAffidataria to put it in the QUERY ..</p> <p><a href="https://i.stack.imgur.com/i54G4.png" rel="nofollow noreferrer">enter image description here</a></p> <p>"0 results" indicates that the query did not find any subAffidataria .. when in fact they are in the database</p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;?php session_start(); if(!isset($_SESSION["username"])) { header('location: ../index.php'); } else { ?&gt; &lt;?php $servername = "localhost"; $username = "progettocantiere"; $password = ""; $dbname = "my_progettocantiere"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $idCantiere = $_GET['idCantiere']; $sql1 = "SELECT idAffidataria,nomeCantiere,fkIDCantiere FROM Affidataria WHERE fkIDCantiere = '$idCantiere'"; echo($idAffidataria); $idAffidataria = $_GET['idAffidataria']; $result1 = $conn-&gt;query($sql1); if ($result1-&gt;num_rows &gt; 0) { // output data of each row while($row = $result1-&gt;fetch_assoc()) { echo'&lt;br&gt;&lt;br&gt;&lt;br&gt;'; echo '&lt;h3&gt;Affidataria&lt;/h3&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Stampa PDF ' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Esporta Directory Interna ' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Stampa Personale ' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Esporta Directory Personale ' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Stampa Mezzi ' . $row["nomeCantiere"] . '&lt;/a&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/affidatario.php?idAffidataria=' . $row["idAffidataria"] . '"&gt;Esporta Directory Mezzi ' . $row["nomeCantiere"] . '&lt;/a&gt;'; } echo'&lt;br&gt;&lt;br&gt;&lt;br&gt;'; } else { echo "0 results"; } $conn-&gt;close(); ?&gt; //subAffidatario &lt;?php $servername = "localhost"; $username = "progettocantiere"; $password = ""; $dbname = "my_progettocantiere"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } $sql1 = "SELECT * FROM SubAffidatario WHERE fkIdAffidataria = '$idAffidataria'"; echo($idSubAffidatario); $result1 = $conn-&gt;query($sql1); if ($result1-&gt;num_rows &gt; 0) { // output data of each row while($row = $result1-&gt;fetch_assoc()) { echo'&lt;br&gt;&lt;br&gt;&lt;br&gt;'; echo '&lt;a class="myButton" href="../../pagineHtml/visualizza/visualizzazione/subAffidatario.php?idSubAffidatario=' . $row["idSubAffidatario"] . '"&gt;' . $row["ragioneSocialeSubAffidatario"] . '&lt;/a&gt;'; } echo'&lt;br&gt;&lt;br&gt;&lt;br&gt;'; echo '&lt;a href="../../pagineHtml/inserimento/inserimentoGenerale/inserimentoCantiere.php" class="myButton" alt="Nuovo Cantiere +"&gt;Nuovo Cantiere +&lt;/a&gt;'; } else { echo "0 results"; } $conn-&gt;close(); ?&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Progetto Cantiere&lt;/title&gt; &lt;!-- Bootstrap --&gt; &lt;link href="../paginaIniziale/css/bootstrap-4.0.0.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php } ?&gt;</code></pre> </div> </div> </div>

优化PHPExcel和脚本以加载文件

<div class="post-text" itemprop="text"> <p>First of all, clarify that I have seen many topics on the optimization of the reading of the excel file, but having applied some of the solutions and without finding the one that helps me.</p> <p>I have a system that at a certain point, invokes another php that calls the excel library. This system, what it does is read an excel file, and record its information in SQL, to then generate PDF.</p> <p><strong>index.php</strong></p> <pre><code>&lt;?php .... include("read_excel.php"); .... ?&gt; </code></pre> <p>I have seen that the load of my index takes approximately 20 seconds, so I have started to dispense parts of my code to see where the problem was, and identify that it was in the file "read_excel.php"</p> <p><strong>read_excel.php</strong></p> <pre><code>&lt;?php $sql_host = "127.0.0.1"; $sql_username = "root"; $sql_password = ""; $sql_database = "payment_locations"; $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database); $mysqli-&gt;set_charset("utf8"); require_once("_library/PHPExcel/Classes/PHPExcel.php"); $fileName = '_excel/locations.xlsx'; if (!file_exists($fileName)){ ?&gt; &lt;script type="text/javascript"&gt; alertify.alert("No exists file"); &lt;/script&gt; &lt;?php }else{ $objPHPExcel = PHPExcel_IOFactory::load($fileName); $date = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('U11')-&gt;getValue(); $dateFormat = date('d/m/Y', PHPExcel_Shared_Date::ExcelToPHP($date)); // echo $dateFormat; // $dto = PHPExcel_Shared_Date::ExcelToPHPObject($objPHPExcel-&gt;getActiveSheet()-&gt;getCell('U11')-&gt;getCalculatedValue()); // echo $dto-&gt;format('d-m-Y'); for ($i = 11; $i &lt;= 31; $i++) { if ((float) $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('A' . $i)-&gt;getCalculatedValue() == 0) { break; } $dataExcel[$i]['id_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('A' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['payment'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('X' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['period_to'] = PHPExcel_Shared_Date::ExcelToPHPObject($objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AC' . $i)-&gt;getCalculatedValue()); $dataExcel[$i]['period_from'] = PHPExcel_Shared_Date::ExcelToPHPObject($objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AD' . $i)-&gt;getCalculatedValue()); $dataExcel[$i]['support'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('J' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['location'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('H' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['comments'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AF' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['name_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('E' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['ci_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('F' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['tel_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('G' . $i)-&gt;getCalculatedValue(); $dataExcel[$i]['address_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('I' . $i)-&gt;getCalculatedValue(); } foreach ($dataExcel as $dataRow =&gt; $value) { $dateFormatPeriodTo = $value['period_to']-&gt;format('d/m/Y'); $dateFormatPeriodFrom = $value['period_from']-&gt;format('d/m/Y'); // var_dump($dateFormatPeriodTo); //$dateFormatPeriodTo = date('d/m/Y', PHPExcel_Shared_Date::ExcelToPHP($value['period_to'])); $sql = "REPLACE data_locator (id_locator, payment, period_to, period_from, support, location, comments, name_locator, ci_locator, tel_locator, address_locator) VALUES ({$value['id_locator']}, {$value['payment']}, '$dateFormatPeriodTo', '$dateFormatPeriodFrom', '{$value['support']}', '{$value['location']}', '{$value['comments']}', '{$value['name_locator']}', {$value['ci_locator']}, '{$value['tel_locator']}', '{$value['address_locator']}')"; // echo $sql; $result = $mysqli-&gt;query($sql); } for ($j = 42; $j &lt;= 55; $j++) { if ((float) $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('A' . $j)-&gt;getCalculatedValue() == 0) { break; } $dataExcelTwo[$j]['id_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('A' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['payment'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('X' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['period_to'] = PHPExcel_Shared_Date::ExcelToPHPObject($objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AC' . $j)-&gt;getCalculatedValue()); $dataExcelTwo[$j]['period_from'] = PHPExcel_Shared_Date::ExcelToPHPObject($objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AD' . $j)-&gt;getCalculatedValue()); $dataExcelTwo[$j]['support'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('J' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['location'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('H' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['comments'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('AF' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['name_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('E' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['ci_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('F' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['tel_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('G' . $j)-&gt;getCalculatedValue(); $dataExcelTwo[$j]['address_locator'] = $objPHPExcel-&gt;getActiveSheet()-&gt;getCell('I' . $j)-&gt;getCalculatedValue(); } foreach ($dataExcelTwo as $dataRow =&gt; $value) { $dateFormatPeriodTo = $value['period_to']-&gt;format('d/m/Y'); $dateFormatPeriodFrom = $value['period_from']-&gt;format('d/m/Y'); // var_dump($dateFormatPeriodTo); //$dateFormatPeriodTo = date('d/m/Y', PHPExcel_Shared_Date::ExcelToPHP($value['period_to'])); $sql = "REPLACE data_locator (id_locator, payment, period_to, period_from, support, location, comments, name_locator, ci_locator, tel_locator, address_locator) VALUES ({$value['id_locator']}, {$value['payment']}, '$dateFormatPeriodTo', '$dateFormatPeriodFrom', '{$value['support']}', '{$value['location']}', '{$value['comments']}', '{$value['name_locator']}', {$value['ci_locator']}, '{$value['tel_locator']}', '{$value['address_locator']}')"; // echo $sql; $result = $mysqli-&gt;query($sql); } } ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;title&gt;&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"&gt; &lt;link rel="stylesheet" href="_css/datepicker.css"&gt; &lt;script src="_js/alertify.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/3.2.0/css/bootstrap.min.css"/&gt; &lt;link rel="stylesheet" href="_css/style.css"&gt; &lt;link rel="stylesheet" href="_css/alertify.default.css"&gt; &lt;link rel="stylesheet" href="_css/alertify.core.css"&gt; &lt;link rel="stylesheet" href="_css/alertify.bootstrap3.css"&gt; &lt;link href='https://fonts.googleapis.com/css?family=Roboto:400,700,300,900' rel='stylesheet' type='text/css'&gt; &lt;link rel="icon" href="_images/favicon.png" type="image/gif" sizes="16x16"&gt; &lt;link rel="stylesheet" href="alertify.default.css"&gt; &lt;link rel="stylesheet" href="alertify.core.css"&gt; &lt;link rel="stylesheet" href="alertify.bootstrap3.css"&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>After erasing almost all the code blocks in my read file "read_excel.php", I could see that the line that delayed the execution of my index (which invokes read_excel.php)</p> <pre><code>$objPHPExcel = PHPExcel_IOFactory::load($fileName); </code></pre> <p>Once I delete that line, my index loads in milliseconds.</p> <p>So, my question is, is wrong my way of invoking the excel file that I want to read?</p> <p>The size of my excel is only 110 KB, I do not think this is a problem, is it?</p> <p>I'm running my software on a local server, (wamp server 2.5), and Windows 7 64bits. Could be a problem?</p> <p>I have seen topics where optimizations are suggested for files where a lot of information is processed, but in my case it is a small file and I only use excel blocks (for condition) and this does not seem to be the problem, because the loading speed of my index varies when I eliminate the line:</p> <pre><code>$objPHPExcel = PHPExcel_IOFactory::load($fileName); </code></pre> <p>Can it be the version of the excel library that I am using?</p> <p>Thanks!</p> </div>

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

Python可以这样学(第一季:Python内功修炼)

Python可以这样学(第一季:Python内功修炼)

C++语言基础视频教程

C++语言基础视频教程

Python可以这样学(第四季:数据分析与科学计算可视化)

Python可以这样学(第四季:数据分析与科学计算可视化)

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

网络工程师小白入门--【思科CCNA、华为HCNA等网络工程师认证】

Python数据分析与挖掘

Python数据分析与挖掘

相关热词 c# 开发接口 c# 中方法上面的限制 c# java 时间戳 c#单元测试入门 c# 数组转化成文本 c#实体类主外键关系设置 c# 子函数 局部 c#窗口位置设置 c# list 查询 c# 事件 执行顺序
立即提问