working on it ...

Filters

Explore Public Snippets

Sort by

Found 63k snippets

    public by DinhoPutz modified Feb 5, 2019  239  2  4  0

    Calculadora de Reflorestamento em PHP

    Calcula a quanto de área a ser replantada/paga
    <html>
        <head>
            <title>Calculadora Reflorestamento</title>
    		<META charset="UTF-8" lang="pt-br">
    		<style>
    			body { font-family: Arial; }
    			table { border: none; font-weight: bold; }
    			tr, td { border: black 1px solid; }
    		</style>
    	</head>
        <body>
            <div class="Calc">
                <form method="POST">
                    <fieldset>
                        <table>
                            <legend>Calculadora de Reflorestamento</legend>
                            <tr>
                                <td>Ano</td><td>Estado</td><td>Árvores cortadas</td><td>Volume (m³)</td>
    						</tr>
                            <tr>
                                <td><input name="ano" type="text" maxlength="4" size="8"></td>
                                <td>
    								<select name="estado">
    									<option value="AC">Acre</option>
    									<option value="AL">Alagoas</option>
    									<option value="AP">Amapá</option>
    									<option value="AM">Amazonas</option>
    									<option value="BA">Bahia</option>
    									<option value="CE">Ceará</option>
    									<option value="DF">Distrito Federal</option>
    									<option value="ES">Espírito Santo</option>
    									<option value="GO">Goiás</option>
    									<option value="MA">Maranhão</option>
    									<option value="MT">Mato Grosso</option>
    									<option value="MS">Mato Grosso do Sul</option>
    									<option value="MG">Minas Gerais</option>
    									<option value="PA">Pará</option>
    									<option value="PB">Paraíba</option>
    									<option value="PR">Paraná</option>
    									<option value="PE">Pernambuco</option>
    									<option value="PI">Piauí</option>
    									<option value="RJ">Rio de Janeiro</option>
    									<option value="RN">Rio Grande do Norte</option>
    									<option value="RS">Rio Grande do Sul</option>
    									<option value="RO">Rondônia</option>
    									<option value="RR">Roraima</option>
    									<option value="SC">Santa Catarina</option>
    									<option value="SP">São Paulo</option>
    									<option value="SE">Sergipe</option>
    									<option value="TO">Tocantins</option>
    								</select>
    							</td>
                                <td><input name="arvore" type="number" max="9999" value="0"></td>
                                <td><input name="volume" type="number" max="9999" value="0"></td>
    						</tr>
                            <tr>
                                <td colspan="4"><input type="submit" value="Calcular"><input type="reset"></td>
    						</tr>
    					</table>
    				</fieldset>
    			</form>
    		</div>
    	</body>
    </html>
    
    <?php
    	
    	if($_POST != null) {
    		$ano 		= $_POST['ano'];
    		$estado 	= $_POST['estado'];
    		$arvore 	= $_POST['arvore'];
    		$volume 	= $_POST['volume'];
    		$arvoreR 	= (intval($volume) * 6);
    		$totalPagar = (intval($arvore) * 0.75);	
    		} else {
    		$ano 		= 0;
    		$estado 	= 0;
    		$arvore 	= 0;
    		$volume 	= 0;
    		$arvoreR 	= 0;
    		$totalPagar = 0;			
    	}
    	
    ?>
    <legend align='center'></legend>
    <table border='1' align='center'>
    	<tr>
    		<td colspan='6' align='center'>Resultado</td>
    	</tr>
    	<tr style='size: 16px; font-weight:bold; font-family: 'Arial Narrow';>
    		<td>Ano Base </td><td>Estado Origem </td><td>Árvores cortadas </td><td>Volume (m³) </td><td>Árvores a repor </td><td>Total a ser Pago</td>
    	</tr>
    	<tr align='center'>
    		<td><?php echo $ano			?></td>
    		<td><?php echo $estado		?></td>
    		<td><?php echo $arvore		?></td>
    		<td><?php echo $volume		?></td>
    		<td><?php echo $arvoreR		?></td>
    		<td><?php echo $totalPagar	?></td>
    	</tr>
    </table>

    public by DinhoPutz modified Feb 5, 2019  54  0  3  0

    PHP basic function to find a word in a string

    <?php 
    
    function replaceText($text) {
      // The wanted word
    	$expected = "World"; 
    	
    	$save = str_replace($expected, "<b>World</b>", $text);
    	
    	$cont = strpos($text, $expected) !== false;
    	
    	if($cont == true){
    		echo "True: " . $save; 
    	} else { 
    		echo "False: " . $text;
    	}
    }
    
    // the call function 
    replaceText("Hello World");						

    public by DinhoPutz modified Feb 1, 2019  60  1  3  0

    Criando / Atualizado dados no RM via SOAP com PHP

    Atualizando dados no Totvs Corpore RM via PHP com SOAP utilizando o método SaveRecord do WebServices
    <?php
    	// chamada para o webservice via Soap
    	$wsdl ='http://SERVIDOR:8051/wsDataServer/MEX?wsdl';
    	
    	// Paramêtros para iniciar a sessão
    	$soapParametros = array('login' => 'mestre',
    	'password' => 'totvs',
    	'authentication' => SOAP_AUTHENTICATION_BASIC,
    	'trace' => 1,
    	'exceptions' => true
    	);	
    	
    	// Criando objeto para fazer chamada
    	$client = new SoapClient($wsdl, $soapParametros);
    	$function = 'SaveRecord';
    	
    	// Argumentos para atualização de dados via SOAP/XML 
    	$arguments = array(array( 'SaveRecord',
    	'DataServerName' => 'RhuPessoaData',
    	'XML' => '<RhuPessoa><PPessoa><CODIGO>12</CODIGO><APELIDO>Aninha =)</APELIDO></PPessoa><VPCompl><CODPESSOA>12</CODPESSOA><IDADE>26</IDADE><PESO>62</PESO></VPCompl></RhuPessoa>',
    	'Contexto' => '?' ));
    	
    	// Converter para XML, não utilizado nesse momento é apenas um teste
    	// $xml = simplexml_load_string($arguments[0]["XML"]) or die("Erro");	
    
    	//var_dump($xml);	
    	
    	// Anotações para lembrar 
    	// $options = array('location' => 'http://350z:8051/wsDataServer.asmx');
    	// (String xmlContexto, Boolean checkRoot) em RM.Con.Conector.ConWSDataServer.
    	// SaveRecord(String DataServerName, String XML, String UserName, String UserPassword, String contexto, String emailUsuarioContexto) ) 
    	
    	// Chamada para salvamento
    	$result = $client->__soapCall($function, $arguments);
    
    	// Retorno da execução 
    	// Se tudo ocorrer como deve, vai retorno a chama primaria o objeto
    	print_r($result);
    ?>

    public by DinhoPutz modified Jan 31, 2019  223  2  4  0

    Consumir dados do RM por PHP via SOAP

    Este código faz uma consulta simples e direta via PHP / SOAP no banco de dados do Totvs RM
    <?php
    	// SOAP client
    	
    	$wsdl ='http://servidor:8051/wsDataServer/MEX?wsdl';
    	
    	$soapParametros = array('login' => 'mestre',
    	'password' => 'totvs',
    	'authentication' => SOAP_AUTHENTICATION_BASIC,
    	'trace' => 1,
    	'exceptions' => true
    	);
    	
    	$paramentros = array('DataServerName' => 'EduAlunoData', 'Filtro'=>'1=1', 'Contexto'=>'?'); 
    	
    	try{
    		$client = new SoapClient($wsdl, $soapParametros);
    		$retorno = $client->ReadView($paramentros);
    		$retorno2 =  $client->__getLastResponse();
    		echo "<pre>" . $retorno2 . "</pre>";
    	}	
    	catch (Exception $e)
    	{
    		echo "<h4>Error!</h4>";
    		echo $e -> getMessage ();
    		echo '<pre>Last response: '. $client->__getLastResponse() . '</pre>';
    	}
    

    public by oliverrussell modified Nov 4, 2018  140  0  3  0

    Codeigniter Curl

    Use Codeigniter Curl library to parse data in JSON format.
    $this->load->library('Curl');
    
    $url = 'http://your-domin.com/';
    
    $formatJsondata = array(
    
       'username' => 'authenticate-username',
    
       'password' => 'password-authentication'
    
    );
    
    $encodedJsonData = json_encode($formatJsondata);
    
    $this->curl->create($url);
    
    $this->curl->option(CURLOPT_HTTPHEADER, array('Content-type: application/json; Charset=UTF-8'));
    
    $this->curl->post($encodedJsonData);
    
    echo $result = $this->curl->execute();

    public by simon_sourcecode modified May 2, 2018  732  0  3  0

    Konstanten durch neue Definition ersetzen

    PHP
    // Replace define with const
    [DEFINdefin]{6}[ ]*\(\'ARTRES_PROP_([A-Z_0-9]+)\',([\t 0-9]+)\)\;

    public by azazqadir modified Apr 11, 2018  742  1  5  0

    Using WooCommerce Rest API for Custom Dashboard

    Using WooCommerce Rest API (https://www.cloudways.com/blog/custom-dashboard-using-woocommerce-php-rest-api/ ) to create a Custom Dashboard
    <div class="container">
    
                                      <h2 class="sub-header">Customers List</h2>
    
                                      <div class='table-responsive'>
    
                                          <table id='myTable' class='table table-striped table-bordered'>
    
                                              <thead>
    
                                                  <tr>
    
                                                      <th>Email</th>
    
                                                      <th>Name</th>
    
                                                      <th>Billing Address</th>
    
                                                      <th>Total Orders</th>
    
                                                      <th>Total spent</th>
    
                                                      <th>Avatar</th>
    
                                                      <th>Actions</th>
    
                                                  </tr>
    
                                              </thead>
    
                                              <tbody>
    
                                                  <?php
    
                      foreach($customers as $customer){
    
    
    
                      echo "<tr><td>" . $customer["email"]."</td>
    
                                <td>" . $customer["first_name"].$customer["last_name"]."</td>
    
                                <td>" . $customer["billing"]["address_1"]."</td>
    
                                <td>" . $customer["orders_count"]."</td>
    
                                <td>" . $customer["total_spent"]."</td>
    
                                <td><img height='50px' width='50px' src='".$customer["avatar_url"]."'></td>
    
                                 <td><a class='open-AddBookDialog btn btn-primary' data-target='#myModal' data-id=".$customer['id']." data-toggle='modal'>Update</a>
    
                                 <a class='open-deleteDialog btn btn-danger' data-target='#myModal1' data-id=".$customer['id']." data-toggle='modal'>Delete</a></td></tr>";
    
                      }
    
    
    
                      ?>
    
                                              </tbody>
    
                                          </table>
    
                                      </div>
    
      </div>												

    public by DaveMorton modified Apr 2, 2018  707  2  5  1

    connect.php - Database Abstraction Functions

    <?php
    /* 
     *  %[Filename]=[connect.php]%
     * This is a complete set of PDO abstraction functions
     * to make connecting, reading from and writing to a
     * MySQL database faster and easier. It's meant to be
     * used as a snippet in RapidPHP/WeBuilder from Karlis
     * Bluementals, but can easily be used in many other
     * web development IDEs. Items with %[something]% or
     * %[something]=[value]% are replaceable parameters
     * in RapidPHP/WeBuilder and can be swapped out with
     * whatever you like
     */
    
    /* DB Credentials */
    
    $dbh    = '%[Hostname]=[localhost]%';
    $dbn    = '%[DB Name]%';
    $dbu    = '%[Username]=[username]%';
    $dbp    = '%[Password]=[password]%';
    $dbPort = '%[DB Port]=[3306]%';
    
    $db = db_open($dbh, $dbu, $dbp, $dbn, $dbPort);
    
    /**
     * function db_open()
     * Connect to the database
     *
     * @internal param string $dbh    - db host
     * @internal param string $dbu    - db user
     * @internal param string $dbp    - db password
     * @internal param string $dbn    - db name
     * @internal param string $dbPort - db port
     * @return resource $dbConn - the database connection resource
     */
    function db_open($dbh, $dbu, $dbp, $dbn, $dbPort=3306)
    {
        try {
            $dbConn = new PDO("mysql:host=$dbh;dbname=$dbn;charset=utf8", $dbu, $dbp);
            $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $dbConn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            $dbConn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
        }
        catch (Exception $e)
        {
            exit('The application has encountered a problem with connecting to the database. With any luck, the following message will help: ' . $e->getMessage());
        }
        return $dbConn;
    }
    
    /**
     * function db_close()
     * Close the connection to the database
     *
     * @internal param resource $dbConn - the open connection
     *
     * @return null
     */
    function db_close()
    {
        return null;
    }
    
    /*
     * function db_fetch_all
     * Fetches all matching rows of data from the database
     *
     * @param (string) $sql - The SQL query to execute
     * @param (mixed) $params - either an array of placeholder/value pairs, or null, for no parameters
     * @param (string) $file - the path/filename of the file that the function call originated in
     * @param (string) $function - the name of the function that the function call originated in
     * @param (string) $line - the line number of the originating function call
     *
     * @return (mixed) $out - Either the row of data from the DB query, or false, if the query fails
     */
    
    function db_fetch_all($sql, $params = null, $file = 'unknown', $function = 'unknown', $line = 'unknown')
    {
        global $dbConn;
        try
        {
            $sth = $dbConn->prepare($sql);
            ($params === null) ? $sth->execute() : $sth->execute($params);
            return $sth->fetchAll();
        }
        catch (Exception $e)
        {
            //error_log("bad SQL encountered in file $file, line #$line. SQL:\n$sql\n", 3, _LOG_PATH_ . 'badSQL.txt');
            $pdoError = print_r($dbConn->errorInfo(), true);
            $psError  = print_r($sth->errorInfo(), true);
            return false;
        }
    }
    
    /*
     * function db_fetch_row
     * Fetches a single row of data from the database
     *
     * @param (string) $sql - The SQL query to execute
     * @param (mixed) $params - either an array of placeholder/value pairs, or null, for no parameters
     * @param (string) $file - the path/filename of the file that the function call originated in
     * @param (string) $function - the name of the function that the function call originated in
     * @param (string) $line - the line number of the originating function call
     *
     * @return (mixed) $out - Either the row of data from the DB query, or false, if the query fails
     */
    function db_fetch_row($sql, $params = null, $file = 'unknown', $function = 'unknown', $line = 'unknown')
    {
        global $dbConn;
        //error_log(print_r($dbConn, true), 3, _LOG_PATH_ . 'dbConn.txt');
        try
        {
            $sth = $dbConn->prepare($sql);
            ($params === null) ? $sth->execute() : $sth->execute($params);
            $out = $sth->fetch();
            return $out;
        }
        catch (Exception $e)
        {
            //error_log("bad SQL encountered in file $file, line #$line. SQL:\n$sql\n", 3, _LOG_PATH_ . 'badSQL.txt');
            $pdoError = print_r($dbConn->errorInfo(), true);
            $psError  = print_r($sth->errorInfo(), true);
            return false;
        }
    }
    
    /*
     * function db_write
     * Writes and/or updates data to the database
     *
     * @param (string) $sql - The SQL query to execute
     * @param (mixed) $params - either an array of placeholder/value pairs, or null, for no parameters
     * @param (string) $file - the path/filename of the file that the function call originated in
     * @param (string) $function - the name of the function that the function call originated in
     * @param (string) $line - the line number of the originating function call
     *
     * @return (mixed) $out - Either the number of rows affected from the DB query, or false, if the query fails
     */
    
    function db_write($sql, $params = null, $multi = false, $file = 'unknown', $function = 'unknown', $line = 'unknown')
    {
        global $dbConn;
        try
        {
            $sth = $dbConn->prepare($sql);
            switch (true)
            {
                case ($params === null):
                    $sth->execute();
                    break;
                case ($multi === true):
                    foreach ($params as $row)
                    {
                        $sth->execute($row);
                    }
                    break;
                default:
                    $sth->execute($params);
            }
            return $sth->rowCount();
        }
        catch (Exception $e)
        {
            $pdoError = print_r($dbConn->errorInfo(), true);
            $psError  = print_r($sth->errorInfo(), true);
            error_log("bad SQL encountered in file $file, line #$line. SQL:\n$sql\nPDO Error:\n$pdoError\nSTH Error:\n$psError\nEsception Message:\n" . $e->getMessage(), 3, _LOG_PATH_ . 'db_write.txt');
            return false;
        }
    }

    public by brsgrlr modified Mar 5, 2018  872  3  4  0

    phptags

    opening and closing php tags
    PHP
    <?php  ?>

    public by azazqadir modified Feb 20, 2018  781  1  4  1

    LEMP on Debian

    Learn how to install LEMP on Debian: https://www.cloudways.com/blog/how-to-create-a-lemp-stack-on-debian-server/
    php
    location ~ \.php$ {
    
                   
    
                   fastcgi_pass unix:/var/run/php5-fpm.sock;
    
                   fastcgi_index index.php;
    
                   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    
                   include fastcgi_params;
    
                   
    
           }			
    • Public Snippets
    • Channels Snippets