Beginning PHP

Started by Vinil, 09-06-2011, 23:18:26

Previous topic - Next topic

VinilTopic starter

I am new to php.I just know C programming language .How to begin with php?How to build web pages in php ?  :-\


megazord100

Learn basic php on http://www.w3schools.com

Then learn to use open source php framework.
It's a quickest way. You have knowledge in C so that it's not difficult to learn a new language.
  •  


VinilTopic starter

thanks for the help but its the syntax difference in php so its easy to learn it but suggest some framework to practice

thelazytrader

#3
Shifting from C to PHP shouldn't be very difficult as both are procedural languages. PHP also supports object-oriented programming, which can be a new concept for you to explore if you're only familiar with C.

Let's start with understanding some basics about PHP:

About PHP: PHP stands for Hypertext Preprocessor and it's a server-side scripting language. That means PHP is a programming language for making dynamic and interactive Web pages. PHP scripts are executed on the server and result is sent to the browser as plain HTML.

Setting up your environment: First, you'll need to set up a server environment to run your PHP scripts. If you're using a Windows machine, you can use WAMP (Windows, Apache, MySQL, PHP). For MacOS, MAMP (Mac, Apache, MySQL, PHP) can be used. For Linux, LAMP (Linux Apache MySQL PHP) is an option. These all are free packages containing Apache server, MySQL, and PHP in a single installation.

Steps for building a web page in PHP:

HTML Structure: PHP can be embedded inside HTML and this means you can build a webpage as you would normally do using HTML, but incorporate PHP code as well. You could start your PHP file (index.php) with a basic HTML format:
<!DOCTYPE html>
<html>
<head>
  <title>My first PHP page</title>
</head>
<body>

</body>
</html>
Inserting PHP code: You can insert PHP code anywhere in the document. To do this you'll need to place your PHP code inside the PHP tags. The most common tag is <?php ... ?>. Every PHP line ends with a semicolon (;), just like in C. Let's insert some PHP code in our HTML:
<!DOCTYPE html>
<html>
<head>
  <title>My first PHP page</title>
</head>
<body>
  <?php
    echo "Hello, world!";
  ?>
</body>
</html>
The echo keyword is used to output data to the web page. In this case, it will print "Hello, world!".

Running your PHP file: Save your PHP file with a .php extension (for example, index.php) in your server's root directory (this is www or htdocs folder in the WAMP or MAMP installation). Now, open your favourite web browser and type localhost/index.php in the address bar. You should see "Hello, world!" printed on your page.
From here on, you can start learning more about PHP variables, control structures (if, else, while, for, etc.), GET and POST data, sessions, cookies, functions, working with a database like MySQL, and object-oriented programming in PHP. Websites like W3Schools, PHP.net (official PHP documentation) and tutorials on YouTube, Udemy or Coursera could be good resources to learn more.

Remember, developing in PHP means you'll also need to know some HTML, CSS and likely JavaScript for frontend work as PHP is a server-side language. It would be beneficial if you learn these languages alongside PHP to develop complete web applications.


Let's delve deeper into some elemental PHP concepts.

Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable. There's no need to declare the data type of a variable, unlike in C.

<?php
$name = "John";
$age = 25;
?>
Arrays

PHP allows for both indexed and associative arrays:

<?php
// An indexed array
$fruits = array("Apple", "Banana", "Cherry");

// An associative array
$person = array("Name" => "John", "Age" => 25);
?>
Control Structures

PHP includes many control structures you'd be familiar with from C - including if, else, while, and for:

<?php
$age = 20;

if ($age > 18) {
    echo "Adult";
} else {
    echo "Minor";
}
?>
Functions

You can define a function by using the function keyword. Here we have a function that multiplies two numbers:

<?php
function multiply($num1, $num2) {
    return $num1 * $num2;
}

echo multiply(5, 3);  // Outputs: 15
?>
Including PHP Files

You can include the content of one PHP file into another, using include or require.

<?php
include 'header.php';  // 'header.php' includes code for the header part of the webpage.
?>
Form Handling

