website development company in jaipur

BUILD THE PERFECT WEBSITE WITH WEB DEVELOPMENT

When it comes to success in business, do you know how it happens? What does it take to stand out from the pack? These are questions that every business owner needs to be concerned with. One of the best answers anyone could give you is to take control of your online presence. Building a first class website for your business is one of the first and most important things you can do. This is the step you need to take in order to establish not only your presence on the web but also your unique identity. To reach this goal, it helps to hire a team of web experts.

When it’s Time to Launch Your Site, You Need to Do it Right

The first thing you need to know about launching a new site is that you need to get it as close as possible to perfect on your first try. Sure, there may still be some bugs in the system. You can iron all of them out later. But when it comes to making the crucial first impression on your public, you really need to concern yourself with putting your best foot forward. How can you do it? The answer is to hire a team of experts who can give your new business site the look and feel of a truly professional operation. This is why you need to hire Web Development to build your new website.

A Responsive Site is a Site That the Public Can Trust

There are many things that need to be taken account of when launching a new website. For example, you need to make sure that your site contains all of the latest modern e-commerce software. It also needs to be fully responsive. These are elements that the public will expect to see present on your site. Here at Web Development, we take great pride in supplying these vital features to each and every new site that we build for our clients. The more responsive and up to date that your site is, the more trust the public will place in it. A good looking site will become a profitable site.

The Time for You to Build the Perfect Website is Now

When it comes to succeeding in the world of business, there are many lessons that you will need to learn. You can make it much easier on yourself by learning a very important lesson straight off the bat. The bulk of your public will be using the world wide web to shop at your store and buy your goods. To reach them, you need a first class business website. Contact Web Development today to build the ultimate home for your business.

Best SEO Company In jaipur

MAXIMIZE YOUR LOCAL SEO PRESENCE WITH GD INFO SOLUTION

How present is your business in local Google searches? This is a major concern that you need to take seriously. The more often your business shows up in the search listings for your local area, the more exposure you will get. This naturally translates to a higher level of sales. You can take advantage of the local SEO services offered by GDINFO Solution to reach this important goal. All you need to do is let us know where you are located, what kind of business you are in, and we’ll take it from there. The stage will be set for your success.

You Need a High Level of Local Exposure to Succeed

When people punch in a search for “local hardware store in Jaipur”, yours is the one that needs to come up first in the listings. If you own a barber shop, yours is the one that should come up first for “Cristy barber shop.” This is the result of working hard to maximize your presence on the web. You need to be listed on sites such as Google My Business in order to make sure that as many people as possible know about your business. You can take advantage of sites like these in order to fully customize your content in order to reach the demographic that you want to appeal to.

The Sooner You Get SEO Optimized, the Better for Your Business

Our goal at GDINFO Solution is to help you optimize your SEO presence. This is the key to making sure that you get the highest possible level of exposure on the world wide web. This is the place where 3 out of 4 shoppers will turn to first in order to find out where to get the goods and services that they need. The higher your business is listed in the local search rankings, the better chance you will have of making the sale. We can show you how to rank as highly as possible.

Get in Touch with Us Today to Maximize Your Local SEO Success

The time for you to maximize your frequency in local search results is now. This is an outcome you need to obtain in order to guarantee your long term survival. GDINFO Solution can help you maximize your website and social media content for SEO purposes. The more exposure your business gets on the web, the more success you will have. This is an outcome that all of your rivals are working toward already. You can take a page from their book in order to get the same results. Get in touch with us today to learn more about what we can do to help your business grow and thrive.

IMPROVE YOUR SEO STRATEGY WITH PHP DEVELOPMENT

How many likes, clicks, and shares are your various social media pages getting? And just how visits do you average to your site per day? These are the basic questions that every business owner should be asking. If you aren’t getting the results you want, it may be time for a basic tune up. You can get answers to your questions along with some valuable aid and counsel by hiring an expert PHP Development team. We are here to give you the help you need to turn your page into a social media power player. All you need to do is get in touch with us today.

Your Audience is All About Social Media, So Why Aren’t You There?

