在URL中使用另一個url作為參數時會被`&`截斷的問題
阿新 • • 發佈:2018-03-22
轉換 blog value AD -a result too isset 工具 在URL中使用另一個url作為參數時會被
,後臺從
在URL中使用另一個url作為參數時會被&
截斷的問題
下午幫同事寫一個url轉二維碼的小工具時,發生標題中描述的問題。比如:輸入的url是http://www.example.dev/name=user&code=2000
,轉換為二維碼後,掃描得到的url卻是http://www.example.dev/name=user
,&
後的部分沒有正確轉換。問題很明顯,作為參數的url中的&
後的被解析為其他參數了。
前臺請求的完整url是"http://{domain}/tools/getQrCode.php?url=http://www.example.dev/name=user&code=2000
$_GET[‘url‘]
中取得卻是http://www.example.dev/name=user
,另一部分成了$_GET[‘code‘]
了。
解決方法其實很簡單,給作為參數的url做一下urlencode就好了。js中可以直接使用encodeURIComponent
函數為url編碼。
代碼示例如下:
- 後臺php
<?php $url = isset($_GET['url']) ? $_GET['url'] : ''; if (empty($url)) { echo '<div class="alert alert-danger" role="alert">請輸入url!</div>'; exit(1); } echo genQrCode($url); exit(0); function genQrCode($url=''){ require_once 'libs/phpqrcode.php'; $value = $url; //二維碼內容 $errorCorrectionLevel = 'L'; //容錯級別 $matrixPointSize = 5; //生成圖片大小 //生成二維碼圖片 $filename = '/../tmp/'.microtime().'.png'; QRcode::png($value, dirname( __FILE__ ) . $filename, $errorCorrectionLevel, $matrixPointSize, 2); return '<img src="tmp'. $filename . '"><br><p>' . $url . '</p>'; }
- 前臺html和js
之前的部分略 <div class="col-md-6 col-lg-6"> <div class="panel panel-warning"> <div class="panel-heading">二維碼轉換</div> <div class="panel-body"> <form> <div class="form-group"> <label for="url">url</label> <input type="text" class="form-control" id="url" placeholder="url"> </div> <button type="button" id="getQr" class="btn btn-primary">生成二維碼</button> <button type="reset" class="btn btn-success">清除url</button> </form> </div> <div id="qrdiv" class="panel-body" style="word-break: break-all;"> </div> </div> </div> </div> </div> <script type="text/javascript"> $( $("#getQr").click(function () { $qrstr=$("#url").val(); $url = "tools/getQrCode.php?url=" + encodeURIComponent($qrstr); $.get($url, function (result) { $("#qrdiv").html(result); }); }) ); </script> </body> </html>
PS:樣式部分使用的bootstrap3
以上
在URL中使用另一個url作為參數時會被`&`截斷的問題