PHP can be used to collect form data. For instance, if you have an HTML form:

<form method="post" action="welcome.php">
  Name: <input type="text" name="name"><br>
  Email: <input type="text" name="email"><br>
  <input type="submit">
</form>
The form data can be collected in the 'welcome.php' file:

<?php
echo "Welcome " . $_POST["name"] . "!";
echo "Your email is " . $_POST["email"] . ".";
?>
$_POST is a global PHP array which holds the data from a form using method "post". Similarly, $_GET holds the data from a form using method "get".

Sessions and Cookies

Sessions and cookies are used to store and pass information from one application page to another. Sessions are stored on the server, while cookies are stored in the user's browser.

Database Connectivity

PHP has functions that allow you to connect to a database like MySQL and manipulate it:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>
I recommend you to regularly use the official PHP documentation here to learn in-depth on any specific function or feature you want to implement.

Starting with basic web pages, slowly try to build some simple projects - like a contact form or a login system. After understanding the basics, move to building applications like a small blogging system or a basic e-commerce site using PHP. This would require understanding more advanced concepts like classes, objects, exceptions, namespaces.


One important aspect that is worth exploring in any server-side language, like PHP, is Object-Oriented Programming (OOP). This allows you to think of variables and functions in terms of objects and can be more efficient and easier to manage in many scenarios.

Here's a basic guide on what Object-Oriented Programming looks like in PHP.

Classes and Objects

A class can be thought of as a blueprint for creating objects (a particular data structure), providing initial values for the state of an object. It is a basic concept of OOP. An object is an instance of a class:

<?php
class Car {
    // Properties
    public $color;

    // Methods
    public function setColor($color) {
        $this->color = $color;
    }

    public function getColor() {
        return $this->color;
    }
}

$car = new Car(); // Create a new car object
$car->setColor("Red"); // Call the method setColor of object car
echo $car->getColor(); // Print the color of car
?>
In the above example, Car is a class and $car is an instance (object) of this class. The Car class has a $color property and two methods which get and set the car's color.

Constructor

A constructor is a special function within a class that is automatically called when you create a new instance of that class. It's commonly used to automatically do some initialization, like setting up properties:

<?php
class Car {
    function __construct() {
        echo 'A new car object has been made!';
    }
}

$car = new Car();
?>
Inheritance

In OOP, inheritance allows us to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.

<?php
class Vehicle {
    public $wheels = 4;
}

class Car extends Vehicle {
    public $doors = 4;
}

$car = new Car();
echo $car->wheels; // Car inherited the $wheels property from Vehicle
echo $car->doors;
?>
Visibility

Visibility refers to how we encapsulate the properties of our classes. In PHP, we use three keywords to set the visibility: public, protected, private.

public : Any code can access this property or method.
protected: Only the current class and classes that inherit from the current class can access this property or method.
private: Only the current class can access this property or method.
These are the basics of OOP in PHP and just represent the surface of what you can do with this powerful feature. Keep in mind that for small scripts, traditional procedural coding can be fine but for larger applications, using an OOP approach can make the code more organized, reusable, and easier to maintain. It's recommended to learn both styles to be a well-rounded developer.

Along with this, you might want to also familiarise yourself with PHP's extensive built-in functions for handling arrays, strings, regular expressions, files, including other PHP scripts and interacting with databases. PHP also has powerful features for error and exception handling, and tools for securing your scripts from common security vulnerabilities like SQL injection attacks or Cross-Site scripting (XSS).


I can cover a few more advanced topics, including exceptions and error handling, namespaces, and how to work with JSON data in PHP.

Exceptions and Error Handling

PHP 5 introduced the concept of exception handling. When an exception is thrown, the code following it will not be executed, and PHP will attempt to find the first matching catch block. Here's a sample:

<?php
function checkNum($number) {
   if ($number > 1) {
      throw new Exception("Value must be 1 or below");
   }
   return true;
}

try {
   checkNum(2);
   echo 'If you see this, the number is 1 or below';
}