Nine out of ten people prefer to use the world wide web as their online shopping center. This translates into hundreds of millions of people surfing the web on a daily basis. If you can manage to catch the attention of even a small fraction of this multitude, you’ll be doing very well indeed. So why aren’t you there? If you just don’t know where to begin, contact GD INFO SOLUTION today. We’ll cure your stage fright and show you how to crash the web with a whole new advertising strategy.

Do You Know the Best Ways to Improve Your Social Media Standing?

When it comes to increasing your profits, the first thing you need to know how to do is increase your exposure. Your direct rivals in the industry have already learned this valuable secret. This explains why you’re currently so far behind them in the rankings. What we can do for you is to help you increase your knowledge of all of the various SEO tactics and techniques. We can help you localize your audience so that you can get the maximum search engine result rankings for your business. And we can also help increase your global exposure so that you can gain a whole new audience.

Get in Touch With Us Today to Raise Your Social Media Exposure

Once you have a high profile on social media, you can begin to grow and expand your business all over the country and then the world. The secret is to learn how to target your chosen demographic with the sharpest possible focus. We can show you the magic SEO keywords and phrases that will reel in a whole new generation of long term loyal customers. It isn’t rocket science but it’s a technique that is well worth taking the time and effort to learn. Get in touch with GD INFO SOLUTION today and let us show you how the magic is made. This is your chance to hit the big time.

Most Popular PHP Frameworks

Most popular PHP Frameworks

Nowdays PHP is most favorable coding language among web developers and bloggers because of it is open source.PHP, known as the most popular server-side scripting language in the world, has evolved a lot since the first inline code snippets appeared in static HTML files. The reason behind popularity of PHP is its flexibility, database support, interactivity and plenty of frameworks.

What PHP frameworks do:

  • Make speed development possible
  • Provide well-organized, reusable and maintainable code
  • Frameworks Follow the MVC (Model-View-Controller) pattern that ensures the separation of presentation layer and logic
  • Follow object-oriented programming tools
  • Provide Security feature like (CSRF …)

1. Laravel (released in 2011),
2. Symfony
3. CodeIgniter (released in 2006
4. Yii 2
5. Phalcon (released in 2012)
6. CakePHP (released in 2005)
7. Zend Framework
8. Slim (PHP micro framework)
9. Aura
10. FuelPHP

How to check cURL is install or not on server in PHP

To check cURL we need to check PHP extension –
function _is_curl_installed() {
if  (in_array  (‘curl’, get_loaded_extensions())) {
return true;
}
else {
return false;
}
}

// Output text to user based on test
if (_is_curl_installed()) {
echo “cURL is <span style=\”color:blue\”>installed</span> on this server”;
} else {
echo “cURL is NOT <span style=\”color:red\”>installed</span> on this server”;
}
php mail send development

PHP script to send emails using gmail smtp

We can send emails through php mail() function from server but it is not guaranteed that emails will be delivered into inbox because that emails are not authenticated.

Authenticated emails are that emails which sent through a authenticated sender. Here, we will create a scrript to send authenticated emails. 

We will use gmail authentication details to send emails through SMTP. 

Step1: Install PHPMailer Library

In the first step, we will install and download PHPMailer library through the composer command. So open your terminal and run the following command.composer require phpmailer/phpmailer

Above composer command will download all the files of phpmailer with autoloader which will load all the classes.

Step 2: Write script to send email

Now, after downloading phpmailer library we will write a php script to send emails through gmail authentication using phpmailer library.

So, first thing to send emails from gmail smtp we will need to have a gmail account. If you do not have, please go to gmail.com and signup with a email id and password and these details will be need ed in sendmail.php which we are going to create.

Let’s create a file sendmail.php in the directory where phpmailer library has downloaded and put some code which will work for sending emails. Now sendmail.php file will look a like below.

sendmail.php

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
require_once "vendor/autoload.php";
require_once "constants.php";
 
$mail = new PHPMailer(true);
 
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';  //gmail SMTP server
    $mail->SMTPAuth = true;
    $mail->Username = GMAIL_USERNAME;   //username
    $mail->Password = GMAIL_PASSWORD;   //password
    
    // Sending mail through smtp secure(ssl/tls)
    $mail->SMTPSecure = 'ssl';  // Can also use 'tls' instead of 'ssl'
    $mail->Port = 465;   // SMTP port Should be 587 whien using 'tls'                  
  
    $mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
    $mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');
 
    // Add attachment
    $mail->addAttachment(__DIR__ . '/sample_file.txt');
    $mail->addAttachment(__DIR__ . '/sample_image.png');
    // isHTML true for sending html body content
    $mail->isHTML(true);
    $mail->Subject = 'Email Subject';
    $mail->Body    = '<b>Email Body</b>';
 
    $mail->send();
    echo 'Email has been sent';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: '. $mail->ErrorInfo;
}
?

