[쿠키] - 사용자 브라우저에 저장되는 값(보안성이 없고 주로 장바구니 용도)

$_COOKIE['변수명']

쿠키 불러옴

setcookie()

쿠키 저장


[세션] - 서버에 저장되는 쿠키

$_SESSION['변수명']

으로 로딩 및 저장 가능


[캐시]

css,js,image 파일 사용자 브라우저에 저장



Posted by 모과이IT
,

HTML form으로부터 넘어온(post) file 오브젝트는 php에서 $_FILES에 담겨있습니다.
이를 이용하여 업로드를 구현하면 됩니다.

$_FILES에는 다음과 같은 변수로 값이 저장되어집니다.
아래는 file폼의 name값이 upfile이라는 가정하여 작성하였습니다.

$_FILES['upfile']['tmp_name'] = 웹서버에 임시로 저장된 파일의 위치
$_FILES['upfile']['name'] = 사용자 시스템에 있을 때의 파일 이름
$_FILES['upfile']['size'] = 파일의 바이트 크기
$_FILES['upfile']['type'] = 파일의 MIME 타입 예)text/plain | image/png
$_FILES['upfile']['error'] = 파일 업로드시 발생한 오류 코드


그렇다면 간단히 PHP에서는 어떻게 구성되는지 보겠습니다.

Posted by 모과이IT
,

php.ini 

opcache.enable=0



Posted by 모과이IT
,

$_SERVER['DOCUMENT_ROOT'] : 사이트 루트의 물리적 경로. ex) /home/ksprg/www


$_SERVER['HTTP_ACCEPT_ENCODING'] : 인코딩 받식. ex) gzip, deflate


$_SERVER['HTTP_ACCEPT_LANGUAGE'] : 언어. ex) ko


$_SERVER['HTTP_USER_AGENT'] : 사이트 접속한 클라이언트 프로그램 정보. ex) Mozilla/4.0(compatible; MSIE 7.0; Windows NT 5.1; Q312461; .NET CLR 1.0.3705


$_SERVER['REMOTE_ADDR'] : 사이트 접속한 클라이언트의 IP. ex) 192.168.0.100

 

$_SERVER['HTTP_REFERER'] : 현제 페이지로 오기전의 페이지 주소값. <a> 또는 <form> 태그로 전송시 값이 넘어옴. 

                                            ex) http://roadrunner.tistory.com/write.php 


$_SERVER['SCRIPT_FILENAME'] : 실행되고 있는 파일의 전체경로. ex) /home/ksprg/www/index.php


$_SERVER['SERVER_NAME'] : 사이트 도메인 : roadrunner.tistory.com (virtual host에 지정한 도메인)

 

$_SERVER['HTTP_HOST'] : 사이트 도메인 : roadrunner.tistory.com (접속할 때 사용한 도메인)


$_SERVER['SERVER_PORT'] : 사이트 포트. ex) 80


$_SERVER['SERVER_SOFTWARE'] : 서버의 소프트웨어 환경

                                                 ex) Apache/1.3.23 (Unix) PHP/4.1.2 mod_fastcgi/2.2.10 mod_throttle/3.1.2 mod_ssl/2.8.6


$_SERVER['GATEWAY_INTERFACE'] : CGI 정보. ex) CGI/1.1


$_SERVER['SERVER_PROTOCOL'] : 사용된 서버 프로토콜. ex) HTTP/1.1


$_SERVER['REQUEST_URI'] : 현재페이지의 주소에서 도메인 제외. ex) /index.php?user=ksprg&name=hong


$_SERVER['PHP_SELF'] : 현재페이지의 주소에서 도메인과 넘겨지는 값 제외. ex) /test/index.php

                                    파일명만 가져올때 : basename($_SERVER['PHP_SELF']);


$_SERVER['APPL_PHYSICAL_PATH'] : 현재페이지의 실제 파일 주소. ex) /home/ksprg/www/

 

$_SERVER['QUERY_STRING'] : GET 방식의 파일명 뒤에 붙어서 넘어오는 파라미터 값. ex) ?user=ksprg&name=hong 



출처: http://roadrunner.tistory.com/158 [삶의 조각들]


Posted by 모과이IT
,

PHP 코드 쪽에서



mysqli_query($conn,"set names utf8;");



위의 코드를 삽입한다.


Posted by 모과이IT
,

Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.

오류 해결방법

 

로그인해서 빨간색 으로 색이 칠해지고

Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.

문구가 나오면

 

뒤로 한번 누르고

 

새로고침 한번 누르고

 

다시 로그인하면 됩니다.

Posted by 모과이IT
,

<?php 
include_once 'class.push.php'
$push = new pushmessage(); 

$params = array("pushtype"=>"android"$idphone=>"android_smart_phone_id_here"$mst=>"Hello, an android user"); 
$rtn $push->sendMessage($params); 
//print_r($rtn); 


=========================================================================================


class.push.php


<?php 
/** 
 * Copyright 2014 Shop-Wiz.Com. 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may 
 * not use this file except in compliance with the License. You may obtain 
 * a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License. 
 */ 

class pushmessage
     
     
     
    public 
$androidAuthKey "Android Auth Key Here"
    public 
$iosApnsCert "./certification/xxxxx.pem"
    
     
/** 
     * For Android GCM 
     * $params["msg"] : Expected Message For GCM 
     */ 
    
private function sendMessageAndroid($registration_id$params) { 
        
$this->androidAuthKey "Android Auth Key Here";//Auth Key Herer 
         
        ## data is different from what your app is programmed 
        
$data = array( 
                
'registration_ids' => array($registration_id), 
                
'data' => array( 
                                
'gcm_msg' => $params["msg"
                            ) 
                ); 
         
         
        
$headers = array( 
        
"Content-Type:application/json"
        
"Authorization:key=".$this->androidAuthKey 
        
); 
         
         
        
$ch curl_init(); 
        
curl_setopt($chCURLOPT_URL"https://android.googleapis.com/gcm/send"); 
        
curl_setopt($chCURLOPT_SSL_VERIFYHOST0); 
        
curl_setopt($chCURLOPT_SSL_VERIFYPEER0); 
        
curl_setopt($chCURLOPT_RETURNTRANSFERtrue); 
        
curl_setopt($chCURLOPT_HTTPHEADER$headers); 
        
curl_setopt($chCURLOPT_POSTtrue); 
        
curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data)); 
        
$result curl_exec($ch); 
        
//result sample {"multicast_id":6375780939476727795,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1390531659626943%6cd617fcf9fd7ecd"}]} 
        //http://developer.android.com/google/gcm/http.html // refer error code 
        
curl_close($ch); 
        
        
$rtn["code"] = "000";//means result OK 
        
$rtn["msg"] = "OK"
        
$rtn["result"] = $result
        return 
$rtn
        
     } 
     
     
    
/** 
     * For IOS APNS 
     * $params["msg"] : Expected Message For APNS 
     */ 
    
private function sendMessageIos($registration_id$params) { 
        
        
$ssl_url 'ssl://gateway.push.apple.com:2195'
        
//$ssl_url = 'ssl://gateway.sandbox.push.apple.com:2195; //For Test 
        
        
$payload = array(); 
        
$payload['aps'] = array('alert' => array("body"=>$params["msg"], "action-loc-key"=>"View"), 'badge' => 0'sound' => 'default'); 
        
## notice : alert, badge, sound 

                 
        ## $payload['extra_info'] is different from what your app is programmed, this extra_info transfer to your IOS App 
        
$payload['extra_info'] = array('apns_msg' => $params["msg"]); 
        
$push json_encode($payload); 
         
        
//Create stream context for Push Sever. 
        
$streamContext stream_context_create(); 
        
stream_context_set_option($streamContext'ssl''local_cert'$this->iosApnsCert); 

        
$apns stream_socket_client($ssl_url$error$errorString60STREAM_CLIENT_CONNECT$streamContext); 
        if (!
$apns) { 

            
$rtn["code"] = "001"
            
$rtn["msg"] = "Failed to connect ".$error." ".$errorString
            return 
$rtn
        } 
         
        
//echo 'error=' . $error; 
        
$t_registration_id str_replace('%20'''$registration_id); 
        
$t_registration_id str_replace(' '''$t_registration_id); 
        
$apnsMessage chr(0) . chr(0) . chr(32) . pack('H*'str_replace(' '''$t_registration_id)) . chr(0) . chr(strlen($push)) . $push
         
        
$writeResult fwrite($apns$apnsMessage); 
        
fclose($apns); 
        
        
$rtn["code"] = "000";//means result OK 
        
$rtn["msg"] = "OK"
        return 
$rtn

    }
//private function sendMessageIos($registration_id, $msg, $link, $type) { 
           
            
        
       /** 
     * Send message to SmartPhone 
     * $params [pushtype, msg, registration_id] 
     */ 
       
public function sendMessage($params){ 
           
        
//$parm = array("msg"=>$params["msg"]); 
        
if($params["registration_id"] && $params["msg"]){ 
               switch(
$params["pushtype"]){ 
                   case 
"ios"
                    
$this->sendMessageIos($params["registration_id"], $params); 
                    break; 
                case 
"android"
                    
$this->sendMessageAndroid($params["registration_id"], $params); 
                    break; 
               } 
        } 

       } 
    
   
    
/* 
     * Sample For database 
     * regist phone Id from Phone to Mysql via controllers 
     * Look a tableSchema at the bottom 
     * @ $params["appType"] : android or ios.. 
     * @ $params["appId"] : //APA91bGEGu5NSyYDYp5OMO4mZ0j1n2DznGARaNFVcCYfLHvHat..... or 6b1653ad818a89fc6937f5067a9b372aec79edeb9504d6ef.... 
     **/ 
    
public function registration($params){ 
        
$pushtype $params["pushtype"]; 
        
$idphone $params["idphone"]; 
        
        
print_r($params); 
        
//{insert into database} 
        
echo json_encode($rtn); 
    } 
     
     
    
