Archive for March 2013

Function for getting all parents of a child category in php

Function for getting all parents of a child category in php

function getRootParent($id,$cats=array())
    {
        $this->db->select('cat_id,cat_parent_id');
        $this->db->where('cat_id', $id);
        $result = $this->db->get('category');
            foreach($result->result_array() as $ids){
                if($ids['cat_parent_id']==0){
                $cats[] = $ids['cat_id'];
                    return $cats;
                }else{
                $cats[] = $ids['cat_id'];
                    $cats = $this->getRootParent($ids['cat_parent_id'],$cats);
                }
            }
      
        return $cats;
    }

Control Structures in PHP: ELSEIF

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:
  

<?php

if ($a > $b) {

echo "a is bigger than b";

} elseif ($a == $b) {

echo "a is equal to b";

} else {

echo "a is smaller than b";

}

?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Facebook like exchange script




I will send you on mail all PHP Facebook like exchange script to create WebSite about Facebook likes exchange, Twitter followers exchange, Youtube views exchange,.. You need webhost with php and mysql, and mail servis available. 

With Facebook like exchange site you can earn money when someone buy credits for exchange.

Example of site you can see on DEMO

You can also find this offer on >> Fiverr<<

HOW TO INSTALL?
1. upload all files to your domain.

2. setup a new mysql database however you want.

3. import file db.sql into your database using phpmyadmin.

4. open config.php and type in the new database settings that you setup.

5. open your browser and load up your domain

6. login to your site as  admin/password 

7. Change your admin information and continue to adjust site as you want..

If you need any additional help or assistance , contact us!

Javascript in PHP on Windows with php_spidermonkey

I recently had a problem to solve: run some Javascript from inside PHP on a web server.

I needed to evaluate a web browser's PAC (proxy auto config) file exactly the way a browser would, by executing the Javascript function FindProxyForURL() (see here for a good guide). The browser uses its Javascript engine, so to simulate it, I wanted to run Javascript inside PHP (an example is here in another post). 

On the web there were some solutions for Javascript engines, written in PHP, such as:

The problem is that these solutions, however impressive, are not the real thing. There will be nagging worries about reliability and speed.

So then I looked at Mozilla and wondered if their Spidermonkey engine could be used. I didn't have to look much further to see that there was already a fantastic PHP PECL package written by Christophe Robin that wraps the Mozilla Spidermonkey engine. Theoretically a perfect solution, giving speed, efficiency and reliablity - the only hurdle was to get it built on Windows - it wasn't a piece of cake, but worth the effort, and nothing compared to the effort of the programmers who wrote the code.