Now, the script to send emails is ready to be used. It will use the gmail login details for gmail authentication. After putting correct authentication details, email may not work becuase of the gmail security reason.

You will need ‘Allow less secure app’ to set on like the screeenshot below-

After allowing less secure app your email will work like a charm.

Most Popular PHP Frameworks

How to Read Big Files with PHP (Without Killing Your Server)

It’s not often that we, as PHP developers, need to worry about memory management. The PHP engine does a stellar job of cleaning up after us, and the web server model of short-lived execution contexts means even the sloppiest code has no long-lasting effects.

There are rare times when we may need to step outside of this comfortable boundary — like when we’re trying to run Composer for a large project on the smallest VPS we can create, or when we need to read large files on an equally small server.

It’s the latter problem we’ll look at in this tutorial.

Measuring Success

The only way to be sure we’re making any improvement to our code is to measure a bad situation and then compare that measurement to another after we’ve applied our fix. In other words, unless we know how much a “solution” helps us (if at all), we can’t know if it really is a solution or not.

There are two metrics we can care about. The first is CPU usage. How fast or slow is the process we want to work on? The second is memory usage. How much memory does the script take to execute? These are often inversely proportional — meaning that we can offload memory usage at the cost of CPU usage, and vice versa.

In an asynchronous execution model (like with multi-process or multi-threaded PHP applications), both CPU and memory usage are important considerations. In traditional PHP architecture, these generally become a problem when either one reaches the limits of the server.

It’s impractical to measure CPU usage inside PHP. If that’s the area you want to focus on, consider using something like top, on Ubuntu or macOS. For Windows, consider using the Linux Subsystem, so you can use top in Ubuntu.

For the purposes of this tutorial, we’re going to measure memory usage. We’ll look at how much memory is used in “traditional” scripts. We’ll implement a couple of optimization strategies and measure those too. In the end, I want you to be able to make an educated choice.

The methods we’ll use to see how much memory is used are:

// formatBytes is taken from the php.net documentation

memory_get_peak_usage();

function formatBytes($bytes, $precision = 2) {
    $units = array("b", "kb", "mb", "gb", "tb");

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= (1 << (10 * $pow));

    return round($bytes, $precision) . " " . $units[$pow];
}

We’ll use these functions at the end of our scripts, so we can see which script uses the most memory at one time.

What Are Our Options?

There are many approaches we could take to read files efficiently. But there are also two likely scenarios in which we could use them. We could want to read and process data all at the same time, outputting the processed data or performing other actions based on what we read. We could also want to transform a stream of data without ever really needing access to the data.

Let’s imagine, for the first scenario, that we want to be able to read a file and create separate queued processing jobs every 10,000 lines. We’d need to keep at least 10,000 lines in memory, and pass them along to the queued job manager (whatever form that may take).

For the second scenario, let’s imagine we want to compress the contents of a particularly large API response. We don’t care what it says, but we need to make sure it’s backed up in a compressed form.

In both scenarios, we need to read large files. In the first, we need to know what the data is. In the second, we don’t care what the data is. Let’s explore these options…

Reading Files, Line By Line

There are many functions for working with files. Let’s combine a few into a naive file reader:

// from memory.php

function formatBytes($bytes, $precision = 2) {
    $units = array("b", "kb", "mb", "gb", "tb");

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= (1 << (10 * $pow));

    return round($bytes, $precision) . " " . $units[$pow];
}

print formatBytes(memory_get_peak_usage());
// from reading-files-line-by-line-1.php

function readTheFile($path) {
    $lines = [];
    $handle = fopen($path, "r");

    while(!feof($handle)) {
        $lines[] = trim(fgets($handle));
    }

    fclose($handle);
    return $lines;
}

readTheFile("shakespeare.txt");

require "memory.php";

We’re reading a text file containing the complete works of Shakespeare. The text file is about 5.5MB, and the peak memory usage is 12.8MB. Now, let’s use a generator to read each line:

// from reading-files-line-by-line-2.php

function readTheFile($path) {
    $handle = fopen($path, "r");

    while(!feof($handle)) {
        yield trim(fgets($handle));
    }

    fclose($handle);
}

readTheFile("shakespeare.txt");

require "memory.php";

The text file is the same size, but the peak memory usage is 393KB. This doesn’t mean anything until we do something with the data we’re reading. Perhaps we can split the document into chunks whenever we see two blank lines. Something like this:

// from reading-files-line-by-line-3.php

$iterator = readTheFile("shakespeare.txt");

$buffer = "";

foreach ($iterator as $iteration) {
    preg_match("/\n{3}/", $buffer, $matches);

    if (count($matches)) {
        print ".";
        $buffer = "";
    } else {
        $buffer .= $iteration . PHP_EOL;
    }
}

require "memory.php";

Any guesses how much memory we’re using now? Would it surprise you to know that, even though we split the text document up into 1,216 chunks, we still only use 459KB of memory? Given the nature of generators, the most memory we’ll use is that which we need to store the largest text chunk in an iteration. In this case, the largest chunk is 101,985 characters.

Generators have other uses, but this one is demonstrably good for performant reading of large files. If we need to work on the data, generators are probably the best way.

Piping Between Files

In situations where we don’t need to operate on the data, we can pass file data from one file to another. This is commonly called piping (presumably because we don’t see what’s inside a pipe except at each end … as long as it’s opaque, of course!). We can achieve this by using stream methods. Let’s first write a script to transfer from one file to another, so that we can measure the memory usage:

// from piping-files-1.php

file_put_contents(
    "piping-files-1.txt", file_get_contents("shakespeare.txt")
);

require "memory.php";

Unsurprisingly, this script uses slightly more memory to run than the text file it copies. That’s because it has to read (and keep) the file contents in memory until it has written to the new file. For small files, that may be okay. When we start to use bigger files, no so much…

Let’s try streaming (or piping) from one file to another:

// from piping-files-2.php

$handle1 = fopen("shakespeare.txt", "r");
$handle2 = fopen("piping-files-2.txt", "w");

stream_copy_to_stream($handle1, $handle2);

fclose($handle1);
fclose($handle2);

require "memory.php";

This code is slightly strange. We open handles to both files, the first in read mode and the second in write mode. Then we copy from the first into the second. We finish by closing both files again. It may surprise you to know that the memory used is 393KB.

That seems familiar. Isn’t that what the generator code used to store when reading each line? That’s because the second argument to fgets specifies how many bytes of each line to read (and defaults to -1 or until it reaches a new line).

The third argument to stream_copy_to_stream is exactly the same sort of parameter (with exactly the same default). stream_copy_to_stream is reading from one stream, one line at a time, and writing it to the other stream. It skips the part where the generator yields a value, since we don’t need to work with that value.

Piping this text isn’t useful to us, so let’s think of other examples which might be. Suppose we wanted to output an image from our CDN, as a sort of redirected application route. We could illustrate it with code resembling the following:

// from piping-files-3.php

file_put_contents(
    "piping-files-3.jpeg", file_get_contents(
        "https://github.com/assertchris/uploads/raw/master/rick.jpg"
    )
);

// ...or write this straight to stdout, if we don't need the memory info

require "memory.php";

Imagine an application route brought us to this code. But instead of serving up a file from the local file system, we want to get it from a CDN. We may substitute file_get_contents for something more elegant (like Guzzle), but under the hood it’s much the same.

The memory usage (for this image) is around 581KB. Now, how about we try to stream this instead?

// from piping-files-4.php

$handle1 = fopen(
    "https://github.com/assertchris/uploads/raw/master/rick.jpg", "r"
);

$handle2 = fopen(
    "piping-files-4.jpeg", "w"
);

// ...or write this straight to stdout, if we don't need the memory info

stream_copy_to_stream($handle1, $handle2);

fclose($handle1);
fclose($handle2);

require "memory.php";

The memory usage is slightly less (at 400KB), but the result is the same. If we didn’t need the memory information, we could just as well print to standard output. In fact, PHP provides a simple way to do this:

$handle1 = fopen(
    "https://github.com/assertchris/uploads/raw/master/rick.jpg", "r"
);

$handle2 = fopen(
    "php://stdout", "w"
);

stream_copy_to_stream($handle1, $handle2);

fclose($handle1);
fclose($handle2);

// require "memory.php";

Other Streams

There are a few other streams we could pipe and/or write to and/or read from:

  • php://stdin (read-only)
  • php://stderr (write-only, like php://stdout)
  • php://input (read-only) which gives us access to the raw request body
  • php://output (write-only) which lets us write to an output buffer
  • php://memory and php://temp (read-write) are places we can store data temporarily. The difference is that php://temp will store the data in the file system once it becomes large enough, while php://memory will keep storing in memory until that runs out.

Filters

There’s another trick we can use with streams called filters. They’re a kind of in-between step, providing a tiny bit of control over the stream data without exposing it to us. Imagine we wanted to compress our shakespeare.txt. We might use the Zip extension:

// from filters-1.php

$zip = new ZipArchive();
$filename = "filters-1.zip";

$zip->open($filename, ZipArchive::CREATE);
$zip->addFromString("shakespeare.txt", file_get_contents("shakespeare.txt"));
$zip->close();

require "memory.php";

This is a neat bit of code, but it clocks in at around 10.75MB. We can do better, with filters:

// from filters-2.php

$handle1 = fopen(
    "php://filter/zlib.deflate/resource=shakespeare.txt", "r"
);

$handle2 = fopen(
    "filters-2.deflated", "w"
);

stream_copy_to_stream($handle1, $handle2);

fclose($handle1);
fclose($handle2);

require "memory.php";

Here, we can see the php://filter/zlib.deflate filter, which reads and compresses the contents of a resource. We can then pipe this compressed data into another file. This only uses 896KB.

I know this is not the same format, or that there are upsides to making a zip archive. You have to wonder though: if you could choose the different format and save 12 times the memory, wouldn’t you?

To uncompress the data, we can run the deflated file back through another zlib filter:

// from filters-2.php

file_get_contents(
    "php://filter/zlib.inflate/resource=filters-2.deflated"
);

Customizing Streams

fopen and file_get_contents have their own set of default options, but these are completely customizable. To define them, we need to create a new stream context:

// from creating-contexts-1.php

$data = join("&", [
    "twitter=assertchris",
]);

$headers = join("\r\n", [
    "Content-type: application/x-www-form-urlencoded",
    "Content-length: " . strlen($data),
]);

$options = [
    "http" => [
        "method" => "POST",
        "header"=> $headers,
        "content" => $data,
    ],
];

$context = stream_content_create($options);

$handle = fopen("https://example.com/register", "r", false, $context);
$response = stream_get_contents($handle);

fclose($handle);

In this example, we’re trying to make a POST request to an API. The API endpoint is secure, but we still need to use the http context property (as is used for http and https). We set a few headers and open a file handle to the API. We can open the handle as read-only since the context takes care of the writing.

There are loads of things we can customize, so it’s best to check out the documentation if you want to know more.

Making Custom Protocols and Filters

Before we wrap things up, let’s talk about making custom protocols. If you look at the documentation, you can find an example class to implement:

Protocol {
    public resource $context;
    public __construct ( void )
    public __destruct ( void )
    public bool dir_closedir ( void )
    public bool dir_opendir ( string $path , int $options )
    public string dir_readdir ( void )
    public bool dir_rewinddir ( void )
    public bool mkdir ( string $path , int $mode , int $options )
    public bool rename ( string $path_from , string $path_to )
    public bool rmdir ( string $path , int $options )
    public resource stream_cast ( int $cast_as )
    public void stream_close ( void )
    public bool stream_eof ( void )
    public bool stream_flush ( void )
    public bool stream_lock ( int $operation )
    public bool stream_metadata ( string $path , int $option , mixed $value )
    public bool stream_open ( string $path , string $mode , int $options ,
        string &$opened_path )
    public string stream_read ( int $count )
    public bool stream_seek ( int $offset , int $whence = SEEK_SET )
    public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
    public array stream_stat ( void )
    public int stream_tell ( void )
    public bool stream_truncate ( int $new_size )
    public int stream_write ( string $data )
    public bool unlink ( string $path )
    public array url_stat ( string $path , int $flags )
}

We’re not going to implement one of these, since I think it is deserving of its own tutorial. There’s a lot of work that needs to be done. But once that work is done, we can register our stream wrapper quite easily:

if (in_array("highlight-names", stream_get_wrappers())) {
    stream_wrapper_unregister("highlight-names");
}

stream_wrapper_register("highlight-names", "HighlightNamesProtocol");

$highlighted = file_get_contents("highlight-names://story.txt");

Similarly, it’s also possible to create custom stream filters. The documentation has an example filter class:

Filter {
    public $filtername;
    public $params
    public int filter ( resource $in , resource $out , int &$consumed ,
        bool $closing )
    public void onClose ( void )
    public bool onCreate ( void )
}

This can be registered just as easily:

$handle = fopen("story.txt", "w+");
stream_filter_append($handle, "highlight-names", STREAM_FILTER_READ);

highlight-names needs to match the filtername property of the new filter class. It’s also possible to use custom filters in a php://filter/highligh-names/resource=story.txt string. It’s much easier to define filters than it is to define protocols. One reason for this is that protocols need to handle directory operations, whereas filters only need to handle each chunk of data.

If you have the gumption, I strongly encourage you to experiment with creating custom protocols and filters. If you can apply filters to stream_copy_to_stream operations, your applications are going to use next to no memory even when working with obscenely large files. Imagine writing a resize-image filter or and encrypt-for-application filter.

php mail send development

Your First PHP Code

A server-side language is similar to JavaScript in that it allows you to embed little programs (scripts) into the HTML code of a web page. When executed, these programs give you greater control over what appears in the browser window than HTML alone can provide. The key difference between JavaScript and PHP is the stage of loading the web page at which these embedded programs are executed.

Client-side languages like JavaScript are read and executed by the web browser after downloading the web page (embedded programs and all) from the web server. In contrast, server-side languages like PHP are run by the web server, before sending the web page to the browser. Whereas client-side languages give you control over how a page behaves once it’s displayed by the browser, server-side languages let you generate customized pages on the fly before they’re even sent to the browser.

Once the web server has executed the PHP code embedded in a web page, the result takes the place of the PHP code in the page. All the browser sees is standard HTML code when it receives the page, hence the name “server-side language.” Let’s look at simple example of some PHP that generates a random number between 1 and 10 and then displays it on the screen:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            <?php

            echo rand(1, 10);

            ?>
        </p>
    </body>
</html>
                  

Most of this is plain HTML. Only the line between <?php and ?> is PHP code. <?php marks the start of an embedded PHP script and ?> marks its end. The web server is asked to interpret everything between these two delimiters and convert it to regular HTML code before it sends the web page to the requesting browser. If you right-click inside your browser and choose View Source (the text may be different depending on the browser you’re using) you can see that the browser is presented with the following:


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Random Number</title>
    </head>
    <body>
        <p>Generating a random number between 1 and 10:
            5
        </p>
    </body>
</html>
            

Notice that all signs of the PHP code have disappeared. In its place the output of the script has appeared, and it looks just like standard HTML. This example demonstrates several advantages of server-side scripting …

  • No browser compatibility issues. PHP scripts are interpreted by the web server alone, so there’s no need to worry about whether the language features you’re using are supported by the visitor’s browser.
  • Access to server-side resources. In the example above, we placed a random number generated by the web server into the web page. If we had inserted the number using JavaScript, the number would be generated in the browser and someone could potentially amend the code to insert a specific number. Granted, there are more impressive examples of the exploitation of server-side resources, such as inserting content pulled out of a MySQL database.
  • Reduced load on the client. JavaScript can delay the display of a web page significantly (especially on mobile devices!) as the browser must run the script before it can display the web page. With server-side code, this burden is passed to the web server, which you can make as beefy as your application requires (and your wallet can afford).
  • Choice. When writing code that’s run in the browser, the browser has to understand how to run the code given to it. All modern browsers understand HTML, CSS and JavaScript. To write some code that’s run in the browser, you must use one of these languages. By running code on the server that generates HTML, you have a choice of many languages—one of which is PHP.

