Ugly user info php. Global array $_SERVER in PHP

In the second lesson we will write two more classes and completely finish the internal part of the script.

Plan

The goal of this tutorial series is to create a simple application that allows users to register, log in, log out, and change settings. The class that will contain all the information about the user will be called User and it will be defined in the User.class.php file. The class that will be responsible for input/output will be called UserTools (UserTools.class.php).

A little about class naming

The proper etiquette is to name files that describe a class with the same name as the class itself. This makes it easy to determine the purpose of each file in the classes folder.

It is also common to add .class or .inc to the end of the class file name. This way we clearly define the purpose of the file and can use .htaccess to restrict access to these files.

User Class (User.class.php)

This class will define each user. With growth this application The definition of "User" may change significantly. Fortunately, OOP programming makes it easy to add additional user attributes.

Constructor

In this class we will use a constructor - this is a function that is automatically called when creating the next copy of the class. This allows us to automatically publish some attributes after the project is created. In this class, the constructor will take a single argument: associative array, which contains one row from the users table of our database.

require_once "DB.class.php"; class User ( public $id; public $username; public $hashedPassword; public $email;
public $joinDate;
//The constructor is called when a new object is created//Takes an associative array with the DB row as an argument. function __construct($data) ( $this->id = (isset($data["id"])) ? $data["id"] : ""; $this->username = (isset($data[" username"])) ? $data["username"] : ""; $this->hashedPassword = (isset($data["password"])) ? $data["password"] : ""; $this- >email = (isset($data["email"])) ? $data["email"] : ""; $this->joinDate = (isset($data["join_date"])) ? $data[" join_date"] : ""; )
public function save($isNewUser = false) ( //create a new database object. $db = new DB(); //if the user is already registered and we"re //just updating their info. if(!$isNewUser ) ( //set the data array $data = array("username" => ""$this->username"", "password" => ""$this->hashedPassword"",
"email" => ""$this->email"");
//update the row in the database $db->update($data, "users", "id = ".$this->id); )else ( //if the user is being registered for the first time. $data = array("username" => ""$this->username"", "password" => ""$this->hashedPassword"" , "email" => ""$this->email"", "join_date" => """.date("Y-m-d H:i:s",time())."""); $this-> id = $db->insert($data, "users"); $this->joinDate = time(); ) return true; ) ) ?>

Explanation

The first part of the code, outside the class zone, ensures that the class is connected to the database (since the User class has a function that requires this class).

Instead of variables of the “protected” class (used in the 1st lesson), we define them as “public”. This means that any code outside the class has access to these variables when working with the User object.

The constructor takes an array in which the columns in the table are keys. We define a class variable using $this->variablename. In the example of this class, we first check whether the value of a certain key exists. If yes, then we set the class variable to that value. Otherwise, the empty string. The code uses the short form of notation if:

$value = (3 == 4) ? "A" : "B";

In this example we are checking to see if 3 equals four! If yes - then $value = “A”, no - $value = “B”. In our example, the result is $value = “B”.

We save information about Users in the database

The save function is used to make changes to the database table with the current values ​​in the User object. This function uses the DB class we created in the first tutorial. Using class variables, the $data array is set. If user data is being saved for the first time, then $isNewUser is passed as $true (false by default). If $isNewUser = $true then the insert() function of the DB class is called. Otherwise, the update() function is called. In both cases, information from the user object will be saved in the database.

Class UserTools.class.php

This class will contain functions that are related to users: login(), logout(), checkUsernameExists() and get(). But with the expansion of this application, you can add many more.

//UserTools.class.php require_once "User.class.php"; require_once "DB.class.php";
class UserTools(
//Log the user in. First checks to see if the //username and password match a row in the database. //If it is successful, set the session variables //and store the user object within.
public function login($username, $password)
{
$hashedPassword = md5($password); $result = mysql_query("SELECT * FROM users WHERE username = "$username" AND password = "$hashedPassword""); if(mysql_num_rows($result) == 1) ( $_SESSION["user"] = serialize(new User(mysql_fetch_assoc($result))); $_SESSION["login_time"] = time(); $_SESSION["logged_in "] = 1; return true; )else( return false; ) )
//Log the user out. Destroy the session variables. public function logout() ( unset($_SESSION["user"]); unset($_SESSION["login_time"]); unset($_SESSION["logged_in"]); session_destroy(); ) //Check to see if a username exists. //This is called during registration to make sure all user names are unique. public function checkUsernameExists($username) ( $result = mysql_query("select id from users where username="$username""); if(mysql_num_rows($result) == 0) ( return false; )else( return true; )
}
//get a user //returns a User object. Takes the users id as an input public function get($id) ( $db = new DB(); $result = $db->select("users", "id = $id"); return new User($result ); ) )
?>

login() function

The login() function is clear by its name. It takes the user arguments $username and $password and checks that they match. If everything matches, creates a User object with all the information and saves it in the session. Please note that we are only using the PHP serialize() function. It creates a stored version of the object that can be easily unserialized using unserialize(). Also, the login time will be saved. This can be used later to provide users with information about the length of stay on the site.

You may also notice that we set $_SESSION["logged_in"] to 1. This allows us to easily check on each page whether the user is logged in. It is enough to check only this variable.

logout() function

Also a simple function. The PHP unset() function clears variables in memory, while session_destroy() will delete the session.

checkUsernameExists() function

Anyone who knows English will easily understand the function. It simply asks the database whether a similar login has been used or not.

get() function

This function takes the user's unique id and makes a query to the database using the DB class, namely the select() function. It will take an associative array with a number of user information and create a new User object, passing the array to the constructor.

Where can I use this? For example, if you create a page that needs to display specific user profiles, you will need to dynamically fetch this information. This is how you can do it: (let's say the URL is http://www.website.com/profile.php?userID=3)

//note: you will have to open up a database connection first. //see Part 1 for further information on doing so. //You"ll also have to make sure that you"ve included the class files.
$tools = new UserTools(); $user = $tools->get($_REQUEST["userID"]); echo "Username: ".$user->username.""; echo "Joined On: ".$user->joinDate."";

Easily! Is it true?

The final touch on the server side: global.inc.php

global.inc.php is required for every page on the site. Why? This way we will place all the usual operations that we will need on the page. For example, we will start session_start(). The database connection will also open.

require_once "classes/UserTools.class.php";
require_once "classes/DB.class.php";
//connect to the database $db = new DB(); $db->connect();
//initialize UserTools object $userTools = new UserTools(); //start the session
session_start();
//refresh session variables if logged in if(isset($_SESSION["logged_in"])) ( $user = unserialize($_SESSION["user"]); $_SESSION["user"] = serialize($userTools-> get($user->id)); ) ?>

What is he doing?

There are several things going on here. First of all, we open a connection to the database.

After connecting, we start the session_start() function. The function creates a session or continues the current one if the user is already logged in. Since our application is designed for users to log in/out, this feature is required on every page.

Next, we check whether the user is logged in. If so, we'll update $_SESSION["user"] to reflect the latest user information. For example, if a user changes his email, the old one will be stored in the session. But with auto update this will not happen.

This concludes the second part! Look out for the final lesson on this topic tomorrow.

All the best!

Those who have more or less seriously studied PHP know that there is one very useful global array in PHP which is called $_SERVER. And in this article I would like to analyze the most popular keys and their values ​​in this array, since knowledge of them is simply mandatory even for a beginner PHP programmer.

Before you start global array $_SERVER in PHP, I’ll give you a little hint right away. There is a great feature built into PHP, which is called phpinfo(). Let's immediately give an example of its use:

phpinfo();
?>

As a result of executing this simple script, you will see a huge table with various PHP interpreter settings, including, near the end there will be a table of values global array $_SERVER. It will list all the keys and all their corresponding values. How can this help you? And the fact is that if you need this or that value, and you forget what the key is called, then using the function phpinfo() You can always remember its name. In general, you will execute this script and you will immediately understand me.

Now let's move on to the most popular to the keys of the $_SERVER array:

  • HTTP_USER_AGENT- this key allows you to find out the client’s characteristics. In most cases, this is certainly the browser, however, not always. And again, if it’s a browser, then which one, you can find out about it in this variable.
  • HTTP_REFERER- contains the absolute path to that file ( PHP script, HTML page), from which we switched to this script. Roughly speaking, where the client came from.
  • SERVER_ADDR - IP address server.
  • REMOTE_ADDR - IP address client.
  • DOCUMENT_ROOT- physical path to the root directory of the site. This option is set via Apache server configuration file.
  • SCRIPT_FILENAME- physical path to the called script.
  • QUERY_STRING- a very useful value that allows you to get a string with a request, and then you can parse this string.
  • REQUEST_URI- an even more useful value that contains not only the request itself, but also the relative path to the called script from the root. This is very often used to remove duplication from index.php, that is, when we have such URL: "http://mysite.ru/index.php" And " http://mysite.ru/" lead to one page, and URLs different, hence duplication, which will have a bad effect on search engine optimization. And with the help REQUEST_URI we can determine: with index.php or not the script was called. And we can do a redirect with index.php(if he was present in REQUEST_URI) on without index.php. As a result, when sending such a request: " http://mysite.ru/index.php?id=5", we will have a redirect to URL: "http://mysite.ru/?id=5". That is, we got rid of duplication by removing from URL this index.php.
  • SCRIPT_NAME- relative path to the called script.

Perhaps these are all the elements global array $_SERVER in PHP that are used regularly. You need to know them and be able to use them when necessary.

$HTTP_SERVER_VARS [deleted]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_SERVER -- $HTTP_SERVER_VARS [deleted]Information about the server and execution environment

Description

The $_SERVER variable is an array containing information such as script headers, paths, and locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of them; the server may omit some of them or provide others not listed here. However, many of these variables are present in the » CGI/1.1 specification, so you can expect them to be implemented in your particular web server.

The $HTTP_SERVER_VARS variable contains the same initial information, but it is not superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables, so PHP treats them accordingly). Also note that "long arrays" were removed in PHP 5.4.0, so $HTTP_SERVER_VARS no longer exists.

Indexes

You may (or may not) find any of the following elements in the $_SERVER array. Note that few, if any, items will be available (or really make a difference) if PHP is running on the command line.

"PHP_SELF" The name of the script file that is currently running, relative to the document root. For example, $_SERVER["PHP_SELF"] in the script at http://example.com/foo/bar.php would be /foo/bar.php . The __FILE__ constant contains the full path and filename of the current (that is, connected) file. If PHP is running on the command line, this variable contains the name of the script, starting with PHP 4.3.0. Previously it was not available."argv" An array of arguments passed to the script. When the script is run on the command line, it gives C-like access to command line options. When called via the GET method, this array will contain the query string."argc" Contains the number of parameters passed to the script (if launched on the command line)."GATEWAY_INTERFACE" Contains the version of the CGI specification used by the server; For example" CGI/1.1". "SERVER_ADDR" IP address of the server on which the current script is running."SERVER_NAME" The name of the host on which the current script is running. If the script is running on a virtual host, this will contain the name defined for that virtual host."SERVER_SOFTWARE" The server identification string specified in the headers when a response to a request occurs."SERVER_PROTOCOL" The name and version of the information protocol through which the page was requested; For example " HTTP/1.0"; "REQUEST_METHOD" What method was used to request the page; For example " GET", "HEAD", "POST", "PUT".

Comment:

The PHP script exits after sending the headers (that is, after performing any output without buffering the output), if the request was made using the method HEAD.

"REQUEST_TIME" Timestamp of the start of the request. Available starting from PHP 5.1.0."REQUEST_TIME_FLOAT" Timestamp of the start of the request, accurate to microseconds. Available starting from PHP 5.4.0."QUERY_STRING" The query string, if any, that retrieved the page."DOCUMENT_ROOT" The document root directory in which the current script is executed is exactly the one specified in the server configuration file."HTTP_ACCEPT" Header content Accept: from the current request, if there is one." HTTP_ACCEPT_CHARSET " Header content Accept-Charset: from the current request, if there is one. For example: " iso-8859-1,*,utf-8". " HTTP_ACCEPT_ENCODING " Header content Accept-Encoding: gzip". " HTTP_ACCEPT_LANGUAGE " Header content Accept-Language: from the current request, if there is one. For example: " en". "HTTP_CONNECTION" Header content Connection: from the current request, if there is one. For example: " Keep-Alive". "HTTP_HOST" Header content Host: from the current request, if there is one."HTTP_REFERER" The address of the page (if any) that brought the user's browser to this page. This header is set by the user's web browser. Not all browsers install it and some allow you to change the contents of the HTTP_REFERER header as an additional feature. In a word, he really cannot be trusted." HTTP_USER_AGENT " Header content User-Agent: from the current request, if there is one. This line contains the browser that the user used to request this page. A typical example is the line: Mozilla/4.5 (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with the function get_browser() to adapt the output of your page to the capabilities of the user's browser"HTTPS" Accepts a non-empty value if the request was made via the HTTPS protocol.

Comment: Note that when using ISAPI with IIS the value will be off, if the request was not made via HTTPS.

"REMOTE_ADDR" The IP address from which the user is viewing the current page."REMOTE_HOST" The remote host from which the user is viewing the current page. Reverse DNS lookup is based on the value of the REMOTE_ADDR variable.

Comment: Your web server must be configured to create this variable. For example, in Apache you need the presence of the directive HostnameLookups On in the httpd.conf file so that this variable is created. see also gethostbyaddr().

"REMOTE_PORT" The port on the remote machine that is used to communicate with the web server."REMOTE_USER" Authenticated user."REDIRECT_REMOTE_USER" The authenticated user if the request was redirected internally."SCRIPT_FILENAME"

The absolute path to the script that is currently executing.

Comment:

If the script is run on the command line (CLI) using a relative path such as file.php or ../file.php , the $_SERVER["SCRIPT_FILENAME"] variable will contain the relative path specified by the user.

"SERVER_ADMIN" This variable gets its value (for Apache) from a directive in the server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host."SERVER_PORT" The port on the server computer that the web server uses to connect. For default settings, the value will be " 80 "; using SLL, for example, this value will be as configured for secure HTTP connections.

Comment: To get a physical (real) port in Apache 2, you need to install UseCanonicalName = On And UseCanonicalPhysicalPort = On, otherwise this value may be replaced and not return the real value of the physical port. Relying on this value is unsafe in the context of applications that require enhanced security.

"SERVER_SIGNATURE" A string containing the server version and virtual host name that is added to server-generated pages if enabled."PATH_TRANSLATED" Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Comment: As of PHP 4.3.2, the PATH_TRANSLATED variable is no longer set implicitly in the Apache 2 SAPI, compared to Apache version 1 where it was set to the same value as the SCRIPT_FILENAME variable when not in use by Apache. This change was made to comply with the CGI specification, where the PATH_TRANSLATED variable should only exist when PATH_INFO is defined. Apache 2 users can use the directive AcceptPathInfo = On in the httpd.conf configuration file to set the PATH_INFO variable.

"SCRIPT_NAME" Contains the path to the currently executing script. This is useful for pages that need to point to themselves. The __FILE__ constant contains the full path and name of the current (i.e. included) file."REQUEST_URI" The URI that was passed in order to access this page. For example, " /index.html". "PHP_AUTH_DIGEST" When performing HTTP Digest authentication, this variable is assigned the "Authorization" header, which is sent by the client (this must then be used for appropriate validation)."PHP_AUTH_USER" When HTTP authentication is performed, this variable is set to the username provided by the user."PHP_AUTH_PW" When HTTP authentication is performed, this variable is set to the password provided by the user."AUTH_TYPE" When HTTP authentication is performed, this variable is set to the authentication type that is being used."PATH_INFO" Contains any user-supplied path contained after the script name but before the query string, if available. For example, if the current script is requested by the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar , then the $_SERVER["PATH_INFO"] variable will contain /some/stuff?>

The result of running this example will be something like this.

Computer