Archive for category PHP
Problem with mysql connect to remote database?
Yesterday i found a peculiar problem. We have just transferred our application from our local server to another server. But after that this application wasn’t working properly
.
Anyway, we have tried to locate the problem and found that it wasn’t connecting to the replica database (another mysql database) properly. But most interesting thing was i was successful to connect from command prompt using ssh using same connection parameter.
Then i wrote an script to test the connection and found that i can’t connect to remote database using mysql_connect X(
Anyway, after surfing a lot i’ve found a solution to solve the problem.
Open your my.cnf which is placed in /etc/ directory and find the following line.
bind-address=127.0.0.1
It allow only localhost to connect. So delete or comment out this line. It will solve the problem
But my porblem wasn’t that. infact that line wasn’t exist in my my.cnf file. Problem was with the extra security that apache provide now a days. apache doesn’t allow connetion to other network by default. So follow the instruction to activate network connection.
At first, verify that SELinux is enabled or not.
in order to varify type in your command prompt getenforce
You should see something like Enforcing
If you see a different result, type setenforce 1 in the command prompt
If you get an error, then you do not have Selinux turned on. Go to /etc/selinux/config and edit the config file to enable Selinux.
Now reboot the linux server
Once SELinux is enabled, do the following
Set SELinux to allow remote connections for HTTP
setsebool -P httpd_can_network_connect=1
Tha’ll do the trick.
How to tune Apache and Mysql
By default, Apache comes preconfigured to serve a maximum of 256 clients simultaneously. This particular configuration setting can be found in the file /etc/httpd/conf/httpd.conf
If your server has 2 GB of RAM, and you’re sharing your server with MySQL(true in my case), you’ll want to reserve about half of it for Apache (1 GB)
MaxClients: here is the process of determining MaxClients. type
ps -U apache -u apache u
See the number of apache process running in you command prompt.
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
apache 7694 0.0 0.3 42704 6680 ? S 18:30 0:00 /usr/sbin/httpd
The above indicates that a single httpd process is using 6.6 MB of RSS (Resident Set Size) memory (or non-swapped physical memory) and that it is using 42 MB of VSZ (Virtual Size) memory. This depends on the number of modules you have loaded and running in Apache.
As shared libraries are included in this number, it’s not 100 percent accurate. We can assume that half the RSS number is “real” memory. Let’s assume that each httpd process is using (6.6/2=3.3) 4 MB of memory. So if you have 1 GB ram then divide it with 4 MB of memory, which leaves room for around 256 concurrent httpd processes. Set MaxClients 256
Or
Somebody prefers to set MaxClients using following rule
MaxClients = 150 x RAM (GB)
So for example if you have 2 GB RAM (dedicated for apache) set this value to 300. In my case IT WILL BE 150
Or
Some individuals maintain that each httpd thread uses about 5 MB of “real” memory. So they determine by the following way..
Or MaxClients = RAM(MB)/5
So for example if you have 2 GB RAM (dedicated for apache) set this value to 409. In my case IT WILL BE 204(1 GB for apache)
Note: There is no reason for you to set it any higher unless you have a specific problem with this value. A high value can lead to a complete server hang in case of a DOS attack. A value too low can create timeout problems for your clients if the limit is reached
StartServers - Sets the number of child server processes created on startup. This setting depends greatly on the type of webserver you run. If you run low traffic websites on that server set it low to something like 5. If you have resource intensive websites on that server you should set it close to MaxClients.
MaxRequestsPerChild - Controls the number of request the a child serves before the child is killed. This should not be set too low as it will put an unnecessary load on the apache server to recreate the child. I suggest setting it to 1000. But we are going to use 2000 for handling heavy traffic load properly.
MinSpareServers and MaxSpareServers - MaxSpareServers and MinSpareServers control how many spare (unused) child-processes Apache will keep alive while waiting for more requests to put them to use. Each child-process consumes resources, so having MaxSpareServers set too high can cause resource problems. On the other hand, if the number of unused servers drops below MinSpareServers, Apache will fork. Leave those values to: MinSpareServers 5 MaxSpareServers 10
ServerLimit: Its better to keep Server limit same as the value of MaxClients.
MaxRequestsPerChild: I’ve Kept default apache value for this one.
So few changes need to be made in httpd.conf file which is located in /etc/httpd/conf/ directory
<IfModule prefork.c>
StartServers 140
MinSpareServers 5
MaxSpareServers 10
ServerLimit 150
MaxClients 150
MaxRequestsPerChild 4000
</IfModule>
[Note]: Response time depends on MaxClients. If you increase the MaxClients number, server will response more quickly for each request but a high value can lead to a complete server hang.
Ab is a tool for benchmarking the performance of your Apache HyperText Transfer Protocol (HTTP) server. It does this by giving you an indication of how many requests per second your Apache installation can serve.
uptime command in your root login should not yield a load average above 1, and the server should respond to commands quickly
ab -n 10000 -c 200 -k http://your_url
-c = concurrent connections
-t = time limit
-n = # of requests
Keep tuning until you hit your maximum desired load average. For servers used interactively often, having a load above 3 is way too much to use the server comfortably. For servers used mostly as real servers, a maximum load average of 10 should be acceptable. More than that, and you’ll find yourself needing to reboot the server when experiencing heavy traffic conditions, because no terminal or remote console will respond quickly to commands, and managing the server will be impossible.
How to configure few things in php.ini file for supporting huge traffic
* Enable the compression of HTML by putting in your php.ini:
output_handler = ob_gzhandler
** Switch from file based sessions to shared memory sessions. Compile PHP with the –with-mm option and
set session.save_handler=mm
Configure mysql. Change my.cnf file for better performance.
The database parameters are tuned for systems with 1 GB RAM (for ISO CD images). If you have higher RAM, please change the following in the “my.cnf” MySQL configuration file under /etc/mysql or /etc directory.
For a machine running with 512 MB of RAM, you can set these to:
key_buffer=128M table_cache=1024 sort_buffer=64M read_buffer=2M record_buffer=4M
For a machine running with 1 GB of RAM, you can set these to:
key_buffer=256M table_cache=2048 sort_buffer=128M read_buffer=2M record_buffer=8M
For a machine running with 2 GB of RAM, you can set these to:
key_buffer=512M table_cache=3072 sort_buffer=256M read_buffer=2M record_buffer=8M
For a machine running with 4 GB of RAM, you can set these to:
key_buffer=1G table_cache=4096 sort_buffer=512M read_buffer=2M record_buffer=8M
How to grab data from other websites using curl
First of all, you need to enable curl support for php. To do this, remove the comment (to enable curl operation) from php.ini file
To get a remote file executed, we need to pass http request from a php file. CURL is used for this purpose. Here is a simple example that you can try.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.com.bd/");
curl_setopt($ch, CURLOPT_HEADER, 0);
$file_contents = curl_exec($ch);
curl_close($ch);
print_r($file_contents);
?>
Now what we generally do is parse the html and show any portion that you want in your own site or use these data to modify, update or for other purpose. Have fun.
How to grabe all checkbox value from html form and parse it in php
Posted by admin in PHP, Simple tricks on April 7th, 2008
Suppose, we are creating a tool for admin user. where admin can view all the comments and then take necessary action (publish, delete, modify). So in a page it will show all the comments with a checkbox beside every comments. There may have pagination or not.. whatever, doesn’t matter.
So if admin check several checkbox and click on any action then in php file one can grab all the checkbox value by the follwoing way…
I’m considering that you have done all the html stuff :P, One important thing is, in html i’ve set checkbox name with check_coresponding_id_of_that_row. something like
<input id="check_$row->id" name="check_$row->id" type="checkbox" />
Now in php file paste these lines and debug. Hope you will get your desired result.
$test = $_POST;
foreach($test as $key=>$value)
{
//$pieces[] = explode(”check”, $key);
$key = strstr($key, ‘_’);
$key = substr($key, 1);
$msg_id[] = $key;
}$message_id = implode(”,”, $msg_id);$message_id = substr($message_id, 0, -1);
print_r($message_id);
There is several way to do it actually
but hey, i’ve kept this portion for my personal use too ;).
Ke jane kon din lage.. lol
Parse mysql result(multiple records) info with delemiter and show with ajax.
Posted by admin in Javascript, PHP on March 4th, 2008
In javascript, call ajax with proper info
var DELIM_1 = '###';
var DELIM_2 = '^^^';
function getEmployerInfo(emp_id)
{
showLayer(LOADING_MSG, 'loadLayer');
var url = '';
var pars = 'cmd=showEmployer&id=' + emp_id;
var myAjax = new Ajax.Request(
url,
{
method: 'get',
parameters: pars,
onComplete: showResponse
});
}
now in php file select multiple records and return as a string…
function getEmployerInfo($employerID)
{
$info['table'] = EMPLOYER_TBL;
$info['where'] = ‘id = ‘ . $employerID;
$result = select($info);
if(empty($result))
{
return null;
}
foreach( $result[0] as $key => $value)
{
$data[] = $key . DELIM_1 . stripslashes($value);
}
return implode(DELIM_2, $data);
}
Finally in js response you should do …
function showResponse(retVal)
{
var response = retVal.responseText.split(DELIM_2);
var frm = document.frmEmployer;
with(frm)
{
for(i = 0; i < response.length; i++)
{
var values = response[i].split(DELIM_1);
if(values[0] == ‘billing_type’)
{
for(j = 0; j < eval(values[0]).length ; j++)
{
if(eval(values[0])[j].value == values[1])
{
eval(values[0])[j].checked = true;
}
else
{
eval(values[0])[j].checked = false;
}
}
continue;
}
if($(values[0]))
{
$(values[0]).value = values[1];
}
}
}
hideLayer(’loadLayer’);
$(’addNew’).style.display = ‘inline’;
}
How to do advance query in mysql
When i was doing an advance job search for my personal project i have organised the “where clause” in the following way…
in the advanced search template there was too many input fields but i think its not necessary to list all those fields here in the following example. That’s why i’ve shown the way considering only 4 input fields.
$JobTitle = $_REQUEST['txtJobTitle'];
$State = $_REQUEST['selState'];
$JobType = $_REQUEST['selJobType'];
$searchDate = $_REQUEST['txtDate'];
$whereClause = ”;
if( $JobTitle )
{
if( $whereClause ) $whereClause .= ‘ AND ‘;
$whereClause .= ‘job_title like “%’. $JobTitle .’%” ‘;
}
if( $State )
{
if( $whereClause ) $whereClause .= ‘ AND ‘;
$whereClause .= ‘ state like “%’ . $State . ‘%” ‘;
}
if( $JobType )
{
if( $whereClause ) $whereClause .= ‘ AND ‘;
$whereClause .= ‘ job_type like “%’ . $JobType . ‘%” ‘;
}
if( $searchDate )
{
if( $whereClause ) $whereClause .= ‘ AND ‘;
$whereClause .= ‘ create_date = “‘ . $searchDate . ‘” ‘;
}
$stmt = “select * from job where $whereClause”;
$result = mysql_query($stmt);
and finally you can fetch information from $result.
How to deal with ajax (prototype.js)
Posted by admin in Javascript, PHP on December 8th, 2007
Using prototype.js its very easy to implement Ajax (Asynchronous javascript and xml). Just call the specific function from html and then parse the xml that is returned from php.
Here is an example. in this example, we are calling a function in the onChange event of a dropdown box.
<tr>
<td>
<select name=”product_name” id=”product_name” style=”width:165px” onChange=”showprice();”>
<option value=”">Select One</option>
<?php
$searchcategory = “select product_name, product_id from product”;
$searchquery = mysql_query($searchcategory);
while($row=mysql_fetch_row($searchquery))
{
echo ‘<option>’.$row[0].’</option>’;
}
?>
</select>
</td>
<td align=right>
<label class=”label” id=lbl_product_price name=lbl_product_price> Price </label>
</td>
<td>
<input readonly type=”text” class=”text” id=”product_price” name=”product_price” value=”">
</td>
</tr>
in html head tag include this line
<script language=”JavaScript” src=”prototype.js” mce_src=”prototype.js”></script>
Now in the javacript part, i’ll use prototype.js , and here is how to use it. you can download prototype.js from internet.
function showprice()
{
checkavailability();
var url = ’sales1.php’;
var proname = $F(’product_name’);
var pars = ‘cmd=loadPrice&name=’ + proname;
//alert(pars);
var myAjax = new Ajax.Request(url, {method: ‘get’, parameters: pars, onComplete: showResponse});
}
Now in php file (sales1.php) , just return product price …
if(cmd==loadPrice) //// [note: we have passed cmd = loadPrice in javascript part ]
{
$product_name = $_REQUEST['product_name'];
$statement =”select product_price from product where product_name=$product_name”;
$result = mysql_query($statement);
$row = mysql_fetch_object($result);
return $row->product_price;
}
Now parse the return value in javascript showResponse function
function showResponse(serverResponse){
if(serverResponse.responseText){
$(’product_price’).value = parseInt(serverResponse.responseText);
// if you want to show the price in a div or in a td then you should use $(’product_price’).innerHTML in place of $(’product_price’).value //
}
}
That’s all. Enjoy
Recent Comments