Basic Syntax and Statements

PHP syntax will be very familiar to anyone with an understanding of JavaScript, C, C++, C#, Objective-C, Java, Perl, or any other C-derived language. But if these languages are unfamiliar to you, or if you’re new to programming in general, there’s no need to worry about it.

A PHP script consists of a series of commands, or statements. Each statement is an instruction that must be followed by the web server before it can proceed to the next instruction. PHP statements, like those in the aforementioned languages, are always terminated by a semicolon (;).

This is a typical PHP statement:

echo 'This is a <strong>test</strong>!';
            

This is an echo statement, which is used to generate content (usually HTML code) to send to the browser. An echo statement simply takes the text it’s given and inserts it into the page’s HTML code at the position of the PHP script where it was contained.

In this case, we’ve supplied a string of text to be output: This is a <strong>test</strong>!. Notice that the string of text contains HTML tags (<strong> and </strong>), which is perfectly acceptable.

So, if we take this statement and put it into a complete web page, here’s the resulting code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test page</title>
    </head>
    <body>
        <p><?php echo 'This is a <strong>test</strong>!'; ?></p>
    </body>
</html>
                    

If you place this file on your web server and then request it using a web browser, your browser will receive this HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Test page</title>
    </head>
    <body>
        <p>This is a <strong>test</strong>!</p>
    </body>
</html>
            

The random.php example we looked at earlier contained a slightly more complex echo statement:


echo rand(1, 10);
            

You’ll notice that, in the first example, PHP is given some text to print directly, and in the second, PHP is given an instruction to follow. PHP tries to read anything that exists outside quotes as an instruction it must follow. Anything inside quotes is treated as a string, which means PHP doesn’t process it at all but just passes it to the command you called. So the following code will pass the string This is a <strong>test</strong>! directly to the echo command:


echo 'This is a <strong>test</strong>!';
            

A string is signified using a start quote and an end quote. PHP will see the first ' as the start of the string and find the next ' and use that as the end of the string.

In contrast, the following code will first run the built-in function rand to generate a random number and then pass the result to the echo command:


echo rand(1, 10);
            

🤷 If 35% of ALL websites are WordPress, is PHP really that dead?

Get ‘PHP & MySQL: Novice to Ninja, 6th Edition’ for free.Find out more

You can think of built-in functions as tasks that PHP knows how to do without you needing to spell out the details. PHP has many built-in functions that let you do everything, from sending email to working with information stored in various types of databases.

PHP won’t try to run anything that’s inside a string. The following code won’t have the result you may be expecting:


echo 'rand(1, 10)';
           

Instead of running the inbuilt function rand, PHP will see it as a string, and rather than printing out a random number, it will actually send the text rand(1, 10) to the browser, which probably isn’t what you wanted to do. It’s important to understand the difference between a string and code. PHP will see any text outside quotes as a series of commands it should follow. Anything inside quotes is a string and is data that PHP will work with.

PHP doesn’t try to understand strings. They can contain any characters in any order. But code—which is essentially a series of instructions—must follow a rigid structure for a computer to understand it.

When you invoke a function in PHP—that is, ask it to do its job—you’re said to be calling that function. Most functions return a value when they’re called; PHP then behaves as if you’d actually just typed that returned value in your code instead. In the echo 'rand(1, 10)'; example, our echo statement contains a call to the rand function, which returns a random number as a string of text. The echo statement then outputs the value returned by the function call.

Every function in PHP can have one or more arguments that allow you to make the function behave in a slightly different way. The rand function takes two arguments: the minimum random number and the maximum. By changing the values that are passed to the function, you’re able to change the way it works. For example, if you wanted a random number between 1 and 50, you could use the code:


echo rand(1, 50);
           