I am posting the binaries here so that others can get up and running instantly. The instructions on how to build these follow:
Steps to build - you don't need to build anything, the dll's for Windows are above - these are to help me remember what to do next time around, and maybe will be useful to someone:
  1. For builds to do with PHP, I use this VC9 SDK from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=3138
  2. Get and build Spidermonkey 1.8.5 from here: https://developer.mozilla.org/En/SpiderMonkey/Build_Documentation.
    1. Get the source code - near the top of the page is a link to it, or you can get it from here: http://ftp.mozilla.org/pub/mozilla.org/js/.
    2. Get the build tools for Windows - near the top of the page is a list of platforms - click on Windows, then about half way down the page is a link to the Mozilla build tools entitled "Download the current MozillaBuild package".
    3. Once the build tools are installed, run "start-msvc9.bat", as documented on the Windows page. It opens a Mozilla command window (a unix bash simulation).
    4. Go back to the Build Documentation and follow the instructions for "Easy Build".
    I had no problems building, everything worked perfectly and I ended up with a static JS library, a DLL and js.exe. I chose to use the static library to build php_spidermonkey so that it could be installed as a stand-alone extension in PHP, with no other dependencies.
  3. Building php_spidermonkey is a bit more tricky. Get the original source code here: http://pecl.php.net/package/spidermonkey/1.0.0. It does not build on Windows VC9 at all without adjustment, but the code is sound - it's just minor technicalities and looks worse than it is.You need a working PHP build environment to build the extension. This won't make any sense unless you know how to build PHP extensions - these instructions work with my modified source code...:

    1. Create a spidermonkey folder in php extensions, and copy this (modified) source code into it: php_spidermonkey source (submitted to https://github.com/christopherobin/php-spidermonkey)
    2. Get the recently built javascript static library "js_static.lib" located in "js\src\dist\lib", copy it to PHP build environment folder "php54dev\vc9\x86\deps\include\lib", and rename it "js32.lib"
    3. Create sub-folder "php54dev\vc9\x86\deps\include\js", and copy all of the .h files from the spidermonkey api folder "js\src" into it.
    4. Add "--with-spidermonkey=shared" to your PHP configure command.
    5. Build PHP.

PHP SOAP Extension

PHP SOAP Extension is one of the most popular PHP implementations of SOAP 1.1 and 1.2, developed by The PHP Group. SOAP is a lightweight protocol for exchange of information in a decentralized, distributed environment. , So SOAP is the most popular web services format. It's a SIMPLE way to allow programs written in different languages running on different computers to communicate and share data. SOAP is a W3C standard for passing messages across the network and calling functions on remote computers.

SOAP, formerly known as Simple Object Access Protocol (until the acronym was dropped in version 1.2), came around shortly after XML-RPC was released. It was created by a group of developers with backing from Microsoft. Interestingly, the creator of XML-RPC, David Winer, was also one of the primary contributors to SOAP. Winer released XML-RPC before SOAP, when it became apparent to him that though SOAP was still a way away from being completed, there was an immediate need for some sort of web service protocol.

PHP 5's SOAP extension is the first attempt to implement the SOAP protocol for PHP in C. SOAP is included in the PHP 5.0.4 package for Windows distributed by Zend Technologies. It has some advantages over the existing implementations written in PHP itself, the main one being speed. The extension is currently marked as experimental, but should gradually become more stable and reliable as time progresses.

SOAP is an XML based protocol that consists of four parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules for expressing instances of application-defined data types, a convention for representing remote procedure calls and responses and a binding convention for exchanging messages using an underlying protocol. SOAP can potentially be used in combination with a variety of other protocols; however, the only bindings defined in this document describe how to use SOAP in combination with HTTP and the experimental HTTP Extension Framework. XML SOAP uses XML for transmitting data.

To show you an example of how PHP SOAP Extension can be used in a SOAP client application, here is my first SOAP PHP program, soapClient.php

Example : soapClient.php



<?php
$client = new SoapClient("http://[insert real path here]/productOrder.wsdl");

print_r($client->serverFunction('UserName', password', $Integer1, $string1));
?>


This client function will communicate with productOrder.wsdl file on the server. WSDL (Web Services Definition Language) is an XML based standard designed to describes protocol bindings and message formats of Web services. WSDL is often pronounced as "Whiz-Dull.

Being XML-based, this allows clients to automatically discover everything about the functionality of the web service. Human-readable documentation is technically not required for a SOAP service that uses a WSDL document, though it is still highly recommended. Let's take a look at the structure of a WSDL document and how we can use it to figure out what is available to us in a SOAP-based web service. Out of all three specifications that we're going to look at in relationship to SOAP, WSDL is the most ethereal. Both supporters and detractors often call writing WSDL documents a black art.

The only argument against using it is that the client has to load the relevant WSDL document from the server before the RPC can be made, and this can take a significant amount of time in a Web environment. In order to speed things up, PHP's ext/soap uses a WSDL caching feature that can be controlled through setting the soap.wsdl_cache_enabled, soap.wsdl_cache_dir and soap.wsdl_cache_ttl configuration directives, either in your php.ini or by using ini_set()(see SOAP Server Example ). By default, WSDL caching is turned on and caches WSDL files for one day.





Beginning with a root definitions element, WSDL documents follow this basic structure:


<definitions>
<types>

</types>
<message>

</message>
<portType>

</portType>
<binding>

</binding>
</definitions>

As you can see, in addition to the definitions element, there are four main sections to a WSDL document: types, message, portType, and binding.

Here is a copy of the WSDL document for the demonstration Web service used in in the SOAP Server.
Example : productOrder.wsdl



<?xml version ='1.0' encoding ='UTF-8' ?>
<definitions name=SOAPDefn
xmlns:soap='http://schemas.xmlsoap.org/wsdl/soap/'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:soapenc='http://schemas.xmlsoap.org/soap/encoding/'
xmlns:wsdl='http://schemas.xmlsoap.org/wsdl/'
xmlns='http://schemas.xmlsoap.org/wsdl/'>

<message name='getOrderRequest'>
<part name='userID' type='xsd:string'/> //passing variable 1
<part name='paswrd' type='xsd:string'/> //passing variable 2
<part name='orderNo' type='xsd:integer'/> //passing variable 3
<part name='itemName' type='xsd:string'/> //passing variable 4

</message>
<message name='getOrderResponse'>
<part name='Result' type='xsd:integer'/>
</message>

<portType name='orderPortType'>
<operation name='saveOrderDetails'>
<input message='tns:getOrderRequest'/>
<output message='tns:getOrderResponse'/>
</operation>
</portType>

<binding name='orderBinding' type='tns:orderPortType'>
<soap:binding style='rpc'
transport='http://schemas.xmlsoap.org/soap/http'/>
<operation name='saveOrderDetails'>
<soap:operation soapAction='urn:xmethods-delayed-quotes#saveOrderDetails'/>
<input>
<soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'
encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
</input>
<output>
<soap:body use='encoded' namespace='urn:xmethods-delayed-quotes'
encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'/>
</output>
</operation>
</binding>

<service name='orderService'>
<port name='StockQuotePort' binding='tns:orderBinding'>
<soap:address location= ‘http://[insert real path here]/ server.php'/>
</port>
</service>
</definitions>

Note: The WSDL caching feature is on by default. During the development of your WSDL file it should be turned off.



Now it's time to create our server.

Example : server.php


<?php
require_once "SOAPFunctionsManager.obj";
ini_set("soap.wsdl_cache_enabled", "0"); //disabling WSDL cache
$server = new SoapServer("productOrder.wsdl");
$server->setClass("SOAPFunctionsManager");
$server->handle();
?>


$server->setClass method connect the SoapServer object with the SOAPFunctionsManager class, and used all methods in the SOAPFunctionsManager class with the SOAP Server .

Example: SOAPFunctionsManager

class SOAPFunctionsManager
{
function saveOrderDetails($userName, $paswrd, $orderNo, $itemname) {
if($this->authenticateUser($userName, $paswrd)) {
$order_Index = $this->saveOrder($orderNo, $itemname);
return $order_Index;
} else {
return 0;
}
}

function saveOrder($orderNo, $itemname)
{
execute MY SQL Query here..
return last Insert_ID()

}

function authenticateUser($userName, $paswrd) {
if($userName == '_USER_NAME_' && $paswrd == '_PASSWORD_)
return 1;
else
return 0;
}

}

Conclusion

In this article, we were introduced to SOAP, the most complex of the web service protocols so far. SOAP relies heavily on other standards like WSDL and XSD. Well XML-RPC is a great way to transmit simple data as shown in the above sample. However, SOAP allows Objects to be used. These days most people are working in object oriented languages and know the power of using Objects. SOAP allows you to harness that power in your web applications.

The SOAP extension is fully documented at http://www.php.net/manual/en/ref.soap.php.
If you read the SOAP Extension reference page, you will see that SOAP Extension support SOAP client applications with a class called SoapClient, which offers the following functions:

• SoapClient->__construct() - constructs a new SoapClient object
• SoapClient->__soapCall() - Calls a SOAP function
• SoapClient->__getFunctions() - Returns list of SOAP functions
• SoapClient->__getLastRequestHeaders() - Returns last SOAP request headers
• SoapClient->__getLastRequest() - Returns last SOAP request
• SoapClient->__getLastResponseHeaders() - Returns last SOAP response headers
• SoapClient->__getLastResponse() - Returns last SOAP response
• ...

The extension is still in the early development phase, so your feedback will help to make it more stable, reliable, usable and fast. Please report any problems you find at http://bugs.php.net/.

References
http://devzone.zend.com/node/view/id/689

260 PHP script

Link Listing Script links.zip
Links Exchange Website conservatory.zip
Live Help Script livehelp.zip
MySQL Database Backup Perl Script backupscript.zip
News Publishing Script topstory.zip
Office Intranet Suite intranet.zip
Online Classifieds Script classifieds.zip
Online MultiPlayer Chess webchess.zip
osCommerce PHP Shopping Cart oscommerce.zip
PassGen passgen.zip
PaymentPal paymentpal.zip
Perpetual Traffic Generator trafficgenerator.zip
PHP & MySQL Content Management System contentm.zip
PHP Form To Email Script SECURE! emailer.zip
PHP Message Boards Script messageboard.zip
PHP-based eCard Script/Website gcards.zip
POP-UP Creator popup.zip
Powerful Portal with Content Management phpx.zip
Secure Authentication Script authentication.zip
Simple Yet Powerful Download Counter Script hitcounter.zip
Sophisticated PHP Ecommerce Site xtcommerce.zip
Sports League, Fixture and Prediction Management Script phpfootball.zip
Toplist Website Manager #1 toplist.zip
Toplist Website Manager #2 topsites.zip
USENET News Client newsgroup.zip
Visitor Logging Script tollbooth.zip
Web Event Calendar calendar.zip
Web Portal System geeklog.zip
Web-Based Address Book Script wa-boo.zip
Web-based Image Management System photoseek.zip
Web-based POP Email Client webmail.zip
Website Stats Business trafficgopher.zip
Whois Lookup whois.zip
Yahoo Style Link Directory/Search Engine sslinks.zip

Submit-A-Link Style Script linksubmit.zip
Suggest My Site Script suggest.zip
Users Online Script #1 usersonline.zip
Users Online Script #2 cjusersonline.zip
Advanced Guestbook Script guestbook.zip
Affiliate Banner Rotation Script adrotator.zip
Affiliate Linkmaster affiliatemask.zip
Affiliate Program (Advanced Version) postaffiliate.zip
Affiliate Program (Basic Version) phpaffiliate.zip
Another PHP Web FTP Program webftp.zip
Auction Website phpauction.zip
Auto Hits Script scau.zip
Automated Form Submission Prevention human.zip
Bookmarks/Favorites Script bookmarks.zip
Build a Webring webring.zip
ClickBank "Thank You" Page Protector Script cbscript.zip
Client Invoicing Script myinvoice.zip
Document Management System sdms.zip
Easy Administration Program easyadmin.zip
EasyStream easystream.zip
Electronic Reminder Script ereminder.zip
Expired Domain Finder wgs-expire.zip
FAQ Generator whatdafaq.zip
FAQ Manager faqmanager.zip
FFA Links Page Script ffalinks.zip
File Transfer Script net2ftp.zip
Hot Mailing List Script newsletter.zip
ICQ Pager Script pager.zip
Image to ASCII Generator img2ascii.zip
Image Watermarking Script watermark.zip
Instant Photo Gallery Script instantgallery.zip
Instant Site Maker instantsm.zip
.........................................................

Download Link:

http://rapidshare.com/files/112471002/20_Scripts.rar

search data in table with user inputs in php with mysql

connection.inc.php :

<?php
$host='localhost';
$user_name='root';
$password='';
@$con = mysql_connect("$host","$user_name","$password");
if ($con)
 {}
else
  {
  die('Could not connect ');
  }
?>
=======================================================================

select_form.php :


<center><form action="select_table.php" method="POST">
<table border=0><tr><td>database name</td><td><input type="text" name="db_name" value="test"></td>
<td>table name</td><td><input type="text" name="table_name" value="test"></td></tr>
<tr><td>column1 name</td><td><input type="text" name="col1" value="sno"></td>
<td>column2 name</td><td><input type="text" name="col2" value="name"></td></tr>
<tr><td colspan=4 align="center"><input type="submit" value="submit"> </td></tr></table>
</form>

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

select_table.php :


<?php

require 'connection.inc.php';

if (@mysql_select_db($_POST['db_name']))
{
     if(isset($_POST['db_name'])&& isset($_POST['table_name'])&& isset($_POST['col1'])&& isset($_POST['col2']))
        {
         if(!empty($_POST['db_name'])&& !empty($_POST['table_name'])&& !empty($_POST['col1'])&& !empty($_POST['col2']))
             {
               $db=$_POST['db_name'];
               $tn=$_POST['table_name'];
               $snum=$_POST['col1'];
               $name=$_POST['col2'];
               $result=mysql_query("select * from $tn ",$con);

                          if(mysql_query("select * from $tn ",$con))
                          {
                              if(@mysql_num_rows($result))
                                {
                               echo ("<br><center><table><tr><th><b>$snum</td><th><b>$name</td></tr>");
                               if(mysql_query("select $snum from $tn") && mysql_query("select $name from $tn"))
                               {
                               while($data = mysql_fetch_array($result))
                                     {
                                      echo "<tr><td>".@$data[$snum] . "</td><td>" .@$data[$name]."</td></tr>";
                                     }
                                    }else {
                                            echo '<b>please verify column name(s)</b>';
                                          }

                         }   else echo '<center><b>empty table';
                  }  else echo ('<center><br><br><b>no table with that name<br><br>');
              }
           else echo '<center>please varify is all data entered ?';
  } else echo '<center>one of the input ont set';
}else echo '<center><br>wrong database selected<br>';

mysql_close($con);
?>
=======================================================================

run " select_form.php "

output :

fill every text box and click on submit button

The best PHP Real estate Portal Software


The best PHP Real estate Portal Software

Our Real Estate Portal Script is a complete software solution that will save your money, time and effort. And most importantly, it will boost your online real estate business and guarantee its success! The Real Estate PHP Script is a fully scalable turn-key PHP MySQL Real Estate. 

Key Applications of the Real Estate Portal Script: 
·                      Script is designed by keeping an eye on the basic search requirements of visitors, Agents & Brokers Entry & their Details, Fully controllable by Admin.
·                            All the sites templates are easily editable to suit your requirements. 
·                            3rd Party script integrations possible. 
·                            Impressive Layout to attract your customers and visitors. 
·                            Payment Gateway options.

For more details contact us on ready2goportals@gmail.comVisit us at www.ready2goportals.com.

if-else-if statement or if else if statement in php

<?php

$sno=101;
$name='hari kishore';
$marks=300;

if($sno==101)
  {
     if($name=='hari kishore')
        {
           if($marks>=300)
               {
                  echo 'you are second class';

                }
             else
                {
                    echo 'you are not second class';
                 }
         }
       else 
         {
               echo 'you are not hari kishore';
          }
    }

?>

output : you are second class

postgres - from clause in update sql

update students set college_name = c.name from colleges c
where students.city = c.city

weired SQL but awesome isn't??!!

> In update we cannot use aliases for the update table so have to use the full name in case of ambiguous columns e.g. city

> we can have any number of from tables with aliases and have a join on the update table and also can update a value using a value from the join table

PHP Training Institute - Yorex Infotech


Yorex Infotech
Professional Training and Development
ISO 9001:2008 Company
A Registered Company

Training in PHP

Training in Wordpress 

Training in Drupal

Training in .net

Training in Android

Training in Cakephp

Training in Java


100% Satisfaction Guaranteed. 

100% Quality Education.

100% yours Money Value.

Contact
98-76-76-76-68
82-83-83-83-73


Contador de usuarios activos con PHP

Con este script podemos contar los usuarios activos con PHP.

No vamos a usar ninguna base de datos. En su lugar usaremos un archivo llamado usuarios.dat

Creamos nuestro script PHP y lo llamamos activos.php

<?php

$tiempo_logout = 600; // segundos tras los cuales un usuario es marcado como inactivo

$arr = file("usuarios.dat");

$contenido = $REMOTE_ADDR.":".time()." ";

for ( $i = 0 ; $i < sizeof($arr) ; $i++ )

{

$tmp = explode(":",$arr[$i]);

if (( $tmp[0] != $REMOTE_ADDR ) && (( time() - $tmp[1] ) < $tiempo_logout ))

{

$contenido .= $REMOTE_ADDR.":".time()." ";

}

}

$fp = fopen("usuarios.dat","w");

fputs($fp,$contenido);

fclose($fp);

$array = file("usuarios.dat");

$USUARIOS_ACTIVOS = count($array);

?>

La explicación de lo que hace el codigo anterior es la siguiente:

  • Cargamos usuarios.dat a un array
  • Creamos el archivo de texto con las IP y la hora de visita de los que visitan nuestra web
  • “Borramos” de ese archivo los que llevan más de $tiempo_logout sin actividad
  • Escribimos el archivo
  • Declaramos una variable $USUARIOS_ACTIVOS que contiene el número de usuarios activos del momento

Para utilizar este Script, al principio de cualquier página ponemos

<?php

include(”activos.php”)

?>

y donde queremos mostrar el número de usuarios, usamos la variable $USUARIOS_ACTIVOS.

Best practice (optimization)

1. References
Use of references are slower than making copies of original data and than manipulate it. So use references only when you have large data structs to save memory. The use of references depends on your system, if your system is CPU bound avoid using the references and if your system is memory bound use references.

2. Persistent Database connections
Generally databases are slower to establish connections so it is better to use persistent db connection. But persistent connections will consume and tie up resources even when not in use so watch your resource limits before making tradeoff.

3. Avoid using regex
Php have good sets of string manipulation functions:

    <?php ereg_replace("-","_",$str); ?>Bad
    <?php str_replace("-", "_", $str);?>Good


4. mysql_unbuffered_query()
The function mysql_unbuffered_query() is same as mysql_query() except that instead of waiting for the entire query to execute and storing the result in the client API, it makes results available to you as soon as possible and they are not allocated in the client API. So you get access to data quicker and uses less memory. You can't use mysql_num_rows() on the result resource and it is likely to be slightly slower for small selects.


The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases.
PHP is basically used for developing web based software applications. 
This tutorial helps you to build your base with PHP. 
You can practice PHP online using compileonline.com
Audience:
This tutorial is designed for PHP programmers who are completely unaware of PHP concepts but they have basic understanding on computer programming.
Prerequisites:
Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful.