Category Archives: PHP

PHP Curl and C# HttpWebRequest

Sample HTTP POST


POST /web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID HTTP/1.1
Host: www.sagepayments.net
Content-Type: application/x-www-form-urlencoded
Content-Length: length

M_ID=string&M_KEY=string&T_REFERENCE=string

Using C# HttpWebRequest

Dictionary post_values = new Dictionary();
post_values.Add("M_ID", "TestUsrID");
post_values.Add("M_KEY", "TestKey");
post_values.Add("T_REFERENCE", "TestRef");

String post_string = "";

foreach (KeyValuePair post_value in post_values)
{
   post_string += post_value.Key + "=" + HttpUtility.UrlEncode(post_value.Value) + "&";
}
post_string = post_string.TrimEnd('&');
string VOID_URL = "https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(VOID_URL);
objRequest.Method = "POST";
objRequest.ContentLength = post_string.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";

// post data is sent as a stream
StreamWriter myWriter = null;
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(post_string);
myWriter.Close();

// returned values are returned as a stream, then read into a string
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
   post_response = responseStream.ReadToEnd();
   responseStream.Close();
}

Console.WriteLine("Response"+post_response);

Using PHP Curl

$param = array("M_ID" => "TestUsrID", "M_KEY" => "TestKey", "T_REFERENCE" => "TestRef");

$url = "https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_VOID";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if (curl_errno($ch)) {
   echo "Error : ".curl_error($ch));
}
curl_close($ch);

echo "Response : ".$response;

C# HttpWebRequest Class Reference : http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
PHP CURL Reference : http://us2.php.net/manual/en/book.curl.php

Posted in ASP.NET, PHP, Tech Note | Tagged , | 2 Comments

Get Browser Information using PHP

function getBrowser(){
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?' . join('|', $known) .
    ')[/ ]+(?[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){             $version= $matches['version'][0];         }         else {             $version= $matches['version'][1];         }     }     else {         $version= $matches['version'][0];     }     // check if we have a number     if ($version==null || $version=="") {$version="?";}     return array(         'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

Source from : http://php.net/manual/en/function.get-browser.php

Posted in PHP, Tech Note | Tagged , , , , | Leave a comment

302 Error while running Curl

If you get 302 error while running Curl, try to use CURLOPT_FOLLOWLOCATION.

Ex)

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);


Also, you can use curl_getinfo() to get more information regarding your curl transfer.

Ex)

echo curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

http://us.php.net/manual/en/function.curl-getinfo.php

Posted in PHP, Tech Note | Tagged , , , | Leave a comment

Use print_r in Smarty template

{$myArray|print_r}

:)

Posted in PHP, Tech Note | Tagged , | Leave a comment

Serialize with Jquery and Unserialize with PHP

//JS (Jquery)

var serializedData = $('#myForm').serialize();

$.post(
	'getSerializedData.php',
	{data:serializedData},
	function(data){
	}
)

// PHP

$serializedData = $_POST['data'];
$unserializedData = array();

parse_str($serializedData,$unserializedData);

print_r($unserializedData);
Posted in JavaScript, PHP, Tech Note | Tagged , , , | 6 Comments

Access parent’s parent variable and Access interface constant variable


// Access parent's parent variable
class Parent1 {
	const PARENT_NAME = "Mark Song";
	const PARENT_AGE = "31";
	const PARENT_EMAIL = "ilovekanon@gmail.com";
	protected $_normal_val = "HeHeHeHe";
}

class Parent2 extends Parent1 {
	public function __construct(){}
}

class Child extends Parent2 {
	public function __construct(){}
	
	public function getParentName(){
		return parent::PARENT_NAME;
	}

	public function getNormalVal(){
		return $this->_normal_val;
	}
}

$c = new Child();
echo $c->getParentName();
echo "br";
echo $c->getNormalVal();

/*
Output : 
	Mark Song
	HeHeHeHe
*/

// Access interface constant variable

interface Parent3 {
	const PARENT_NAME = "Mark Song";
	const PARENT_AGE = "31";
	const PARENT_EMAIL = "ilovekanon@gmail.com";
	//protected $_normal_val = "HeHeHeHe"; Error : Interfaces may not include member variables
}

class Parent4 implements Parent3 {
	public function __construct(){}

	public function getParentName(){
		//return parent::PARENT_NAME;  Error : current class scope has no parent 
		return self::PARENT_NAME;
	}
}

class Child2 extends Parent4 {
	public function __construct(){}

	public function getParentName(){
		return parent::PARENT_NAME;

	}
	public function getParentAge(){
		return parent::PARENT_AGE;
	}
}

$d = new Parent4();
echo $d -> getParentName();
echo "br";
$e = new Child2();
echo $e->getParentName();
echo "br";
echo $e->getParentAge();

/* 
Output : 
	Mark Song
	Mark Song
	31
*/

Posted in PHP, Tech Note | Tagged , , , , , | Leave a comment

[HEREDOC] PHP assign multiline string to variable

$var1 = <<<EOD
<table>
<tr>
<th> name </th>
<td> {$name} </td>
</tr>
</table>
EOD;
$var2 = <<<BLOCK
<script type=’text/javascript’>
function myFunction(){
alert(‘This defined by PHP_HEREDOC’);
}
</script>
BLOCK;
* Note : Before close tag (ex, EOD; and BLOCK;), if there is a space, then it wouldn’t work. Be sure there is no tab and no space!
Posted in PHP, Tech Note | Tagged | Leave a comment

How to use PHP temporary file ?

$temp = tmpfile();
fwrite($temp,'Line #1'.chr(13).chr(10));
fwrite($temp,'Line #2'.chr(13).chr(10));
fwrite($temp,'Line #3'.chr(13).chr(10));
fseek($temp,0); //move file pointer

// char(13) = \r
// char(10) = \n

while($row = fgets($temp,1024)){
	echo $row ."
";
}

fclose($temp); // remove temporary file


Output ::
Line #1
Line #2
Line #3

Posted in PHP, Tech Note | Tagged , , | 3 Comments

How to use array_map() with class method?

array_map(array(‘CLASS_NAME’,’METHOD_NAME’,array(‘USA’,’KOREA’,’JAPAN’);

Example ::


class MyClass {
	public function __construct(){}
	
	protected function convertToObject($array){
		return (object) $array;
	}

	public function convertMyArray($array){
		$obj = array_map(array('MyClass','convertToObject'),$array);
		return $obj;
	}
}

$array = array(
	array('Country' => 'US'),
	array('Country' => 'KOREA'),
	array('Country' => 'JAPAN'),
	array('Country' => 'INDIA'),
	array('Country' => 'CANADA')
);

$cls = new MyClass();
$obj = $cls->convertMyArray($array);
echo $obj[0]->Country; // OUTPUT : US

Posted in PHP, Tech Note | Tagged , , | 2 Comments

How to create stdClass (Object)

function myFunction($stdObj){
	echo $stdObj->name."
"; } $a= new stdClass; $a->name = "Mark Song"; $a->email = "ilovekanon@gmail.com"; $a->web = "uniapple.net"; myFunction($a); // output : Mark Song /******** Other Way ********/ $b = array( "name" => "Mark song", "email" => "ilovekanon@gmail.com", "web" => "uniapple.net"); $b = (object) $b; myFunction($b); // output : Mark Song
Posted in PHP, Tech Note | Tagged , | 4 Comments