Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, January 5, 2014

php simplexml get a specific item based on the value of a field

Is there a way i can obtain a specific item with SimpleXML ?

For example, i would like to obtain the title of an item having ID set to 12437 with this example xml :

<items>  <item>    <title>blah blah 43534</title>    <id>43534</id>  </item>  <item>    <title>blah blah 12437</title>    <id>12437</id>  </item>  <item>    <title>blah blah 7868</title>    <id>7868</id>  </item></items>

Here are 2 simple ways of doing what you want, one is iterating with each item like this:

<?php$str = <<<XML<items><item><title>blah blah 43534</title><id>43534</id></item><item><title>blah blah 12437</title><id>12437</id></item><item><title>blah blah 7868</title><id>7868</id></item></items>XML;$data = new SimpleXMLElement($str);foreach ($data->item as $item){    if ($item->id == 12437)    {        echo "ID: " . $item->id . "\n";        echo "Title: " . $item->title . "\n";    }}

Live DEMO.

The other would be using an XPath, to pin point the exact data you want like this:

<?php$str = <<<XML<items><item><title>blah blah 43534</title><id>43534</id></item><item><title>blah blah 12437</title><id>12437</id></item><item><title>blah blah 7868</title><id>7868</id></item></items>XML;$data = new SimpleXMLElement($str);// Here we find the element id = 12437 & obtain it's parent$nodes = $data->xpath('//items/item/id[.="12437"]/parent::*');$result = $nodes[0];echo "ID: " . $result->id . "\n";echo "Title: " . $result->title . "\n";

Live DEMO.

Sunday, October 27, 2013