/** 
     * Step 2. 
     * Send message to each iphone from web App. 
     * @params : Array() : messages () 
     */ 
    
public function send($params){ 
        
//$sql = "select pushtype, idphone from gcmapns "; 
       // $rows = $CI->db->get_rows($sql); 
       //get data from database and save to $rows 
        
if(is_array($rows)){ 
            foreach(
$rows as $key => $val){ 
                switch(
$val["pushtype"]){ 
                    case 
"ios"
                        
$rtn $this->sendMessageIos($val["idphone"], $params); 
                        break; 
                    case 
"android"
                        
$rtn $this->sendMessageAndroid($val["idphone"], $params); 
                        break; 
                }
//switch($val["pushtype"]){ 
            
}//foreach($rows as $key => $val){ 
        
}//if(is_array($rows)){ 

         
    
}//function send(){ 
            
         
     

                 

Posted by 모과이IT
,



<?php

$con = mysql_connect("localhost", "아이디", "비밀번호");



// 쿼리 전에 utf8로 셋팅

mysql_query("set names utf8",$con);

if (!$con)

{

  die('연결안됨: '.mysql_error());

} else {

  // 해당 DB select

  mysql_select_db("bonbebe",$con);

  

}




$return_array = array();

// sql 쿼리문 작성

$sql = "SELECT * FROM `userinfo` ";

$result = mysql_query($sql);



// json_encode 함수를 쓰면 Web에서 한글이 제데로 표시가 안됨

$outp = "[";

while($rs = mysql_fetch_array($result, MYSQL_ASSOC)) {

    if ($outp != "[") {$outp .= ",";}

    $outp .= '{"id":"'  . $rs["id"] . '",';

    $outp .= '"pw":"'   . $rs["pw"]        . '",';

    $outp .= '"country":"'. $rs["country"]     . '"}'; 

}

$outp .="]";



mysql_close($con);

echo($outp);


?>


Posted by 모과이IT
,

위 오류는 말그대로 헤더를 수정하기전에 먼제 전송된 데이터가 있어서

 

헤더 처리를 못했다는 오류이다.

 

주로 php 에서는 header 함수를 사용할때나 session_start();   함수를 사용할때 주로 이런 오류를 만날수 있는데

 

 

 /*

   <--- 요기 위에 HTML 로 출력되거나 공백줄이라도 있으면 오류 발생

   ▼ 혹은 여기 <? 앞에 공백이 있더라도 오류 발생  */

   <?

     header(~~);

   ?>

 

 



[참고사이트]

http://blog.naver.com/roland82/220053619786


'개발지식창고 > Web_PHP' 카테고리의 다른 글

php push 서버 예제1  (0) 2015.08.11
mysql DB와 php 연동 코드 예제  (0) 2015.07.17
PHP 5.xx 버전 폼에 변수값 전달이 되지 않을때  (0) 2014.08.22
PHP 강좌 링크  (0) 2014.08.21
PHP 문법 정리  (0) 2014.08.21
Posted by 모과이IT
,
[php]php.ini 설정에서 register_globals = on/off 차이점과 기능설명

rester_globals 를 On 으로 하면 변수가 get, post, session 변수인지 체크하지 않아도 됩니다. 
쓰기에 따라서 보안적인 부분에 문제가 생길 수 있습니다
 

register_globals = on
가능 -> $_POST['u_id']
가능 -> $u_id
 
register_globals = off
가능 -> $_POST['u_id']
불가능 -> $u_id  
* extrract()로 처리하면 가능

php.ini에서 register_globals=off 일경우 헤더나 인클루드를 이용해서 상단에
@extract($_GET);
@extract($_POST);
@extract($_SERVER);
@extract($_FILES);
@extract($_ENV);
@extract($_COOKIE);
@extract($_SESSION);
 
위와 같이 처리해 주면 기존 소스를 그대로 사용할 수 있다.
혹은 받아오는 변수의 전체코드를 다 써주면 됨
$HTTP_GET_VARS[변수] 또는 $_GET[변수]
$HTTP_POST_VARS[변수] 또는 $_POST[변수]
$HTTP_COOKIE_VARS[변수] 또는 $_COOKIE[변수]
$HTTP_SESSION_VARS[변수] 또는 $_SESSION[변수]
$HTTP_POST_FILES[변수] 또는 $_POST_FILES[변수]

[참고사이트]
http://www.jnetwork.co.kr/bbs/board.php?bo_table=useguide&wr_id=111


'개발지식창고 > Web_PHP' 카테고리의 다른 글

php push 서버 예제1  (0) 2015.08.11
mysql DB와 php 연동 코드 예제  (0) 2015.07.17
[tip]Cannot modify header information - headers already sent by 오류  (0) 2014.08.25
PHP 강좌 링크  (0) 2014.08.21
PHP 문법 정리  (0) 2014.08.21
Posted by 모과이IT
,