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

Find second and fourth saturday's of the month in PHP-MySql

Find second and fourth saturday's of the month in PHP-MySql


In this section, I have created simple script in PHP to find second(2nd) and fourth(4th) Saturday of the month.

<?php
// Mysql Connection
$conn = mysql_connect('localhost','root','');
if (!$conn) {
die('Could not connect to MySQL: ' . mysql_error());
}
echo 'Connection OK'; mysql_close($conn);

// Select Database
mysql_select_db("test");

// Array of the Month's
$month_array=array("jan","Feb","Mar","Apr","May","Jun","july",'Aug',"Sep","Oct","Nov","Dec");

// Array of the Years's
$year_array=array("2013","2014");

foreach($year_array as $year)
{

foreach($month_array as $month)
{
echo $second=date('Y-m-d', strtotime("second sat of $month $year"));
echo "<br>";
echo $fourth=date('Y-m-d', strtotime("fourth sat of $month $year"));
echo "<br>";

}
}

?>



You can use this PHP script to find second and fourth saturday of particular month and year.


Bookmark and Share

Yahoo Weather API PHP Script Example/Widget

Yahoo Weather API PHP Script Example/Widget  

In this example, I will show how to create weather application using Yahoo Weather API.Yahoo Weather API allows developers and programmers to get up-to-date weather information for your location.Yahoo Weather API provides local & long range Weather Forecast, Current Conditions, weather icons and two day future.

<?php
/*

Example: Yahoo! Weather API Example Using SimpleXML in PHP.

The base URL for the Weather RSS feed is
http://weather.yahooapis.com/forecastrss

Parameters
w WOEID 
e.g: w=111111

u Units for temperature
f: Fahrenheit
c: Celsius 
e.g.: u=c

*/


$city="bangalore";

$result1 = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22$city%22&format=xml");
$xml1 = simplexml_load_string($result1);
 $woeid=$xml1->results->place->woeid;

if($woeid!="")
{
$fetchData = file_get_contents("http://weather.yahooapis.com/forecastrss?w=$woeid&u=c");
$xmlData = simplexml_load_string($fetchData);
$location = $xmlData->channel->xpath('yweather:location');


if(!empty($location))
{

foreach($xmlData->channel->item as $data)
{
$current_condition = $data->xpath('yweather:condition');
$forecast = $data->xpath('yweather:forecast');
$current_condition = $current_condition[0];
echo "
<table width=40% border=1 align=center>
<tr>
<td align=center style='background-color:yellow'>
  <h1>{$location[0]['city']}, {$location[0]['region']}</h1>
<small>Date: {$current_condition['date']}</small>
<h2>Current Temprature</h2>
<p>
<span style=\"font-size:64px;font-color:red; font-weight:bold;\">{$current_condition['temp']}°C</span>
<br/>
<img src=\"http://l.yimg.com/a/i/us/we/52/{$current_condition['code']}.gif\" style=\"vertical-align: middle;\"/>
{$current_condition['text']}
</p>
<h2>Forecast</h2>
<b>{$forecast[0]['day']}</b> : {$forecast[0]['text']}. <b>High:</b> {$forecast[0]['high']} <b>Low:</b> {$forecast[0]['low']}
<br/>
<b>{$forecast[1]['day']}</b> - {$forecast[1]['text']}. <b>High:</b> {$forecast[1]['high']} <b>Low:</b> {$forecast[1]['low']}
</p>
</td>
</tr></table>
";
}
}
else
{
echo "<h1>please try a different City.</h1>";
}


}
else
{
echo "<h1>Please try a different City.</h1>";
}

?>



OUTPUT


I hope above example will help you to get weather Information for your location.
For more details check : http://developer.yahoo.com/weather


Bookmark and Share

Create Dynamic Bar Graph/Chart in php

Create Dynamic Bar Graph/Chart in php

In this article, I will show how to dynamically create bar graph in PHP. I have created PHP script to create a bar graph in php such that x-scale and y-scale changes dynamically.

Example : Create dynamic Graph/Chart image page using MySQL&PHP

<?php

$hrs= array( "0" => 11, "1" => 12 ,"2" => 13 ,"3" => 14 ,"4" => 15);

$data= array ("0" => 15 ,"1" => 11, "2" => 5, "3" => 15 ,"4" => 17 );

$hrs_len=sizeof($hrs);

if(!empty($data) && !empty($hrs))
{
$data=array_combine($hrs,$data);

$image_width=($hrs_len+1)*32;
$image_height=80;
$padding=20;


$graph_width=$image_width - $padding * 2;
$graph_height=$image_height - $padding * 2;
$image=imagecreate($image_width,$image_height);
$bar_width=25;
$total_bars=count($data);
$gap= 5;
$background_color=imagecolorallocate($image,255,255,255);
$border_color=imagecolorallocate($image,255,255,255);
$line_color=imagecolorallocate($image,255,255,255);


$max_value=max($data);
$ratio= $graph_height/$max_value;
$horizontal_data=20;
$horizontal_gap=$graph_height/$horizontal_data;
for($i=1;$i<=$horizontal_data;$i++){
$y=$image_height - $padding - $horizontal_gap * $i ;
imageline($image,$padding,$y,$image_width-$padding,$y,$line_color);
$v=intval($horizontal_gap * $i /$ratio);
}
   $bar_color=imagecolorallocate($image,50,205,50);
for($i=0;$i< $total_bars; $i++){
list($key,$value)=each($data);
$x1= $padding + $gap + $i * ($gap+$bar_width) ;
$x2= $x1 + $bar_width;
$y1=$padding +$graph_height- intval($value * $ratio) ;
$y2=$image_height-$padding;

imagestring($image,0,$x1+3,$y1-10,$value,$bar_color);
imagestring($image,0,$x1+3,$image_height-15,$key,$bar_color);
imagefilledrectangle($image,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($image);
}
?>


I hope this example will help you to create Dynamic Bar Graph/Chart in php.


Bookmark and Share

Post data to a specific port using PHP/Curl.

Post data to a specific port using PHP/Curl.

In this article,I will show how to Post data to a specific port using PHP/Curl Method. PHP-curl library can be used to communicate with a specific port under Linux and windows platform.

Example: Send data to Port in PHP.

  <?php
ini_set("display_errors",1);
error_reporting(E_ERROR);

$msg="&command=1";
$url = "http://127.0.0.1:1234";

$curl = curl_init();
curl_setopt($curl,  CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $msg);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);

if($response!="")
{
$fp = fopen("test.txt","w");
fwrite( $fp, $response);
fclose($fp);
}

curl_close($curl);
?>





Bookmark and Share

Print a web page using PHP/JavaScript Code

Print a web page using PHP/JavaScript Code

In this article I will show how to Print a HTML Web Page using PHP/JavaScript.I have Written simple script to print Visitor card in PHP.On web page, there is a print option. When the user click on `print` Button it will send a print command to the printer.
We are using Javascript window.print(); function to print HTML portion of a Web Page.

Javascript window.print():
 The window.print() method prints the contents of the current page.This method is supported in all major browsers.

Example: How to Print a Web Page Using JavaScript and PHP.

<!DOCTYPE html>
<HTML lang="en"><HEAD>
<TITLE>Print Visitor card using PHP/JavaScript </TITLE>
<META content=IE=7 http-equiv=X-UA-Compatible>
<META content="text/html; charset=Windows-1252" http-equiv=Content-Type>
<STYLE>
#outer
{
  border-collapse:collapse;
  border: 0px solid black;
  height:250px;width:420px;
 }
.cover{
background:#EEEEEE;
padding: 10px;
text-align:left;
margin:10px;
width:400px;
height:200px;
font-size: 1.0em;
top:10%; left:10%;
/*--CSS3 Box Shadows--*/
-webkit-box-shadow: 0px 0px 20px #000;
-moz-box-shadow: 0px 0px 20px #000;
box-shadow: 0px 0px 20px #000;
/*--CSS3 Rounded Corners--*/
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
}
#inner
{
  border-collapse:collapse;
  border: 0px solid black;
  height:100%;width:100%;
  background:#EEEEEE;

}
#hgt_abv
{ height:18%;}
#hgt_abv_back
{   float:inherit;
height:18px;
width:400px;
background:#000000;
}
#hgt_belo
{ height:3%;background:#FF6600;}
.docimg
{
float:inherit;
hight:119px;
width:90px;
}
.logo
{
float:left;
width:100px;
}
.address
{
    padding:2px;
text-align:left;
margin:2px;
hight:100px;
width:130px;
font-size: 1.1em;
}
</STYLE>
<META name=GENERATOR content="MSHTML 9.00.8112.16446"></HEAD>
<BODY class="ExtravaganzaAqua page-view2" >
<CENTER><SPAN></SPAN>

<TABLE id=outer>
<TR>
<TD><DIV class=cover>
<TABLE id=inner border=0>
<TR>
<TD align=center colspan="2">
<DIV id=hgt_abv_back><FONT color=#ffffff size=3><B>VISITOR     PASS</B></FONT></DIV>
</TD>
</TR>
<TR>
<TD valign="top" align=left><br /><FONT size=2><B>Name: </B><B>Computer Geek</B><br /><br /><br />
<B>Designation: </B><B>Software Engg.</B><br /><br /><br />
<B>Date: </B><B>24th Nov 2012</B><br />
</FONT>
</TD>
<TD valign="top" align=right>
<img width="90" hight="119px" src="user.jpg" alt="bg">
</TD>
</TR>
<TR id=hgt_belo>
<TD colSpan=2></TD>
</TR>
</TABLE>
</DIV>
</TD>
</TR>
</TABLE>
</CENTER>
<center>
<table id=outer>
<tr>
<td align="right" valign="top">
<button type="button" onclick="window.print();" >Print</button>
</td>
</tr>
</table>
</center>
</BODY>
</HTML>


I hope this example will help you to Print a Web Page Using JavaScript and PHP.


Bookmark and Share

How to enable SSl on Wamp Server(apache2) - HTTPS Configuration

How to enable SSl on Wamp Server(apache2) - HTTPS Configuration

In this article, I will show how to Configure/Enable SSL in Wamp Server.I have installed wampserver with apache 2.2.12 and php 5.3.5. I have to configure the Open SSL server.



How to Setup HTTPS SSL on WAMP Server for apache 2.2

1. Install WAMPServer

2. Open Control Panel

3. Click System >> Select Advanced System Setting >> Select Environment Variables.

4.Create new system variable OPENSSL_CONF:
   Value: C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf

 
5. Create a SSL Certificate and Key for the Web Server 

 Open command prompt  and Run the following commands:

>cd wamp\bin\apache\apache2.2.12\bin

>openssl genrsa -des3 -out server.key 1024

>copy server.key server.key.org

>openssl rsa -in server.key.org -out server.key

>openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -config          C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf

Create a folder c:\wamp\OpenSSL with the following subfolders:

  i. certificats
ii. private

Copy server.cert, server.csr, server.key files
 from C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\certificats folder

Copy server.key.org file from
 C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\private folder


6. Open Php.ini file

 Remove comment of following line:
 extension=php_openssl.dll 

 OR 

 Left click the wampserver icon >> PHP >> php extensions >> click php_openssl


7. Open Httpd.conf file (C:\wamp\bin\apache\Apache2.2.12\conf\)

Remove comment of following lines:

LoadModule ssl_module modules/mod_ssl.so

LoadModule setenvif_module modules/mod_setenvif.so

Include conf/extra/httpd_ssl.conf

8.Open httpd-ssl.conf file(C:\wamp\bin\apache\Apache2.2.12\conf\extra\)

 Find and replace follwing lines:

 SSLMutex default

 DocumentRoot "C:/wamp/www"

 ErrorLog "C:/wamp/logs/ssl_ErrorLog.txt"
 TransferLog "C:/wamp/logs/ssl_TransferLog.txt"

 SSLCertificateFile "C:/wamp/OpenSSL/certificats/server.crt"

 SSLCertificateKeyFile "C:/wamp/OpenSSL/certificats/server.key"

 CustomLog "C:/wamp/logs/ssl_request.txt" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

 Change Directory Tag:

Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all 

9.Verify SSL/HTTPS

  • Run httpd –t and make sure the syntax is OK.
  • Restart Apache.

10.Check whether the WAMP server is running or not

Right click the wampserver icon >> Rsstart All Services
  • If icon is partially red, it means no service is currently running 
  • If icon is White, that means all services are running.


11.Open https://localhost

12.Done.

I hope this article will help you to enable SSL on the Apache server.


Bookmark and Share

Image upload from url in php

Image upload from url in php

In this Article,I will explain how to upload image from url using php.I have written simple script using php functions to upload image from another domain.

Example: Image upload to URL.
<?php
display_errors(0);
$url = "http://www.example.com/logo.jpg";
$file_name= substr($url, strrpos($url,"/")+1, 
strlen($url)-strrpos($url,"/"));  //Retrive file name from url
$img = file_get_contents($url);//get contents of file
$f = fopen($file_name, 'w');//Open file
fwrite($f, $img);//Write File
fclose($f);  
?>

I hope above script will help you to upload image from URL in php.

Cheers :)


Bookmark and Share

Difference between curl and file_get_contents

Difference between curl and file_get_contents


In this tutorial,I will explain difference between curl and file_get_contents.
PHP offers two main options to get a remote file, curl and file_get_contents. There are many difference between the two.
file_get_contents - It is a function to get the contents of a file
curl - It is a library.curl supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading HTTP form based upload, proxies, cookies.
file_get_contents() for a remote file, it is very slow, and does not handle redirects, caching, cookies.
Curl is a much faster alternative to file_get_contents.


Bookmark and Share

jquery onclick change class script (.removeClass() and .addClass())

JQuery onclick change class (.removeClass() and .addClass())

In this example,I will show How to change class name using Jquery .removeClass() and .addClass() property.

Syntax:
.removeClass(className)
className will be One or more classes to be removed from the class attribute of each matched element.


Bookmark and Share

Strict Standards jcache error - Joomla

Strict Standards jcache error - Joomla

Strict Standards: Accessing static property JCache::$_handle - Joomla error

How about fixing the error?
1. Open cache.php (line number 419)and change all occurences of $this->_handler to JCache::$_handler:

<?php
   public function &_getStorage()
   {
      if (!isset(JCache::$_handler)) {
         JCache::$_handler = JCacheStorage::getInstance($this->_options['storage'], $this->_options);
      }
      return JCache::$_handler;
   }
   ?>


Bookmark and Share

wait_timeout Mysql | max_connections Mysql

wait_timeout Mysql :

wait_timeout defines the number of seconds a mysql thread waits in idle state before mysql kills it.

MySQL uses a lot of different timeout variables at different stages.when connection is just being established connect_timeout is used. When server waits for another query to be sent to it wait_timeout.
By default, the server closes the connection after eight hours if nothing has happened.
You can change the time limit by setting the wait_timeout variable when you
start mysqld.


Bookmark and Share

Clustered indexes Vs Non-clustered indexes-MySql

Clustered indexes Vs Non-clustered indexes-MySql
  • Clustered index will physically order the data based on the values in the index.
  • A non clustered index is a special type of index that stores the records in logical order rather than physical order. This means, a table can have many non clustered indexes. More non clustered indexes per table means more time it takes to write new records.
  • A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
  • A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
  • Clustered index is physically stored a table can have 1 clustered index.
  • Non clustered index is logically stored a table can have 249 non  clustered  index.


Bookmark and Share

Remove duplicate values from an array php

How can remove duplicate values from an array php

array_unique :Removes duplicate values from an array

Syntax:
array_unique(array,sort flag);
sort flag:
ORT_REGULAR - compare items normally
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Example:
<?php
$arr = array("php","tutorial","php","example");
 $unique_arr = array_unique($arr); //removes duplicate values from an array
print_r($unique_arr ); 
?> 
Outputs:
Array
(
[0] => php
[1] => tutorial
[2] => example
)


Bookmark and Share

print_r() Versus var_dump()

Difference between print_r() and var_dump(): 
In this article, I will explain difference between print_r(), var_dump() and var_export().

var_dump():
The var_dump function displays structured information about variables/expressions that includes its type and value

Syntax
var_dump(variable1, variabl2, ....)

Example:
<?php
$str = array(1, 2, "a");
var_dump($str);
?>
OUTPUT:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
string(1) "a"
}


Bookmark and Share

Fatal error: Call to undefined function mcrypt_get_iv_size()

Fatal error: Call to undefined function mcrypt_get_iv_size()
In this tutorials,I will show how to resolve Fatal error: Call to undefined function mcrypt_get_iv_size()

Steps:


1.Download libmcrypt.dll from
   http://ftp.emini.dk/pub/php/win32/mcrypt/

2.Copy the file to system32.

3.Open valid php.ini file in the windows directory

4.Search for a line
;extension=php_mcrypt.dll
in php.ini file

5.Remove the ; at the beginning of the line.

6.Rrestart apache.

7.Done



Bookmark and Share

Enable Htaccess in localhost AppServ

Enable Htaccess in localhost AppServ.
In this tutorials,I will show how to enable htaccess in localhost AppServ

1) Open AppSer installed folder
      For Example In Windows:
      D:\AppServ\Apache2.2\conf\
        OR
      C:\AppServ\Apache2.2\conf\

2).Find and open httpd.conf file

3).Search below line
      #LoadModule rewrite_module modules/mod_rewrite.so

4).if hash is there remove that hash("#")sign in front, becomes:
  LoadModule rewrite_module modules/mod_rewrite.so.

5).save the file

6). restart the AppServe

7).Done.

Cheers..:)


