Category Archives: PHP

php news, php articals, php certification, php frameworks, php classes, php code, php feed, php update, php array, php string, php function, php oops, php xml, php open projects, PHP SOAP

How to Submit form through PHP CURL ?

Last week I was working with salesforce form to collect data from third party website. If you have to just submit form its easy salesforce does not restrict to use CURL in order to post data but my requirement was to post salesforce from data and store that data in my database too. This is easy and simple and has a lot of ways to do.
Now I would like to show you PHP CURL way to post form data. You can use PHP Jquery and Ajax to make it more fancy. But I want to keep it simple.
Step 1 –
I am using one sales force form as example.

 







Step 2  –  This is standard PHP CURL script (form-action-curl.php) to post from you can use anywhere without any modification in from you can add more fields if you need.

 

//Initialize the $query_string variable for later use
$query_string = "";

//If there are POST variables
if ($_POST) {

//Initialize the $kv array for later use
$kv = array();

//For each POST variable as $name_of_input_field => $value_of_input_field
foreach ($_POST as $key => $value) {

//Set array element for each POST variable (ie. first_name=Arsham)
$kv[] = stripslashes($key)."=".stripslashes($value);

}

//Create a query string with join function separted by &
$query_string = join("&", $kv);
}
//Check to see if cURL is installed ...
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}

//The original form action URL from Step 2 :)
$url = 'https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';

//Open cURL connection
$ch = curl_init();

//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

//Set some settings that make it all work :)
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

//Execute SalesForce web to lead PHP cURL
$result = curl_exec($ch);

//close cURL connection
curl_close($ch);
if($result=='ok')
{
//echo '<script>alert("Posted -- ")</script>';
}
// Here you can write mysql query to insert data in table.

$insert_tbl_index_page= "insert into tbl_form_data(first_name,last_name,street,city,zip,phone,email)values('$first_name','$last_name','$street','$city','$zip','$phone','$email')";

Share

How to change date formate of twitter field “created_at”?

php coder who is reading twitter API for latest tweets want to change date/ timestamp format which is returned by ‘created_at’ key. Most of the times I use JSON based request. e. i. http://search.twitter.com/search.json?q=phpmind

These are the fields returned by above request.

Hope fully you understand how json string looks like.

Now it is time to convert date time stamp in more readable format.

echo date("l M j \- g:ia",strtotime($object->returns[0]->created_at));

Please change the date parameters if you want to play with different date formats.

If you want to use javaScript way to format dates here is very cool function.
Returned by twitter – Wed, 09 Feb 2011 02:44:36 +0000

Returned by this javaScript function, TwitterDateConverter ($object->returns[0]->created_at);
Output will be for Example “14 minutes ago”

See Image Below!


function Convert_Datetime($datetime)
{
    define("SECOND", 1);
    define("MINUTE", 60 * SECOND);
    define("HOUR", 60 * MINUTE); define("DAY", 24 * HOUR);
    define("MONTH", 30 * DAY); $delta = time() - strtotime($datetime);

    // convert

    if($delta < 1 * MINUTE)
    {
        return $delta == 1 ? "one second ago" : $delta." seconds ago";
    }
    if($delta < 2 * MINUTE)
    { return "a minute ago";
    }
    if($delta < 45 * MINUTE)
    {
        return floor($delta / MINUTE)." minutes ago";
    }
    if($delta < 90 * MINUTE)
    {
        return "an hour ago";
    }
    if($delta < 24 * HOUR)
    {
        return floor($delta / HOUR)." hours ago";
    }
    if($delta < 48 * HOUR)
    {
        return "yesterday";
    }
    if($delta < 30 * DAY)
    {
        return floor($delta / DAY)." days ago";
    }
    if($delta < 12 * MONTH)
    {
        $months = floor($delta / DAY / 30); return $months <= 1 ? "one month ago" : $months." months ago"; }
    else
    {
        $years = floor($delta / DAY / 365); return $years <= 1 ? "one year ago" : $years." years ago";
    }

echo Convert_Datetime("2015-04-1 22:10:00"); // one year ago

Share

How to Enable CURL in WAMP?

CURL is not enabled by default in WAMP. Every php programmer have to use CURL to make remote connection.

The steps are as follows :

1) Close WAMP (if running)
2) Navigate to WAMP\bin\php\(your version of php)\
3) edit php.ini
4) Search for curl, uncomment extension=php_curl.dll
5) Navigate to WAMP\bin\Apache\(your version of apache)\bin\
6) edit php.ini
7) Search for curl, uncomment extension=php_curl.dll
8 ) Save both
9) Restart WAMP

