AUTO_INCREMENT 값 초기화
아래와 같이 쿼리하면 된다 alter table 테이블명 auto_increment=1
키자드에 등록된 총 535개의 포스트를 확인하실 수 있습니다.
navigator.userAgent 로 접속 기기를 체크할 수 있다 if(navigator.userAgent.match("iPhone")) alert('아이폰'); else if(navigator.userAgent.match("iPad")) alert('아이패드); else if(navigator.userAgent.match("Android")) alert('안드로이드);
document.getElementById(id).style.display = "none"; document.getElementById(id).style.display = "block";
$('#memberLayer').attr('style', 'display:block'); $('#memberLayer').attr('style', 'display:none');
select sum(point) from( select sum(point) as point from test1 where id='24021' union all select sum(point) as point from test2 where uid='ytn24' )as a 2개의 쿼리 결과를 sum 한다
function get_content($url) { $agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)'; $curlsession = curl_init (); curl_setopt ($curlsession, CURLOPT_URL, $url); curl_setopt ($curlsession, CURLOPT_HEADER, 0); curl_setopt ($curlsession, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($curlsession, CURLOPT_POST, 0); curl_setopt ($curlsession, CURLOPT_USERAGENT, $agent); curl_setopt ($curlsession, CURLOPT_REFERER, ""); curl_setopt ($curlsession, CURLOPT_TIMEOUT, 3); $buffer = curl_exec ($curlsession
* SNOOPY 다운로드 : http://snoopy.sourceforge.net/ 웹 페이지를 가져와서 파싱할수 있도록 도와주는 도구이다. 사용은 아래와 같이한다. include "../_snoopy/Snoopy.class.php"; $snoopy = new Snoopy; $snoopy->fetch("http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=11&ncvContSeq=&contSeq=&board_id=&gubun="); preg_match('/<table class="num minisize">(.*?)<\/table>/is', $snoopy->results, $tmp1);
네이버tvcast 동영상에 들어가면 재생수가 표시되는데 이를 가져오는 방법이다. snoopy를 사용했으며 활용하여 여러가지 값을 가져올 수 있다. include "../_snoopy/Snoopy.class.php"; $snoopy = new Snoopy; $snoopy->fetch("http://tvcast.naver.com/v/671154"); $txt = $snoopy->results; $txt = str_replace("\r","",$txt); $txt = str_replace("\n","",$txt); //재생수 축출 $rex = "/\<span class=\"play\">(.+?)\<\/span\>/"; preg_match_all($rex,$txt,$temp); $num = preg_replace("/[^0-9]*/s", "", strip_tags($temp[0][0])); echo "재생수 : {$num}";
Snoopy를 사용했으며 다음tv팟은 웹페이지에서 바로 정보를 가져올 수 없다. 패킷을 분석해보면 json으로 정보를 가져오는 걸 확인할 수 있는데 이를 사용하여 정보를 가져온다. include "../_snoopy/Snoopy.class.php"; $snoopy = new Snoopy; $url = "http://tvpot.daum.net/mypot/json/GetClipInfo.do?clipid=73378540"; $snoopy->fetch($url); //play_count $txt = json_decode($snoopy->results); echo $txt->{'clip_bean'}->{'play_count'};
* https://developer.dailymotion.com/tools/sdks#sdk-php PHP API 를 사용해 데일리모션에 동영상을 업로드 하는 소스이다. SDK는 위의 사이트에서 확인 후 다운로드하면된다. include("Dailymotion.php"); $apiKey = ""; $apiSecret = ""; $username = ""; $pwd = ""; $filePath = "1.mp4"; $api = new Dailymotion(); $api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_videos', 'write','delete'), array('username' => $username, 'password' => $pwd)); try { $url = $api->uploadFile($filePath); $result = $api->call('video.creat
$api = new Dailymotion(); $api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_playlists', 'write','delete'), array('username' => $username, 'password' => $pwd)); //생성 $result = $api->post('/me/playlists',array('name' => '음악', 'description' => '음악')); //추가 if ($result && !empty($result['id'])) $api->post("/playlist/{$result['id']}/videos/{$videoID}"); //수정 $api->post("/playlist/{$playlistId}", array('name' => 'New playlist name', )); //삭제 $api->delete("/playlis
기본정보 및 동영상까지도 수정가능하다. * 동영상 수정 $api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_videos', 'write','delete'), array('username' => $username, 'password' => $pwd)); $videoId = '수정을 원하는 동영상 아이디'; $url = $api->uploadFile($filePath); //동영상을 수정할 경우 신규 동영상 업로드 $api->post("/video/{$videoId}", array( 'url' => $url, 'title' => '동영상 수정 테스트', 'description' => '내용 수정 테스트', 'thumbnail_url' => '신규 이미지 주소', ) ); * 동영상 삭제 $videoId = '삭제를 원하는 동영상 아이디'; $api->delete("/video/{$v
char 형에 숫자를 저장할 때 정렬을 하면 10을 넘는 숫자에서 아래와 같은 현상이 발생한다. * 1, 10, 11, 2, 21, 3, 4, 5 위와 같이 원하는 숫자순서대로 정렬이 되지 않을 경우 아래와 같이 +0 을 해주면 된다. * select * from test order by ord+0 asc
iconv 사용시 입력문자열이 너무 길 경우 (내 환경에서는 strlen으로 16500 이상) 문자열이 잘려서 나오는 문제가 발생했다. 검색을 해봐도 그런 증상을 겪은 사람이 없는지 그런 글이없다. 일단은 문자열을 잘라서 해결했는데 여기저기 알아보다 mb_convert_encoding 를 사용해보라고 해서 해봤더니 이 함수는 그런 증상이 발생하지 않는다. 앞으로 mb_convert_encoding 를 사용.
<!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <style> * {margin:0; padding:0;} img {vertical-align:bottom;} #btn1 { position:absolute; top:30px; left:540px; display:none;} #btn2 { position:absolute; top:30px; left:540px; } </style> </head> <body> <div id="btn_bg"> <div id="btn1"><a href="http://www.naver.com"><img src="1.png" /></a></div> <div id="btn2"><a href="http://www.naver.com"><img src="2.png" /
10초간격으로 chg() 함수호출 t = setInterval(chg, 10000); // 1000 = 1초입니다. function chg(){}
아래 둘중 하나를 선택해서 사용하면 된다. * <a href="#test" onclick="test();return false;" onkeypress="this.onclick;"> * <a href="http://naver.com" onclick="test(this.href);return false;" onkeypress="this.onclick;">
URL이 http://test.com:8088/test.php?num=1 일 경우 window.location.hostname; // => test.com window.location.href; // => http://test.com:8088/test.php window.location.host; // => test.com:8088 window.location.port; // => 8088 window.location.pathname; // => test.php window.location.search; // => ?num=1 window.location.protocol; // => http:
아래와 같이 변수에 담아서 사용할 수 있다. * var nowAddress = unescape(document.referrer);
mb_detect_encoding 함수사용 <?php /* Detect character encoding with current detect_order */ echo mb_detect_encoding($str); /* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */ echo mb_detect_encoding($str, "auto"); /* Specify encoding_list character encoding by comma separated list */ echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win"); /* Use array to specify encoding_list */ $ary[] = "ASCII"; $ary[] = "JIS"; $ary[] = "EUC-JP"; echo mb_detect_encoding($str, $ary); ?>
http:naver.com/index.php 위와 같이 주소가 있을 경우 /index.php 값을 변경하는 함수이다. * history.pushState("","","/변경"); * history.replaceState("","","/변경");
* ceil : 소수부분이 존재할 때 값을 올려서 리턴 * floor : 소수부분이 존재할 때 소수값을 버린 후 리턴 * round : 소수부분이 존재할 때 소수 부분이 0.5 보다 크면 값을 올리고 작으면 버린 후 리턴, 반올림 지점을 지정할 수 있다
명령어의 위치를 확인하고자 할 때 사용하는 명령어는 which 입니다. 예를 들어 mysql 명령어의 위치를 확인하려면 which mysql
iconv 로 utf-8 에서 euc-kr 로 변경할 때 뷁, 렜, 삻 등의 문자들은 처리되지 않아 제거되거나 함수에서 오류가 발생한다 이럴경우 CP949 를 사용하면 된다. CP949 는 확장완성형 한글코드이다. * $temp = iconv("UTF-8","CP949",$temp);
* length() : 길이를 bytes로 구한다. * char_length() : 글자의 수를 구한다 * bit_length() : 길이를 bit로 구한다
DELIMITER // CREATE PROCEDURE '프로시저명' (IN isub_cd VARCHAR(6)) begin select * from test; end call '프로시저명' 을 하면 프로시저가 실행된다
아래는 예외발생시 쿼리를 중단하고 오류 메세지를 리턴하는 프로시저 선언이다 DELIMITER // CREATE PROCEDURE '프로시저명' (IN isub_cd VARCHAR(6)) begin DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN SHOW ERRORS; END; select * from test; end
아래와 같이 explain 을 사용하면 실행계획을 확인할 수 있다. explain select * from HISTORY where join_key='201303290057097458'
프로시저 실행 시 쿼리 속도가 그냥 쿼리를 하는 것보다 속도가 느리다면 explain 으로 실행계획을 확인해보자. 나같은 경우는 varchar 값을 받아 where 절에 넣을 경우 쿼리 속도가 느려지는 현상이 나타났는데 explain 으로 실행 계획을 확인하니 인덱스를 타지 않고 있었다. 구글링과 여러 테스트를 한결과 문제는 MyISAM 의 문제였다. InnoDB로 새로 생성하여 확인결과 현상이 사라졌다.
strpos 의 3번째 입력값인 offset 을 사용하면 됩니다. $temp = "abcd abcd abcd abcd"; //2번째 a의 위치를 찾는다 for($i=0, $pos=0;$i<2;$i++) $pos=strpos($temp,"a",$pos+1); //2번째 a앞까지의 문자열을 출력한다 echo substr($temp, 0, $pos+1);
div ul 을 사용하여 펼쳐지는 메뉴를 사용할 경우 마우스가 벗어나면 메뉴를 닫으려고 onmouseout 을 사용하는 경우가 있다. 그런데 의도와 달리 벗어나기 전에 onmouseout 이벤트가 발생하는 경우가 있는데 이럴 경우 onmouseleave 함수를 사용하면 해결된다. 반대 함수로는 onmouseenter 가 있다
API KEY, SECRET KEY, ID, PW 를 입력하면 ACCESS TOKEN을 리턴한다. function getAccessToken($key, $secret, $id, $pw){ $url = "https://api.dailymotion.com/oauth/token"; $data = array('grant_type' => 'password', 'client_id' => $key, 'client_secret' => $secret,'username' => $id, 'password' => $pw); $data = http_build_query($data); $ch=curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $result=
jquery.marquee.js 에서 기능을 지원하지 않기 때문에 js를 수정하여 만들어줘야한다. 첨부파일은 수정된 파일이다. //정지 $("#scrollnews").marquee('pause'); //시작 $("#scrollnews").marquee('resume'); //위 $("#scrollnews").marquee('next'); //아래
페이지 로딩시 test.php 에서 데이터를 읽어와 cmp_1 에 뿌려줌 $(document).ready(function (){ $.ajax ({ "url" : "./test.php", cache : false, success : function (html) { document.getElementById("cmp_1").innerHTML = html; } }).done(function(){}); });
$xml_data = file_get_contents($url); $arrXML = simplexml_load_string($xml_data); // 우선 json으로 변환. 만약 응답데이터로 활용한다면 $json 으로 보내는게 좋겠지. $json = json_encode($arrXML); // json 데이터를 배열로 변환. 2번째 파라메터에 true를 넣지 않으면 object 형태로 반환되어 지저분해짐. $arr = json_decode($json, true);
<li id="tabMenu1" class="tab1">호가</li> 위와같은 class 변경 시 아래와 같이 document.getElementById("tabMenu1").className = "tab1 on";
obj 위치까지 스크롤을 이동시킨다 var position = $("#obj").offset(); $('html, body').animate({scrollTop : position.top}, 2000);
- 하루전 : . DATE_FORMAT(DATE_ADD(now(),INTERVAL - 180 DAY),'%Y-%m-%d') . YYYY-MM-DD 형태로 -1 DAY 를 출력 - 한시간전 : . DATE_FORMAT(DATE_ADD(now(),INTERVAL - 60 MINUTE),'%Y-%m-%d %H:%i:%s') - 5분전 . DATE_SUB(NOW(), INTERVAL 5 MINUTE)
* 200자 제한시 <textarea name="ask4" rows="5" cols="20" maxlength="5" onKeyup='javascript:maxChk()'></textarea> function maxChk(){ var f = document.iForm; if(f.ask4.value.length > 200) { alert("글자수는 200자로 제한됩니다."); f.ask4.value=f.ask4.value.substring(0,200); f.ask4.focus(); } }
<script language='javascript'> function noEvent() { if (event.keyCode == 116) { alert('새로고침금지!!'); event.keyCode= 2; return false; } } } document.onkeydown = noEvent; </script>
* 텍스트박스에 표시되는 날짜형식 변경 . $( "#datepicker" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); * 달력위치 변경 . $('.ui-datepicker ').css({"margin-left" : "141px","margin-top": "200px"}); * 년, 월 한글표시 . $( "#datepicker" ).datepicker({ monthNames: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'], monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'], yearSuffix: '년' }); * 기본 소스1 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui
group by 해서 나온데이터가 최신 데이터를 원할 경우가 있다. 만약 아래와 같이 단순 group by 하면 그 결과로 나오는 아이디, 이름, 전화번호가 최신 값으로 나오지 않는다 . select id, name, hp from member group by id 이럴 경우 서브쿼리를 사용해서 정렬 후 group by 해줘야 한다. . select * from ( select id, name, hp from member order by date desc )a group by id
* 스크립트안의 공백제거하기 - $str = preg_replace('/<script>.*?<\/script>/ise', "str_replace(' ', '', '$0')", $str); * 태그안에 style= 속성 제거 - $str=preg_replace("/ zzstyle=([^\"\']+) /"," ",$str); // style=border:0 따옴표가 없을때 - $str=preg_replace("/ style=(\"|\')?([^\"\']+)(\"|\')?/","",$str); // style="border:0" 따옴표 있을때 * 태그안의 width=, height= 속성 제거 - $str=preg_replace("/ width=(\"|\')?\d+(\"|\')?/","",$str); - $str=preg_replace("/ height=(\"|\')?\d+(\"|\')?/","",$str); * 특수문자 제거 - $string = preg_replace("/[ #\&\+
<script> function play(id, opt){ if(opt==1)document.getElementById(id).Play(); else document.getElementById(id).Pause(); } </script> <embed id="player" src="mms://test.mp3" type="application/x-mplayer2" autostart=false showaudiocontrols="false" showpositioncontrols="false" showtracker="false" showControls="false" ></embed> <a href="#" onClick="play('player','1');return false;">재생</a> / <a href="#" onClick="play('player','0');return false;">중지</a>
flowplayer 를 이용하여 mp3 재생 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://releases.flowplayer.org/js/flowplayer-3.2.11.min.js"></script> <a id="mb" style="display:block;width:648px;height:30px;" href="test.mp3"></a> <script> $f("mb", "http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf", { // fullscreen button not needed here plugins: { controls: { fullscreen: false, height: 30, autoHide: false } }, // we a
if(document.createElement('audio').canPlayType) alert('지원'); else alert('미지원');
php 에서 엑셀파일을 만들때 개행문자 \n\r 은 엑셀에서 처리되지 않는다 그래서 아래와 같이 처리해준다 $content = str_replace("\n\r","<br style='mso-data-placement:same-cell;'>",$row[content]);
링크거는거 말고 파일다운로드 구현시 $file : 파일명 $url : 파일 URL header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$file.'"'); readfile($url);
function insertArray($arr, $idx, $add){ $arr_front = array_slice($arr, 0, $idx); $arr_end = array_slice($arr, $idx); $arr_front[] = $add; return array_merge($arr_front, $arr_end); }
if(preg_match("/MSIE|Trident|\|/i", $_SERVER['HTTP_USER_AGENT'])) echo "IE";
function cutString(str, max) { ns = str.substr(0, max); if (ns.length != str.length) ns = ns + ""; return ns+"..."; }
if(navigator.userAgent.toLowerCase().indexOf('trident')!=-1 || navigator.userAgent.toLowerCase().indexOf('msie')!=-1)
자바스크립트로 페이스북 로그인 연동소스 <script> function statusChangeCallback(response) { // response 객체는 현재 로그인 상태를 나타내는 정보를 보여준다. // 앱에서 현재의 로그인 상태에 따라 동작하면 된다. // FB.getLoginStatus().의 레퍼런스에서 더 자세한 내용이 참조 가능하다. if (response.status === 'connected') { // 페이스북을 통해서 로그인이 되어있다. facebookLoginProc(); } else if (response.status === 'not_authorized') { // 페이스북에는 로그인 했으나, 앱에는 로그인이 되어있지 않다. } else { // 페이스북에 로그인이 되어있지 않다. 따라서, 앱에 로그인이 되어있는지 여부가 불확실하다. } } // 이 함수는 누군가가 로그인 버튼에 대한 처리가 끝났을 때 호출된다. onlogin 핸들러를 아래와 같이 첨부하면
아래의 사이트를 통해 압축 후 저장하면 된다. * https://jscompress.com/ * http://javascriptcompressor.com/
//추가, 변경 $('a').attr('href','http://naver.com'); //삭제 $('a').removeAttr('href');
//버튼 텍스트 가져오기 $("#sBtn1").html("Loading...."); //버튼 텍스트 바꾸기 $("#sBtn1").html("Loading....");
<input type='checkbox' name='listChk[]' value='1'> <input type='checkbox' name='listChk[]' value='2'> <input type='checkbox' name='listChk[]' value='3'> 위와 같이 있을 경우 alert( $("input[name='listChk[]']:checked").length ); 선택 된 개수를 가져올 수 있다 아래와 같이 선언했을 경우는 <input type='checkbox' name='listChk' value='1'> <input type='checkbox' name='listChk' value='2'> <input type='checkbox' name='listChk' value='3'> alert( $("#listChk:checked").length );
* 한국 사용자 포럼 . http://www.codeigniter-kr.org/ * 강좌 사이트 . https://opentutorials.org/course/697/3840
* MVC 형식으로 프로그램 작성 . MODEL : DB 로 models 폴더에 파일들이 있다 . VIEW : VIEW 로 views 폴더에 파일들이 있다 . CONTROLLER : 제어로 controllers 폴더에 파일들이 있다 * URL 구성 형식 . test.com/index.php/class/method/id . class : 클래스명 . method : 해당 클래스의 함수명 . id : 입력 인자 . /config/routes.php 에서 형식을 변경할 수 있다 * POST 값 가져오기 . $this->input->post('inputID'); * 기본 흐름 1. controller 파일 호출 2. model 로 데이터 처리 . $this->load->model('Store_model'); . $data = $this->Store_model->getEpilogueData($id); 3. view 를 호출하여 페이지를 보여줌 . $this->load->view('templa
* routes.php . $route['topic/(:num)'] = "topic/get/$1"; topic/get/1 -> topic/1 로 변경 . $route['(:any)'] = 'pages/view/$1'; -> 어떤 주소 형식이든 pages 클래스의 view 함수를 탄다는 의미 . $route['default_controller'] = "index" : 기본주소 입력시 나오는 페이지 세팅
* 세션 가져오기 . $this->session->userdata('ID'); * 세션 설정 . $this->session->set_userdata(array( 'usrId' => $data->Id, 'usrNm' => $data->UserName, 'status' => STATUS_ACTIVATED, 'aCode' => $data->AuthorityCode, 'usrIdx' => $data->Idx ));
* libraries 폴더에 클래스 파일 생성 * 아래와 같이 로드하여 사용 . $this->load->library('commfunc'); . $rst = $this->commfunc->getNaverBlog($this->input->get('bKeyword'));
함수로 제작해 봤다 리턴값은 제목, 내용, 링크, 블로그명이다. 네이버 API 를 검색하면 예제 소스를 볼 수 있다 (https://developers.naver.com/docs/search/blog/) function getNaverBlog($keyword){ $client_id = "MO2JiPxEvVLmM8KOqgtV"; $client_secret = "XEvrWIJ1ib"; $encText = urlencode($keyword); $url = "https://openapi.naver.com/v1/search/blog.xml?query=".$encText; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = array(); $headers[] = "X-Nav
만약 아래와 같이 " 가 들어가 있는 문자을 input 태그의 value 값에 넣으면 오류가 발생한다 $str = '테스트 문자열 "쌍따음표" 입니다'; <input type='input' value='<?=$str?> /> 이럴 경우 아래와 같이 치환작업을 해줘야 한다. $str = str_replace("\"",""",$str);
1. 추가 $('.m_tit').addClass( 'm_tit_hover menu01_hover' ); 2. 삭제 $('.m_tit').removeClass( 'm_tit_hover menu01_hover' ); 3. 변경 $("#tab01").attr("class", "tab01 on");
Math.random() 함수를 사용하여 램덤수를 구할 수 있다 * N 보다 작은 랜덤 수 구하기 . Math.floor(Math.random() * N) * 0~9 중 랜덤 수 구하기 . Math.floor(Math.random() * 10) * 범위 지정 랜덤 수 구하기 (5~10 중 랜덤 수 구하기) . Math.floor ( (Math.random() * (10 - 5 + 1)) + 5)
$("#ID").position() $("#ID").position().top $("#ID").position().left
광고 스크립트는 lazy 로딩 처리가 되지 않아 아래와같이 특정위치까지 스크롤이 되면 그때 광고가 로딩되도록 처리했다. <div id="ad"> <script> var check = true; $(window).scroll(function(){ if(check && ($(window).scrollTop() > ($("#ad").position().top) - 200 - $(window).height())){ check = false; //광고 스크립트 처리 }}); </script> </div>
* https://developer.yahoo.com/performance/rules.html 1. Minimize HTTP Requests(HTTP요청을 최소화하라) 2. Use a Content Delivery Network(CDN을 이용하라) 3. Add an Expires or a Cache-Control Header(응답헤더에 Expires 혹은 Cache-Control을 추가하라) 4. Gzip Components(gzip으로 압축하라) 5. Put Stylesheets at the Top(스타일시트는 문서의 위쪽에 넣어라) 6. Put Scripts at the Bottom(스크립트는 문서의 아래쪽에 넣어라) 7. Avoid CSS Expressions(CSS Expression을 피하라) 8. Make JavaScript and CSS External(자바스크립트와 CSS는 외부 파일로 만들어라) 9. Reduce DNS Lookups(DNS 검색을 줄여라) 10. M
* YSlow YSlow는 앞에서 언급한 웹 사이트 성능 최적화 법칙을 웹 사이트가 얼마나 만족하고 있는지 측정하는 도구다. 다양한 브라우저 확장 프로그램 버전을 제공하고 있으며, http://yslow.org/에서 다운로드할 수 있다. YSlow는 현재 35개 법칙 중 프로그램으로 측정할 수 있는 23개 법칙(앞에서 35개 법칙 중 굵은 글자로 표시해 두었다)을 분석해 자체 기준에 따라 A~F까지 등급을 분류해서 보고한다. 등급 및 점수는 참고 사항이므로 자신의 웹 사이트 상황과는 안 맞을 수 있다. 보고서 점수에 너무 연연하지 말고 보고서 내용을 참고하여 상황에 맞게 최적화하면 된다. 자세한 등급과 점수는 "YSlow Ruleset Matrix(http://yslow.org/ruleset-matrix)" 문서에서 확인할 수 있다. * PhantomJS(http://phantomjs.org/) PhantomJS는 WebKit 엔진으로 브라우저를 에뮬레이팅해 커맨드라인에서 JavaS
* https://developers.google.com/speed/pagespeed/insights/ 위의 사이트에서 성능 개선을 위한 테스트 및 팁을 제공한다
JAVASCRIPT 웹페이지 바로 호출 zgabriel 2017. 12. 14. 16:16 이웃추가 본문 기타 기능 해당 페이지를 바로 호출해준다 var dynamic = new jes.DynamicScript(); dynamic.call('/test.php?i='+idx);
JQUERY 다중 체크박스 처리 zgabriel 2018. 1. 10. 13:14 이웃추가 본문 기타 기능 <input id="box" type="checkbox" class="chkBox"> <input id="box" type="checkbox" class="chkBox"> 위와같이 체크박스가 있을 경우 [해제/설정] #("input[id='box']")[1].checked = true; //설정 #("input[id='box']")[1].checked = false; //해제 [클릭 이벤트] #("input[id='box']").on('click', function(e){ //클릭 한 체크박스 인덱스 alert(#("input[id='box']").index(this)); });
PHP 문자열을 날짜포맷으로 바꾸기 zgabriel 2018. 1. 19. 13:19 이웃추가 본문 기타 기능 $temp = "20180119085517"; $date = date("Y-m-d H:i:s", strtotime( $temp ) );
기타 데일리모션 동영상 업로드 DMRSS zgabriel 2018. 1. 23. 14:16 이웃추가 본문 기타 기능 * http://www.dailymotion.com/dmrss 데일리모션에 동영상을 업로드할 경우 API를 사용하는 방법이 있고 FTP를 제공받아 업로드하는 방법이 있다 FTP를 이용할 경우 이 MRSS 를 사용하는데 해당 문서 형식에 맞게 XML 을 작성하여 FTP 에 업로드하면 데일리모션에서는 처리 후 CALL BACK으 로 결과 값을 반환해준다.
PHP 문자열의 마지막 문자 가져오기 zgabriel 2018. 3. 13. 18:03 이웃추가 본문 기타 기능 $temp = "abcd"; echo substr($temp, -1); 위와 같이 하면 d 를 리턴한다
JAVASCRIPT 팝업창 중앙출력 zgabriel 2018. 3. 16. 9:38 이웃추가 본문 기타 기능 var left = (window.screen.width / 2) - (팝업창 넓이/ 2); var top = (window.screen.height /2) - (팝업창 높이/ 2); window.open('./popup.php','popup','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top='+top+',left='+left+',width=430,height=200');
PHP a 태그 클릭 시 파일다운로드 처리 zgabriel 2018. 3. 16. 10:34 이웃추가 본문 기타 기능 a 태그 클릭 시 브라우저에 따라 파일을 다운로드 하지 않고 바로 보여주는 경우가 있다. 브라우저 설정을 통해 무조건 다운로드를 실행하게 할수도 있 는데 그건 패스하고 프로그램단에서 다운로드를 처리하는 방식이다. 일단 a 태그로 다운로드 페이지로 파일정보를 넘겨 아래의 코드로 파일 다 운로드 처리한다. header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=저장파일명"); header("Content-Transfer-Encoding: binary"); header("Content-Type: binary/octet-stream"); readfile("http://test.com/test.jpg")
JQUERY js 파일 동적로딩하기 zgabriel 2018. 4. 11. 14:23 이웃추가 본문 기타 기능 jquery 로 js 파일 동적 로딩 시 아래와 같이 적용한다. $.getScript( "http://test.com/test.js" ) .done(function( script, textStatus ) { console.log("done"+textStatus ); }).fail(function( jqxhr, settings, exception ) { console.log("fail="+ exception ); });
PHP 문자열 길이 구하기 (모든 문자를 1로 처리) zgabriel 2018. 4. 12. 10:56 이웃추가 본문 기타 기능 strlen("test테스트"); 위와 같이 하면 한글은 3으로 판단하여 결과를 출력한다 이건 길이를 체크한다는 개념보다는 size 를 체크하는 것 같은데 모든 문자를 1로 해서 길이를 체크하고 싶으면 아래와 같이 하면된다 mb_strlen("test테스트", "utf-8")
PHP Firebase 동적링크 생성 (단축 url) zgabriel 2018. 7. 17. 15:14 이웃추가 본문 기타 기능 firebase를 사용하여 단축 url 을 생성하는 방법이다. * https://firebase.google.com/docs/dynamic-links/rest 1. API 키가 필요하다 아래 URL 에 접속하여 APP 을 생성한다. . https://console.firebase.google.com/project/_/settings/general/ 2. 생성한 API 키를 메모한 후 좌측 메뉴에 Dynamic Links 클릭 3. Step 별로 클릭하여 단축 url로 사용할 domain 을 생성한다. 4. 소스 $url="https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=API키"; $headers = array('Content-Type:application/json'); $arr = array(
JAVASCRIPT [javascript] https 체크 zgabriel 2018. 9. 20. 9:53 이웃추가 본문 기타 기능 document.location.protocol 를 사용하면 https 에서는 https: 를 http에서는 http: 를 리턴한다. 아래는 http로 들어왔을 경우 https 로 변환하는 방법 if (document.location.protocol == 'http:') { document.location.href = document.location.href.replace('http:', 'https:'); }
PHP [PHP] 리퍼러 유지하며 리다이렉트 zgabriel 2018. 9. 21. 10:20 이웃추가 본문 기타 기능 리퍼러를 유지하며 페이지를 이동시키려면 아래와 같이 처리 header ('HTTP/1.1 301 Moved Permanently'); header ('Location: test.php');
JAVASCRIPT [JAVASCRIPT] 리퍼러 유지하며 리다이렉트하기 zgabriel 2018. 9. 21. 10:57 이웃추가 본문 기타 기능 아래의 함수를 사용하여 이동 var redirect = function(url) { var dom = window.document.createElement('form'); var parts = url.split('?'); var url_ = parts[0], params = parts[1] || ''; var paramlist = params.split('&'); dom.setAttribute('method', 'get'); dom.setAttribute('action', url_); dom.style.display = 'none'; dom.style.visibility = 'hidden'; var e, kv, k, v; for (var i = 0; i < paramlist.length; ++i) { kv = paramlist[i].sp
JQUERY IMG SRC 변경 zgabriel 2018. 9. 27. 11:14 이웃추가 본문 기타 기능 JQUERY 로 IMG SRC 변경하는 방법 <img id="img_area01" src="TEST_01.jpg" alt="" /> 위와 같이 IMG 태그가 있을 경우 아래와 같이 적용 $('#img_area01').attr("src","TEST_02.jpg");
PHP file_get_contents 으로 https 파일 가져오기 zgabriel 2018. 10. 5. 14:13 이웃추가 본문 기타 기능 file_get_contents 함수 사용 시 http 주소의 파일은 오류없이 가져오는데 https 주소의 파일을 가져오려면 오류가 발생한다. Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in ...php on line 2 이럴 경우 아래와 같이 구현한다. $context=array( "ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false, ), ); $content = file_get_contents("https://test.co
기타 IE Edge 에서 '이전 웹 기술과 관련된 문제...' zgabriel 2018. 11. 21. 9:24 이웃추가 본문 기타 기능 IE Edge 에서 웹페이지에 접속했을 때 아래와 같은 문구가 나온다면 "이전 웹 기술과 관련된 문제가 발생했습니다. 이 웹 사이트는 이전 기술에서 실행되며 Internet Exploerer에서만 작동합니다" 호환성 문제로 해결방법은 2가지가 있다. 1. 사용자라면 . 주소창에 about:flags 를 입력하여 개발자 설정에 들어간다 . 'Microsoft 호환성 목록 사용' 을 설정 해제후 브라우저를 재시작 2. 웹페이지 관리자라면 . http://cvlist.ie.microsoft.com/edge/desktop/1432152749/edgecompatviewlist.xml 리스트에 들어가 자신의 사이트 도메인이 있는지 확인한다 . 리스트에 포함되어 있다면 사이트에 아래의 메타태그를 포함시킨다. <meta http-equiv="X-UA-Compat
PHP strip_tags 사용시 문제해결 zgabriel 2018. 12. 14. 14:23 이웃추가 본문 기타 기능 strip_tags 함수를 사용하면 원하는 태그만을 삭제하는 것이 아닌 <> 안에 있는 모든 문자를 삭제한다. 최소한의 처리로 <> 안에 한글이 있는 경우 태그가 아닌걸로 판단하고 처리하는 방법이다. $temp = preg_replace('/<([^<a-zA-Z]+)>/i', '<$1>', $temp); $temp = strip_tags($temp); $temp = str_replace('<', '<', $temp); $temp = str_replace('>', '>', $temp);
PHP 태그에서 src 만 축출하기 zgabriel 2018. 12. 14. 14:38 이웃추가 본문 기타 기능 <iframe src='test.com'></iframe> 위와 같은 형태의 태그에서 src 내용만 뽑아내기 $tag = "<iframe src='test.com'></iframe>"; $f = "/<iframe[^>]*src=[\'\"]?([^>\'\"]+)[\'\"]?[^>]*>/"; preg_match_all($f,$tag,$rst); echo $rst[1][0];
<input type=text class=input1 name='test[]' onclick='getIndex(this)'> <input type=text class=input1 name='test[]' onclick='getIndex(this)'> 위와 같이 input 태그를 배열로 선언했을 경우 어떤 input box를 선택했는지 인덱스 값을 가져올 때 아래의 함수를 사용하면 됩니다. function getIndex(obj) { var names = document.getElementsByName(obj.name); for (var i = 0; i < names.length; i++) { if (names[i] === obj) return i; } }
* 삭제 document.getElementById('tab01').classList.remove('on'); * 추가 document.getElementById('tab02').classList.add('on');
파일 확장자를 체크하여 허용되지 않은 확장자는 차단하는 소스 //pdf 파일만 통과 $name = "test.php"; if(!preg_match("/(\.(pdf|PDF))$/i", $name)){ echo "해당 파일 차단"; }else{ echo "해당 파일 통과"; }
배열값을 post 로 넘길경우 아래와 같이 처리 * 넘기는 페이지 $temp = urlencode(serialize($array)); <input type=hidden name="temp" value="<?=$temp?>"> * 받는 페이지 $temp = unserialize(urldecode($_POST['temp']));
네이버 스마트 에디터는 2까지는 가져다 사용할 수 있는데 그 이후 버전부터는 비공개되어 있다. 아래는 개발정보이다. * 다운로드 : https://github.com/naver/smarteditor2 * 사용자 가이드 : http://naver.github.io/smarteditor2/user_guide/ * 데모 : http://naver.github.io/smarteditor2/demo/
추가, 삭제 버튼을 눌러 표에 row를 추가, 삭제하는 샘플 코드이다. <script> //ADD ROW function add(obj){ if(document.getElementById) var Tbl = document.getElementById('sample'); else var Tbl = document.all['sample']; //그외 브라우져일때.. if(obj==-1) var tRow = Tbl.insertRow(); else var tRow = Tbl.insertRow(obj.parentNode.parentNode.rowIndex+1); var cell0 = "<input type='text' class='inp2' id='month[]' name='month[]'>"; var cell1 = "<input type='text' class='inp2' id='day[]' name='day[]'>"; var cell2 = "<input type='text' class='
<input type='text' id='content[]' name='content[]'> <input type='text' id='content[]' name='content[]'> 위와같이 생성된 input 의 값 가져오기는 아래와 같이 처리 $('input[name="content[]"]')[0].value //값가져오기 $('input[name="content[]"]')[0].value = "1"; //값 넣기 select 태그도 동일하게 처리할 수 있다 $('select[name="content[]"]')[0].value //값가져오기 $('select[name="content[]"]')[0].value = "1"; //값 넣기
요즘 유튜브, 네이버, 다음등에서 동영상을 플레이한 후 스클롤을 내리면 플레이어가 화면 우측하단으로 작게 표시된다. 이를 간단하게 만들어 봤다. 필요한 개념은 모두 들어갔으니 응용해서 만들면 되겠다 <div id="Player"> <a href="play()"><img class="player_play_btn" /><img src="" width="100%" height="100%" /></a> </div> <script> var pTop; //플레이어 TOP var pLeft = $(window).width() - (270*2); //플레이어 LEFT $(window).scroll(function() { //플레이 했을 경우만 if($("#Player").html().indexOf("player_play_btn")==-1){ pTop = $(window).height() - (480*2) + $(this).scrollTop(); //스크롤 특정범위내에서만 플레이어를 우측하단으로 작