Category Archives: PHP

nginx – avoid 501 and 502 nginx errors

This are my settings on /etc/php5/fpm/pool.d/www.conf to avoid 501 and 502 nginx errors… on CentOS 7 location of www.conf is at /etc/php-fpm.d/.
The server has 16Gb RAM. This configuration is for a 8Gb RAM server so…

pm.max_children = 70
pm.start_servers = 20
pm.min_spare_servers = 20
pm.max_spare_servers = 35
pm.max_requests = 500

Sources & more readings
http://myshell.co.uk/blog/2012/07/adjusting-child-processes-for-php-fpm-nginx/
http://jeremymarc.github.io/2013/04/22/nginx-and-php-fpm-for-performance/

Simple PHP contact form with Google reCaptcha

So, *everyone* needs a simple form to send emails, via PHP, but we also need a protection agains bots/spammers.
This is code that i’v grabbed from codeforgeek and improved since the original had a few errors that made it impossible to run/work/send email.

It uses Google reCaptcha and you need to register you site/domain on it and grab the site key and the secret key.

The form already has twitter bootstrap classes… but you can remove them! 🙂

The form.php – at the begin
<?php
	$to      = '[email protected]';
	$subject = 'Support Message';

	// keys from Google reCaptcha https://www.google.com/recaptcha/admin
	$sitekey = 'recaptcha_site_key';
	$secretkey = 'recaptcha_secret_key';

	$alert = '';
	if ($_SERVER['REQUEST_METHOD'] == 'POST')
	{
		$email;$message;$captcha;
		if(isset($_POST['email']))
        			$email=$_POST['email'];
		        if(isset($_POST['message']))
        			$message=$_POST['message'];
			if(isset($_POST['g-recaptcha-response']))
        		$captcha=$_POST['g-recaptcha-response'];

	        	if(!$captcha)
        		$alert = '<div class="alert alert-warning" role="alert">Please wait until the captcha protection give you a check mark.</div>';

        	$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret='.$secretkey.'&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']));

		if($response->success==false)
		{
			/* lets set the error message for the alert... */
			if ($alert=='')
				$alert = '<div class="alert alert-danger" role="alert">Some how you have been detected has a spammer.</div>';
        	}
		else
		{
			/* the email to you */
			$headers = 'From: '.$to.'' . "\r\n" .
                	'Reply-To: '.$email.'' . "\r\n" .
                	'X-Mailer: PHP/' . phpversion();
            		mail($to, $subject, $message, $headers);
			/* the copy of the email to the *client* */
			$headers = 'From: '.$email.'' . "\r\n" .
				'Reply-To: '.$to.'' . "\r\n" .
				'X-Mailer: PHP/' . phpversion();
			mail($email, 'COPY - '. $subject, $message, $headers);
			/* lets set the success message for the alert... */
			$alert = '<div class="alert alert-success" role="alert">Your email has been sent.</div>';
        	}
	}
?>
The html form
<?=$alert?>
<form id="comment_form" action="" method="post">
	<input name="email" type="email" placeholder="Type your email" size="40" class="form-control" value="<?=@$email?>" ><br><br>
	<textarea name="message" rows="8" cols="39" class="form-control"  placeholder="Your message to us..." ><?=@$message?></textarea><br>
	<div class="g-recaptcha" data-sitekey="<?=$sitekey?>"></div><br>
	<input type="submit" name="submit" value="Send message" class="btn btn-default"><br>
</form>

Some where at the bottom/footer…

<script src='https://www.google.com/recaptcha/api.js'></script>

 

Hope it helps anyone! 🙂

How to generate a .htpasswd password with PHP?!

This worked for me.

$new_password = password_hash($old_password, PASSWORD_BCRYPT);

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt().
Therefore, password hashes created by crypt() can be used with password_hash().

PASSWORD_BCRYPT – Use the CRYPT_BLOWFISH algorithm to create the hash.
This will produce a standard crypt() compatible hash using the “$2y$” identifier. The result will always be a 60 character string, or FALSE on failure. Supported Options:

http://php.net/manual/en/function.password-hash.php

upstream sent too big header while reading response header from upstream

While I was running some scripts, of my new project, from time to time the PHP kinda had some breaks…. went to error.log and I saw the following error.

2015/08/02 19:42:19 [error] 25586#0: *8735692 upstream sent too big header while reading response header from upstream, client: 84.91.69.69, server: www.flow.domain.com, request: "GET /worker/?action=runHTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "flow.domain.com", referrer: "http://flow.domain.com/worker/?action=flushall"

I had to edit my nginx domain.conf and add the lines in bold!

location ~ \.php$ {
 try_files $uri =404;
 fastcgi_split_path_info ^(.+\.php)(.*)$;
 fastcgi_pass unix:/var/run/php5-fpm.sock;
 fastcgi_index index.php;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 access_log off;
 fastcgi_buffers 16 16k;
 fastcgi_buffer_size 32k;
}

OK!
Save it and restart nginx!
Should solve it! 🙂

PHP fetching webpage – file_get_contents – failed to open stream: Redirection limit reached, aborting

I’m my new venture, I need to fetch some webpages – public webpages -…
On a domain, the index page is parsed 100%, without any problem, but all the other pages weren’t returning me the HTML, in fact event CURL wasn’t returning me any error.

First it was protected against any fetch without a user agent defined.
After I’v work it out, I wasn’t getting any HTML source..

I’v decided to use file_get_contents to see if I got any error, since CURL wasn’t returning me any…
And I got it.

failed to open stream: Redirection limit reached, aborting
2015/07/29 14:28:22 [error] 25586#0: *6458641 FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(http://www.domain.com/page/): failed to open stream: Redirection limit reached, aborting in /home/webroot/worker/testes.php on line 5" while reading response header from upstream, client: 84.91.69.69, server: www.gipsy.digitalwhores.net, request: "GET /worker/testes.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "gipsy.digitalwhores.net"

After a few searches I was able to solve it.
This is my PHP CURL.

function getPage ($url) {


$useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36';
$timeout= 120;
$dir            = dirname(__FILE__);
$cookie_file    = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
$content = curl_exec($ch);
if(curl_errno($ch))
{
    echo 'error:' . curl_error($ch);
}
else
{
    return $content;        
}
    curl_close($ch);

}

The solution was in allowing cookies.

 

Shared it here http://stackoverflow.com/questions/12164196/warning-file-get-contents-failed-to-open-stream-redirection-limit-reached-ab/31704183#31704183

 

PHP – check if a file was changed under 10 mins ago

I need to cache results of a PHP glob of a folder…
This folder gets files uploaded via FTP from time to time and I need to prevent the script to perform a glob every time that the page is accessed.

 

$file = 'content.json' ; 
$time = 600 ; //in seconds 

if(!file_exists($file)) 
{ 
  echo 'does not exist' ;
  // lets call the function that makes the glob and create the content.json 
} 
else 
{ 
 if( time() - filemtime( $file ) <= $time ) 
 { 
 echo 'file last changed under 10 mins ago' ; 
 } 
 else 
 { 
 echo 'file last changed more than 10 mins ago' ;
 // lets call the function that makes the glob and create the content.json 
 } 
}