Bookmark and Share

How to count non-empty cells in one row In MySQL


How to count non-empty cells in one row in MySql.
In this section, I will explain how to count non-empty cells in one row in MySql.

Suppose we have to count non empty cells of Price table.

Price table:
Col1          Col2        Col3
1000000     200           1000
4545556     400            NULL     

Query:
SELECT IF(col1 IS NOT NULL, 1, 0) + IF(col2 IS NOT NULL, 1, 0) + IF(col3 IS NOT NULL, 1, 0) AS total_price 
FROM price_table

This query will return Total price of non empty cells(col1,col2,col3)


Bookmark and Share

Import CSV/Excel data into MYSQL database via PHP Script;

Import CSV/Excel data into MYSQL database via PHP Script;

In this article,I will explain How to import the CSV/Excel file in to MYSQL database via PHP Mysql Script.we can use PHP fgetcsv() function to parse/import data from CSV/Excel file into Mysql Database.
fetchCsv.php file will upload the CSV/Excel file and imort the file into Mysql Database.
please check following code:
Example:


fetchCsv.php
<?php
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="";
$db='myDB'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

echo $filename=$_FILES["file"]["tmp_name"];
//echo $ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));


 if($_FILES["file"]["size"] > 0)
 {

$file = fopen($filename, "r");
         while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
         {
            print_r($emapData);
            $sql = "INSERT into myTable(name,address,email,password) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
            mysql_query($sql);
         }
         fclose($file);
         echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";

}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>

<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>

fetchCsv.php file will upload the CSV/Excel file and imort the file into Mysql Database.
If you face any problem than let me know via comment .


Bookmark and Share

How to enable .htaccess in wamp server

How to enable .htaccess in wamp server
In this article,I will explain how to enable .htaccess in wamp server.


1Open wamp_server  (Go to Wamp -> Right click at icon in the taskbar=> Apache=> httpd.conf)



Bookmark and Share

How to get base url in PHP?

How to get base url in PHP?

Example:
<?php
$baseUrl = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https://' : 'http://';
$baseUrl .= isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : getenv('HTTP_HOST');
echo $baseUrl .= isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : dirname(getenv('SCRIPT_NAME'));
?>
Output:
http://domain.com/project/


Bookmark and Share