That will solve your Curl issues.
Enjoy!

Share

How to prevent XSS attacks through php?

There are a number of ways hackers put to use for XSS attacks, PHP’s built-in functions do not respond to all sorts of XSS attacks. Hence, functions such as strip_tags, filter_var, mysql_real_escape_string, htmlentities, htmlspecialchars, etc do not protect us 100%. You need a better mechanism, here is what is solution:

]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);

// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);

// Only works in IE: 
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);

// Remove namespaced elements (we do not need them)
$data = preg_replace('#]*+>#i', '', $data);

do
{
        // Remove really unwanted tags
        $old_data = $data;
        $data = preg_replace('#]*+>#i', '', $data);
}
while ($old_data !== $data);

// we are done...
return $data;
}
?>

Share

How to add www in url through .htaccess?

Recently I was working on a project and SEO team requested to add WWW forcefully in project URL. I asked why, they said.
“Must have www in your URL! Google Like it.”
So here is .htaccess snippet to force a url with WWW
When you will type http://phpmind.com it will automatically become http://www.phpmind.com

RewriteEngine on

rewritecond %{http_host} ^phpmind.com [nc]
rewriterule ^(.*)$ http://www.phpmind.com/$1 [r=301,nc]

This is how I did in this site. I am telling you one .htaccess secret. You can experience here only.

Share

How to add and disable ETags through .htaccess?

What is ETag?
An ETag, or entity tag, is part of HTTP and it provides a unique identifier for the resource being supplied.

This identifier can then be used to validate if it resource has been modified or
Browser requests can use an etag and an if-match header to check whether a resource has been modified since it was served, providing an efficient caching facility that relies on content rather than on timeouts.

Use this code to setup ETags on your server, using following htaccess.


FileETag MTime Size

  
       ExpiresActive on
       ExpiresDefault "access plus 1 year"
   



Sometimes developer want to be disable ETags from headers. To disable ETags, make sure to include following snippet in your .htaccess file.


Header unset ETag
FileETag None

Share

How to use .htaccess for permanent redirect 301?

If you are making search engine friendly URL from pages which are using query string (i.e. www.phpmind.com?id=2 ) and pages which are indexed in search engines or if you are rewriting your website with new urls then you need permanent redirect 301!!

Let me tell you what happens here. If you remove a page which is already in Google it will generate error and that is not good for your site.
So .htaccess for permanent redirect will save life! Just redirect old to new url and Google will like your site this is good practice in terms of SEO too.

This one line PHP code is worth to add in .htaccess file of your root directory without loosing search engine ranking in Google and Others.

Redirect 301 /oldPage.html http://mydomain.com/newpage.html

Another Way 

redirectpermanent /contact-me.html http://www.phpmind.com/contact-us.html

Share

How to prevent hot linking using .htaccess?

Don’t let your users your photo steel! If you have very good photo or even not good! and want to prevent your files using php technology, such as jpg, gif, bmp, png etc.

You can just put this code in root directory of .htaccess file of your php project and it won’t let others site use you files directly and it will save your bandwidth. This is the main purpose of blocking hotlinking using .htaccess in php.


RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?my-website-url\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|gif|bmp|png)$ http://phpmind.com/no-hotlinking-please.png [L]

Share

How to upload big file using .htaccess?

You can upload big file yes it is possible without applet and other third party lib!
Simply put these standard configuration values and they will overwrite php.ini setting, which does not let you upload big file in your server.

php_value upload_max_filesize 10M
php_value post_max_size 10M
php_value max_execution_time 300
php_value max_input_time 300

Share

How to force http to https through .htaccess?

In order to force https:// in payment and other secure pages even if your customer try to access http:// or they forget. You can use .htaccess file and simple code.

Example –
I had created a page http://www.phpmind.com/blog/
I want my visitor to access https://www.phpmind.com/blog/
Here is code which will force them to redirect to https://

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Share