You may wonder why we need to surround the arguments with parentheses ((1, 50)). The parentheses serve two purposes. First, they indicate that rand is a function that you want to call. Second, they mark the beginning and end of a list of arguments—PHP statements that you wish to provide—in order to tell the function what you want it to do. In the case of the rand function, you need to provide a minimum and a maximum value. Those values are separated by a comma.

Later on, we’ll look at functions that take different kinds of arguments. We’ll also consider functions that take no arguments at all. These functions will still need the parentheses, even though there will be nothing to type between them.

How to Install PHP on Windows

We’ve previously shown you how to get a working local installation of Apache on your Windows PC. In this article, we’ll show how to install PHP 5 as an Apache 2.2 module.

Why PHP?

PHP remains the most widespread and popular server-side programming language on the web. It is installed by most web hosts, has a simple learning curve, close ties with the MySQL database, and an excellent collection of libraries to cut your development time. PHP may not be perfect, but it should certainly be considered for your next web application. Both Yahoo and Facebook use it with great success.

Why Install PHP Locally?

Installing PHP on your development PC allows you to safely create and test a web application without affecting the data or systems on your live website. This article describes PHP installation as a module within the Windows version of Apache 2.2. Mac and Linux users will probably have it installed already.

All-in-One packages

There are some excellent all-in-one Windows distributions that contain Apache, PHP, MySQL and other applications in a single installation file, e.g. XAMPP (including a Mac version), WampServer.

There is nothing wrong with using these packages, although manually installing Apache and PHP will help you learn more about the system and its configuration options.

The PHP Installer

Although an installer is available from php.net, I would recommend the manual installation if you already have a web server configured and running.

Manual Installation

Manual installation offers several benefits:

  • backing up, reinstalling, or moving the web server can be achieved in seconds (see 8 Tips for Surviving PC Failure) and
  • you have more control over PHP and Apache configuration.

Step 1: Download the files

Download the latest PHP 5 ZIP package from www.php.net/downloads.php

As always, virus scan the file and check its MD5 checksum using a tool such as fsum.

Step 2: Extract the files

We will install the PHP files to C:\php, so create that folder and extract the contents of the ZIP file into it.

PHP can be installed anywhere on your system, but you will need to change the paths referenced in the following steps.

Step 3: Configure php.ini

Copy C:\php\php.ini-development to C:\php\php.ini. There are several lines you will need to change in a text editor (use search to find the current setting). Where applicable, you will need to remove the leading semicolon to uncomment these setting.

Define the extension directory:

extension_dir = "C:/php/ext"

Enable extensions. This will depend on the libraries you want to use, but the following extensions should be suitable for the majority of applications:

extension=curl
extension=gd2
extension=mbstring
extension=mysql
extension=pdo_mysql
extension=xmlrpc

If you want to send emails using the PHP mail() function, enter the details of an SMTP server (your ISP’s server should be suitable):

[mail function]
; For Win32 only.
SMTP = mail.myisp.com
smtp_port = 25

; For Win32 only.
sendmail_from = my@emailaddress.com

Step 4: Add C:\php to the path environment variable

To ensure Windows can find PHP, you need to change the path environment variable. Open Settings, type ‘environment variables’ into the search field and open the result. Select the “Advanced” tab, and click the “Environment Variables” button.

Scroll down the System variables list and click on “Path” followed by the “Edit” button. Click “Edit text” and add ;C:\php to the end of the Variable value line (remember the semicolon).

PHP path environment variable

Now click OK until you’re out. You might need to reboot at this stage.

Step 5: Configure PHP as an Apache module

Ensure Apache is not running (use net stop Apache2.2 from the command line) and open its confhttpd.conf configuration file in an editor. The following lines should be changed:

On line 239, add index.php as a default file name:

DirectoryIndex index.php index.html

At the bottom of the file, add the following lines (change the PHP file locations if necessary):

# PHP5 module
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"

Save the configuration file and test it from the command line (Start > Run > cmd):

cd Apache2bin 
httpd -t

Step 6: Test a PHP file

Create a file named index.php in Apache’s web page root (either htdocs or D:WebPages) and add this code:

<?php phpinfo(); ?>

Ensure Apache has started successfully, open a web browser and enter the address http://localhost/. If all goes well, a “PHP version” page should appear showing all the configuration settings.