catch(Exception $e) {
   echo 'Message: ' .$e->getMessage();
}
?>
In the above code, when checkNum() function is called within try block with arg as 2, it throws an exception because 2 is greater than 1. And the message inside exception is caught and displayed.

Namespaces

As the size of your PHP code becomes larger, naming everything uniquely becomes difficult. Namespaces solve this problem. A namespace is a way of encapsulating items to avoid name collision.

<?php
namespace MyProject {
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
}

namespace AnotherProject {
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
}
?>
You could use it like so:

<?php
require('vendor/autoload.php');

use MyProject\Connection as MyProjConnection;
use AnotherProject\Connection as AnotherProjConnection;

$conn = new MyProjConnection();
$anotherConn = new AnotherProjConnection();
?>
Working with JSON

PHP supports JSON natively and provides functions to encode and decode JSON data. Here's an example usage:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // object(stdClass)#1 (5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }
?>
Regular Expressions

PHP supports regular expressions using functions from the PCRE (Perl Compatible Regular Expressions) library, or using the POSIX extended family of functions. Regular expressions are a powerful language for matching patterns within strings. Here's an example usage:

<?php
$regex = "/^([a-zA-Z]{3})\s*([0-9]{3})$/";
$test_string = "abc 123";
if (preg_match($regex, $test_string, $matches)) {
    echo $matches[1]; // 'abc'
    echo $matches[2]; // '123'
}
?>
These are some more advanced areas within PHP. If you are familiar with them, you can build more robust and complex applications. It would be good to work on some projects to practice these concepts, try to read and understand the source code of open-source projects or contribute to them. Remember, continuous learning and practicing is the key to become a proficient programmer.


Here are a few resources I recommend if you're eager to learn more about PHP:

Online Documentation and Tutorials

PHP Official Documentation - The official PHP manual is comprehensive and always up-to-date.
W3Schools - W3Schools has tutorials for beginners and covers many topics in PHP.
PHP The Right Way - An easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative tutorials.
Online Courses

Codecademy – Codecademy's interactive PHP course is beginner-friendly and engaging.
Udemy – Udemy has a wide range of PHP courses, from beginner to advanced levels. Make sure to check the reviews before purchasing a course.
Coursera - Coursera offers many courses on PHP from renowned universities and organizations.
Books

PHP and MySQL Web Development (5th Edition) by Luke Welling and Laura Thomson - This book is a comprehensive guide to developing dynamic websites using PHP and MySQL.
Modern PHP: New Features and Good Practices by Josh Lockhart - The book presents new features of PHP along with better practices.
Learning PHP, MySQL & JavaScript: With jQuery, CSS & HTML5 by Robin Nixon - A useful resource for learning PHP along with MySQL, JavaScript, jQuery, and HTML5.
Forums

Stack Overflow - A popular developer community where you can ask questions and find answers to PHP related queries.
PHP Builder - A forum specifically dedicated to PHP.
Blogs

PHPDeveloper.org - A blog aggregator that brings in posts from PHP blogs from around the web.
SitePoint - SitePoint PHP blog has many tutorials and articles on PHP topics.
Remember, different resources can suit different learning styles, so you may need to experiment to see what works best for you. Furthermore, while learning, it's important to have a project or a problem that you're aiming to solve. This helps to apply and consolidate your learning. Happy studying!

masterharvest

start learning HTML for the website structure. also CSS for the design, or you could study that tutorial at w3schools.com that is where i have learned that. :) PHP should be learned after html, since it gives function to the GUI.:)


celestia

You can start with the tutorials and w3schools site to get full idea of the PHP language, Lynda can play a good role in the learning also.
newbielink:https://ntestechnologies.com/web-development.html [nonactive]
  •  

Luca tall

Many online tutorials are helpful to learn PHP like w3schools and PHP.net.Apart from that get some guidens from PHP developers who are actively participated in forum.
Thanks for sharing.

johncruz

I will suggest you to first learn about PHP basic concepts. Many online tutorials will help you to learn about this.
  •