Codeigniter - check if user is logged and exists (it's a real user)

I’m setting a session data for users when they log to my website.

So if the user exists in db i set a session data like : $this->session->set_userdata('user_exists','1');

Now every time i want to check if user exists & is logged i do:

if($this->session->userdata('user_exists')){ //do somenthing for logged user}

Now i’m wondering if this means that user is logged & exists in db since he logged & i setted him a session param, is this true? Or i’ll obtain security problems?

NB: i’m using session database

thanks

//session encryption is mandatory

  $sess_id = $this->session->userdata('user_id');   if(!empty($sess_id))   {        redirect(site_url().'/reports');   }else{        $this->session->set_userdata(array('msg'=>''));         //load the login page        $this->load->view('login/index');           }    

Friday, October 18, 2013

Adding custom rewrite rules to WordPress

My WordPress site has a portfolio that is at www.mysite.com/portfolio/. The portfolio sections & items are administered through a custom plugin I created. I want to access the individual items like www.mysite.com/portfolio/my-cool-photo & have that put “my-cool-photo” into a query string like ?portfolio_item=my-cool-photo so I can read it from my code.

In the plugins activation PHP file I have this code:

function add_rewrite_rules($wp_rewrite) {    $new_rules = array(        'portfolio/(.+)/?$' => 'index.php?&portfolio_item=$1'    );    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;}add_action('generate_rewrite_rules', 'add_rewrite_rules');function query_vars($public_query_vars) {    $public_query_vars[] = "portfolio_item";    return $public_query_vars;}add_filter('query_vars', 'query_vars');

This adds the rewrite rule to the array OK. The problem is it’s not doing anything. When I go to www.mysite.com/portfolio/testing/ I obtain the “This is somewhat embarrassing, isn’t it?” WordPress 404 error page. Obviously the redirect isn’t working, so the query string won’t be filled, yet just to make sure I did this:

global $wp_query, $wp_rewrite;if ($wp_rewrite->using_permalinks()) {    $searchKey = $wp_query->query_vars['portfolio_item'];} else {    $searchKey = $_GET['portfolio_item'];}

…and sure enough the query string isn’t getting passed.

Is there something I’m missing?

After you update the WordPress rewrite rules, you need to flush them:

http://codex.wordpress.org/Function_Reference/flush_rewrite_rules

You can select to flush with the $hard parameter true, & then you should be able to see your rewrite rules in the .htaccess file.

Wednesday, October 16, 2013

HTML table with 100% of height, and the rows equally divided in height. How to make it possible?

please go through this fiddle to see what I have tried so far.

<div class="outer">    <div class="inner">        <table style="background-color: red; width:100%; height:100%;">            <tr style="background-color: red; width:100%; min-height:30%;">                <td>Name</td>            </tr>            <tr style="background-color: blue; width:100%; min-height:30%;">                <td>Nirman</td>            </tr>            <tr style="background-color: blue; width:100%; min-height:30%;">                <td>Nirman</td>            </tr>            </table>    </div></div>

I need to display this table occupying full height of the div, & rows of this table should be equal in height to occupy space of full table.
That means, table’s height should be 100% of div’s height.
and each row’s height should be 30% of div’s height.

Any idea of how to achieve this? Also, I would like a solution that should work on most of the browsers, at least, starting from IE 8.

Any assist on this much appreciated.

In styles of the inner div class, alter min-height:100% to height:100% .
That’s all you need!

(This is because min-height can not be inherited)

Here’s the jsfiddle

Tuesday, October 8, 2013

toString method for SonataAdminBundle Listing in Symfony2

In Symfony 2.3 i am using SonataAdminBundle ( master ) & i am trying to obtain ManyToMany working in Listing. The Problem is that SonataAdminBundle is asking for a toString() method. Implementing this method to the related Entity solves the problem.

My Question: Do i have to implement the toString method or is there a Option to tell SonataAdminBundle a property for using instead of calling the toString method?

Thank you

As far as I know, is mandatory.

But you can return another property value if you want. Also, you can prevent yourself from trying to display a property when the object has no data (for example, when you are “Adding a new object”)

There is a simple way:

public function __toString(){    return ($this->getName()) ? : '';}

Sunday, October 6, 2013

PHP 5.3 accessing array key from object getter

I have a Form object $form. One of its variables is a Field object which represents all fields & is an array (e.g $this->field['fieldname']). The getter is $form->fields().

To access a specific field method (to make it required or not for example) I use $form->fields()['fieldname'] which works on localhost with wamp yet on the server throws this error:

Parse error: syntax error, unexpected '[' in (...)

I have PHP 5.3 on the server & because I reinstalled wamp & forgot to alter it back to 5.3, wamp runs PHP 5.4. So I guess this is the reason for the error.

How can I access an object method, which returns an array, by the array key with PHP 5.3?

Array dereferencing as described in the question is a feature that was only added in PHP 5.4. PHP 5.3 cannot do this.

echo $form->fields()['fieldname']

So this code will work in PHP 5.4 & higher.

In order to make this work in PHP 5.3, you need to do one of the following:

  1. Use a temporary variable:

    $temp = $form->fields()echo $temp['fieldname'];
  2. Output the fields array as an object property rather than from a method:
    ie this….

    echo $form->fields['fieldname']

    …is perfectly valid.

  3. Or, of course, you could upgrade your server to PHP 5.4. Bear in mind that 5.3 will be declared end-of-life relatively soon, now that 5.5 has been released, so you’ll be wanting to upgrade sooner or after anyway; maybe this is your cue to do? (and don’t worry approximately it; the upgrade path from 5.3 to 5.4 is pretty easy; there’s nothing really that will break, except things that were deprecated anyway)

Wednesday, June 26, 2013

Nginx Reverse SSL Proxy with PHP

This trick introduce the way of creating nginx reverse SSL proxy that works with PHP in load balancing environment.

Example network structure

nginx_reverse_proxy

1. Nginx proxy config file for ssl connection
define upsteam in nginx.conf

upstream example.com{        ip_hash;        server 192.168.0.1:8000 max_fails=3 fail_timeout=8;        server 192.168.0.2:8000 max_fails=3 fail_timeout=8;        server 192.168.0.3:8000 max_fails=3 fail_timeout=8;}

define the example.com.conf

server {    listen       443;    server_name  example.com;    index  index.php index.html index.htm;    ssl                  on;    ssl_certificate      /etc/ssl/example.com/example.com.crt;    ssl_certificate_key  /etc/ssl/example.com/example.com.key;    ssl_protocols       SSLv3 TLSv1 TLSv1.1 TLSv1.2;    ssl_ciphers HIGH:!ADH:!MD5:!aNULL:!eNULL:!MEDIUM:!LOW:!EXP:!kEDH;    ssl_session_timeout  10m;    ssl_prefer_server_ciphers   on;    proxy_set_header Cookie $http_cookie;    location / {        proxy_pass http://example.com; #here is the upstreams that defined in upsteam block        proxy_next_upstream     error timeout invalid_header http_500;        proxy_connect_timeout   2;        proxy_set_header        Host $host;        proxy_set_header  X-Real-IP  $remote_addr;        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;        proxy_set_header        X-Forwarded-Proto https;        add_header              Front-End-Https   on;    }}

2. Web server behind the proxy
2.1. Install pecl_http extension with pecl install pecl_http. (This extension allow you to obtain headers from cgi mode, ideally for php-fpm)

2.2. In PHP script, use

if($_SERVER['HTTP_X_FORWARDED_PROTO']=='https' || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')){    //SSL detected}

To check if the request is from https

Friday, June 14, 2013

Get PHP function body as string

This piece of code can return the method body from a class

public static function getFunctionString($class, $function){  $func = new ReflectionMethod($class,$function);   $filename = $func->getFileName();   $start_line = $func->getStartLine();  $end_line = $func->getEndLine()-1;  $length = $end_line - $start_line;  $source = file($filename);  $body = implode("", array_slice($source, $start_line, $length));  return $body;}

When to use:

Extract the function details & execute in other another class when the function contains self::func();

Eg:

class A{   private static $var_a = 1;  public static function a(){     self::func();  }  public static function func(){     echo self::$var_a;  }}

In class B, we need to call function a from Class A

class B{   private static $var_a=2;  public static function b(){     eval(getFunctionString('A', 'a'));  }}B::b();//will output 2

Friday, December 14, 2012

Output array that contains Unicode characters in JSON format

Output array that contains Unicode characters in JSON format (for PHP5.3 or above)

   array_walk_recursive($array_has_unicode_charaters, function(&$item, $Key){	if(is_string($item)){	     $item = urlencode($item);	}   });   $json->data=$array_has_unicode_charaters;   echo urldecode(json_encode($json));

Tuesday, September 25, 2012

Launch RDP from Web Browser

This script allows you create a link that can open a RDP session by passing a server address parameter

eg.

Open RDP

function rdp(address){	try{		var rdpexe = 'C:\\WINDOWS\\system32\\mstsc.exe';		var ws = new ActiveXObject('WScript.Shell');		ws.Exec(rdpexe + " /v:" + address);	}	catch(e){		alert("This link will try to launch RDP session from web browser\n"+			  "1. Please use Internet Explorer 7.0+\n"+ 			  "2. Go to Tools > Internet options > Security > Trusted Sites & click \"sites\" button.\n"+			  "3. Add *.your_domain to trusted site\n"+			  "4. Click Custom Level & find the section \"ActiveX controls & plug-ins\"\n"+			  "5. Select Enable for \"Initializing & Script ActiveX controls not marked as safe\"");	}}

Friday, May 18, 2012

How to create distributed/mirrored dynamic scripting website (Step - 4 Region detection and redirection)

Step four: Region detection & redirection
First of all, download the latest database

wget software77.net/geo-ip/?DL=1 -O /path/IpToCountry.csv.gz

Create a table in your website database & import the data from the csv file

CREATE TABLE IF NOT EXISTS `ip2country` (  `start` int(10) unsigned NOT NULL DEFAULT '0',  `end` int(10) unsigned NOT NULL DEFAULT '0',  `registry` varchar(50) NOT NULL,  `assigned` varchar(50) NOT NULL,  `a2` char(2) NOT NULL DEFAULT '',  `a3` char(3) NOT NULL DEFAULT '',  `country` varchar(100) NOT NULL DEFAULT '',  PRIMARY KEY (`start`,`end`),  KEY `a2` (`a2`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;LOAD DATA LOCAL INFILE 'YOUR_PATH/IpToCountry.csv' INTO TABLE ip2country FIELDS TERMINATED BY ',' ENCLOSED BY '"'  LINES TERMINATED BY '\n';

Now just need add a few line of php code at the beginning of index.php file to handle the redirect.

//If the visitor is search engine spider, then do not redirect.function check_if_spider(){	$spiders = array('Googlebot', 'Yammybot', 'Openbot', 'Yahoo', 'Slurp', 'msnbot', 'ia_archiver', 'Lycos', 'Scooter', 'AltaVista', 'Teoma', 'Gigabot', 'Googlebot-Mobile');	foreach ($spiders as $spider)	{		if (eregi($spider, $_SERVER['HTTP_USER_AGENT']))		{			return TRUE;		}	}	return FALSE;}function checkip(){                if(check_if_spider()) return;		$client_ip=ip2long($_SERVER['REMOTE_ADDR']);		$rs = $db->query("select `a2` from `ip2c` where `start` <= $client_ip & `end` >= $client_ip");		$row = $db->fetch_array($rs);		//$row[0] will be the country code.                switch($row[0]){                    case 'US':                        //..301 Redirection                        header("HTTP/1.0 301 Moved Permanently");			header("Location: http://us.example.com".$_SERVER['REQUEST_URI']);                     break;                    default:                       //... 301 Redirection                    break;                }	}}checkip();

Thursday, August 11, 2011

Tuesday, August 2, 2011

Execute PHP script in background mode in Windows

Create a .vbs file

Dim objshellSET objshell = WScript.CreateObject ("WScript.Shell")objshell.run "c:\php5\php.exe YourPHP.php", 0SET objshell=Nothing

And execute this vbs file in windows schedule task manager

Wednesday, November 3, 2010

Integrate open source secureimage library with CodeIgniter

Heres how:
1.) Download the open source securimage library from:
http://www.phpcaptcha.org/.

2.) Copy the library in your codeigniter’s application/library folder.

3.) Create a function in your codeigniter’s controller’s class (example index)

 function securimage() {$this->load->library('securimage');$img = new Securimage();$img->show(); // alternate use:  $img->show('/path/to/background.jpg');}

4.) In the view where you will place the captcha, insert this line:

<img src="<?=site_url('index/securimage')?>" alt='captcha' />

site_url() – gives the base url with index.php in the end
index – controller
securimage – is the function

Wednesday, October 27, 2010

Nginx rewrite rule for Kohana

This took me a while to investigate how to set the rewrite rule for Kohana in nginx, then I found it is really easy

location / {    root   c:/web;    index  index.php index.html index.htm;    if (-f $request_filename){        break;    }    if (-d $request_filename){        break;    }    rewrite ^/ANY_PATH/(.+)$ /ANY_PATH/index.php?kohana_uri=$1 last;}

Thursday, October 14, 2010

PHP shell - interactive mode

$ php -aInteractive shellphp > echo time();1287046854

Tested ok with Linux, yet Windows seems has some problem with it

Tuesday, October 5, 2010

Use DOMDocument to parse non utf-8 encoding web page in PHP

Recently I was digging around in PHP + curl + DOMDocument, there are quite lot of impressive facilities such as DOMxPath, curl post, cookies, it is very effortless to simulate any action on an website without JavaScript depend. Here is some problem & tricks I found when I handle any non utf-8 encoding with CURL & DOMDocument.

Case 1:
Parsing a non utf-8 encoding page to DomDocument, Some web page put tag in following sequence

<html><head><title>NON UTF-8 TITLE</title><meta http-equiv="Content-Type" content="text/html; charset=ENCODING"/>

Assuming you have just received the html content from curl_exec

//....$htmlContent = curl_exec($ch);$doc=new DocDocument('1.0', 'ENCODING'); //create a new DOMDocument object$doc->loadHtml($htmlContent); //you probably obtain warning here$doc->save('test.html');

Open your test.html with any text editor, you may find the your html body is gone & the header is incomplete.

To resolve this problem, you will have to put the title after the

Here is a simple trick to do

$htmlContent = curl_exec($ch);$pattern="/(<title>.*<\/title>)[.\s]*(<meta\s*http-equiv=\"Content-Type\"\s*content=\"text\/html; charset=gb2312\"\s*\/>)/i";$htmlContent=preg_replace($pattern,"$2\r\n$1",$htmlContent);$doc=new DocDocument('1.0', 'ENCODING');$doc->loadHtml($htmlContent);

Now you should obtain the proper document content without lose anything.

Thursday, September 16, 2010

Run multiple SQL query in PHP when using SQL variables

Some times you may need to run mulitple query in PHP to obtain the query result you want. eg

SELECT `column` INTO @column FROM table LIMIT 1;SET @query = CONCAT("SELECT DISTINCT table2.",@column,"  FROM table2");PREPARE stmt FROM @query;EXECUTE stmt;

Here is an example function

function doMultiQuery{if(mysqli_multi_query($con, $query)){  do {     if ($result = mysqli_store_result($con)) {           if(mysqli_num_rows($result)>0)           {                 return $result;           }           @mysqli_free_result($con);     }   } while (@mysqli_next_result($con));}}