PHP – File Uploading ”; Previous Next One of the common features required in a typical PHP web application is the provision of letting the user upload files. Uploading files from a client is very easy in PHP. In this chapter, we shall learn how to use PHP script for the file upload process. The process of uploading a file follows these steps − The user opens the page containing a HTML form featuring a text files, a browse button and a submit button. The user clicks the browse button and selects a file to upload from the local PC. The full path to the selected file appears in the text filed then the user clicks the submit button. The selected file is sent to the temporary directory on the server. The PHP script that was specified as the form handler in the form”s action attribute checks that the file has arrived and then copies the file into an intended directory. The PHP script confirms the success to the user. In order to perform this activity, we must first ensure that configuration settings related to file upload are enabled in “php.ini”. Open the “php.ini” file and ensure that the following settings are enabled by removing the leading semicolon (;) symbol in file_uploads, upload_tmp_dir, upload_max_filesize and max_file_uploads parameters − ;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ; Whether to allow HTTP file uploads. ; http://php.net/file-uploads file_uploads=On ; Temporary directory for HTTP uploaded files (will use system ; default if not specified). ; http://php.net/upload-tmp-dir upload_tmp_dir=”C:xampptmp” ; Maximum allowed size for uploaded files. ; http://php.net/upload-max-filesize upload_max_filesize=40M ; Maximum number of files that can be uploaded via a single request max_file_uploads=20 It is necessary that the folders for both temporary and final locations have permissions set that enable file writing. If either is set to be read-only then process will fail. Creating a File Upload Form Next, we need to design a HTML form for file upload. The form’s method attribute must be POST and enctype must be multipart/form-data. Use the input type as file to let the user browse and select the file to be uploaded. <h2>File Upload Form</h2> <form method = “POST” action = “uploadfile.php” enctype=”multipart/form-data”> <label for=”file”>File name:</label> <input type=”file” name=”uploadfile” /> <input type=”submit” name=”submit” value=”Upload” /> </form> Creating an Upload Script The uploadfile.php script receives the uploaded file. The file data is collected in a suparglobal variable $_FILES. Fetch the name, file type, size and the tmp_name attributes of the uploaded file. The move_uploaded_file() function copies the selected file to the document folder. <?php echo “<b>File to be uploaded: </b>” . $_FILES[“uploadfile”][“name”] . “<br>”; echo “<b>Type: </b>” . $_FILES[“uploadfile”][“type”] . “<br>”; echo “<b>File Size: </b>” . $_FILES[“uploadfile”][“size”]/1024 . “<br>”; echo “<b>Store in: </b>” . $_FILES[“uploadfile”][“tmp_name”] . “<br>”; if (file_exists($_FILES[“uploadfile”][“name”])){ echo “<h3>The file already exists</h3>”; } else { move_uploaded_file($_FILES[“uploadfile”][“tmp_name”], $_FILES[“uploadfile”][“name”]); echo “<h3>File Successfully Uploaded</h3>”; } ?> Assuming that both the files myform.php and uploadfile.php are stored in the document folder. Open “myform.php” in the browser (http://localhost/myform.php) − Click the File button, browse to the desired file to be uploaded, and click the Upload button. The server responds with the following message − Print Page Previous Next Advertisements ”;
Category: php
PHP – Web Concepts
PHP – Web Concepts ”; Previous Next PHP is a server-side scripting language that is used to create dynamic webpages. It is one of the most popular programming languages for web development. This chapter aims to let you get familiarized with certain important concepts of web application development using PHP. A web-based application is a collection of webpages. A webpage is mainly created with HTML tags. HTML consists of different HTML tags which are required to define the appearance of page elements like text, image, table, etc. Hence, HTML essentially creates a static webpage. A Web application is hosted on a HTTP server with PHP module installed. The browser acts as a http client, to establish communication with the server, following HTTP protocol. How to Add Dynamic Content on a Webpage? To add dynamic content io a webpage, there are two possibilities. JavaScript is a client-side scripting language, that can access the HTML document object model and render dynamic content on the client browser. JavaScript code can be embedded in HTML page. The browser may collect data from the user in the form of HTML form elements and send it to a HTTP server for processing. PHP is a widely used Server-side processing language. PHP script can also be embedded inside HTML page. Example In the following script, JavaScript code embedded in HTML renders the current date as per the client browser, and the PHP code displays the current date as per the server, where this script is hosted. <!DOCTYPE html> <html> <body> <script type=”text/JavaScript”> document.write(“Client”s date :”+Date()+”n”); </script> <?php date_default_timezone_set(“Asia/Calcutta”); echo “server”s date is ” . date(“Y-m-d”) . “n”; echo “The time is ” . date(“h:i:sa”); ?> </body> </html> PHP can intercept and process the data from HTML forms. This allows you to collect information from your users. The next chapter discusses PHP’s form handling. PHP can be used to interact with databases such as MySQL and PostgreSQL. This allows you to store and retrieve data from your database, and dynamically populate the web pages or to power the web applications. PHP includes mysql, mysqli and PDO extensions for database handling. PHP can handle the data received from the client with HTTP GET as well as POST methods. We shall discuss in detail, how PHP handles GET/POST methods in one of the latter chapters. HTTP is a stateless protocol. However, it allows Sessions and cookies to be maintained on server and client respectively. PHP can be used to create and manage sessions and cookies. Sessions allow you to track individual users as they navigate your website, while cookies allow you to store information on the user”s computer for later use. In of the subsequent chapters, we shall learn how PHP handles sessions and cookies. PHP can be used to upload files to your web server. This allows you to create web applications that allow users to upload files, such as images, videos, or documents. You can use PHP to create a login page for your website. When the user enters their username and password, PHP can check the database to see if the user is valid. If the user is valid, PHP can log the user in and redirect them to the main page of your website. Identifying Browser & Platform PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment. One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user”s browser and operating system. PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser. Example Following example demonstrates how you can identify a client browser and operating system. NOTE − The function preg_match()is discussed in PHP Regular expression session. <?php function getBrowser() { $u_agent = $_SERVER[”HTTP_USER_AGENT”]; $bname = ”Unknown”; $platform = ”Unknown”; $version = “”; //First get the platform if (preg_match(”/linux/i”, $u_agent)) { $platform = ”linux”; } elseif (preg_match(”/macintosh|mac os x/i”, $u_agent)) { $platform = ”mac”; } elseif (preg_match(”/windows|win32/i”, $u_agent)) { $platform = ”windows”; } // Next get the name of the useragent yes seperately and for good reason if(preg_match(”/MSIE/i”,$u_agent) && !preg_match(”/Opera/i”,$u_agent)) { $bname = ”Internet Explorer”; $ub = “MSIE”; } elseif(preg_match(”/Firefox/i”,$u_agent)) { $bname = ”Mozilla Firefox”; $ub = “Firefox”; } elseif(preg_match(”/Chrome/i”,$u_agent)) { $bname = ”Google Chrome”; $ub = “Chrome”; } elseif(preg_match(”/Safari/i”,$u_agent)) { $bname = ”Apple Safari”; $ub = “Safari”; } elseif(preg_match(”/Opera/i”,$u_agent)) { $bname = ”Opera”; $ub = “Opera”; } elseif(preg_match(”/Netscape/i”,$u_agent)) { $bname = ”Netscape”; $ub = “Netscape”; } // finally get the correct version number $known = array(”Version”, $ub, ”other”); $pattern = ”#(?<browser>” . join(”|”, $known) . ”) [/ ]+(?<version>[0-9.|a-zA-Z.]*)#”; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches[”browser”]); if ($i != 1) { //we will have two since we are not using ”other” argument yet //see if version is before or after the name if (strripos($u_agent,”Version”) < strripos($u_agent,$ub)){ $version= $matches[”version”][0]; } else { $version= $matches[”version”][1]; } } else { $version= $matches[”version”][0]; } // check if we have a number if ($version == null || $version == “”) {$version = “?”;} return array( ”userAgent” => $u_agent, ”name” => $bname, ”version” => $version, ”platform” => $platform, ”pattern” => $pattern ); } // now try it $ua = getBrowser(); $yourbrowser = “Your browser: ” . $ua[”name”] . ” ” . $ua[”version”] . ” on ” .$ua[”platform”] . ” reports: <br >” . $ua[”userAgent”]; print_r($yourbrowser); ?> This is producing following result on my machine. This result may be different for your computer depending on what you are using. It will produce the following result − Your browser: Google
PHP – Cookies
PHP – Cookies ”; Previous Next The worldwide web is powered by HTTP protocol, which is a stateless protocol. The mechanism of Cookies helps the server maintain the information of previous requests. PHP transparently supports HTTP cookies. When a client first sends its request, the server includes a small piece of data along with its response as cookies. PHP provides the setcookie() method to inject cookies in the response. This cookie data is stored in the client’s machine as text files. On subsequent visits of the same client, these cookies are included as a part of the request header. The server populates the PHP superglobal variable “$_COOKIE” with all the cookies present in the client request. This chapter will teach you how to set cookies, how to access them and how to delete them. The Anatomy of a Cookie Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this − HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date. If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser”s headers might look something like this − GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”]. How to Set a Cookie in PHP? PHP contains the setcookie function to create a cookie object to be sent to the client along with HTTP response. setcookie(name, value, expire, path, domain, security); Parameters Here is the detail of all the arguments − Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies. Value − This sets the value of the named variable and is the content that you actually want to store. Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed. Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories. Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them. Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP. Example The PHP script give below checks if the cookie named username is already set, and retrieves its value, if so. If not, a new cookie username is set. <?php if (isset($_COOKIE[”username”])) { echo “<h2>Cookie username already set:” . $_COOKIE[”username”] . “</h2>”; } else { setcookie(“username”, “MohanKumar”); echo “<h2>Cookie username is now set</h2>”; } ?> Run this script from the document root of the Apache server. You should see this message − Cookie username is now set If this script is re-executed, the cookie is now already set. Cookie username already set: MohanKumar Your browser’s developer tool is a very useful facility. You can set, retrieve and delete cookies with its help. The cookie set by the above program can be viewed under the Application tab of the browser’s developer tools. A foreach loop as below retrieves all the cookies − <?php $arr=$_COOKIE; foreach ($arr as $key=>$val); echo “<h2>$key=>$val </h2>”; ?> The following script contains an HTML form. It sends the form data to setcookie.php script, that sets the cookies with the use of data retrieved from the $_POST array. The HTML form is rendered by the following code − <form action=”setcookie.php” method=”POST”> <input type=”text” name=”name”> <input type=”text” name=”age”> <input type=”submit” name=”Submit”> </form> SetCookie.php reads the form data and sets the cookies. if (isset($_POST[“submit”]) { setcookie(“name”, $_POST[“name”]); setcookie(“age”, $_POST[“age”]); } With another getcookie.php code, we can retrieve the cookies set. if (isset($_COOKIE[“name”]) echo “Cookie: name => ” . $_COOKIE[“name”]. “<br>”; if (isset($_COOKIE[“age”]) echo “Cookie: age => ” . $_COOKIE[“age”]. “<br>”; Accessing Cookies with PHP PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. <?php echo $_COOKIE[“name”]. “<br />”; /* is equivalent to */ echo $HTTP_COOKIE_VARS[“name”]. “<br />”; echo $_COOKIE[“age”] . “<br />”; /* is equivalent to */ echo $HTTP_COOKIE_VARS[“age”] . “<br />”; ?> You can use isset() function to check if a cookie is set or not. <?php if( isset($_COOKIE[“name”])) echo “Welcome ” . $_COOKIE[“name”] . “<br />”; else echo “Sorry… Not recognized” . “<br
PHP – Complete Form
PHP – Complete Form ”; Previous Next This chapter puts all the concepts of form validation and extraction of HTML form data into PHP code. The complete form handling code given below has three sections: A PHP code section in the beginning that looks for any validation errors when the form is submitted, the HTML form with various elements such as text fields, radio buttons, Select control, checkbox, etc. The third part is again a PHP code that renders the data entered by the user. PHP Error Tracking The code that traps errors, is in the beginning of the entire script. Obviously, this will be executed every time the page is loaded. If it’s being loaded after the form is submitted, the following segment checks whether each element is empty, the email field is well-formed, and the checkbox is clicked (indicating that the user agrees to the terms). <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = “”; $name = $email = $gender = $class = $course = $subject = “”; if ($_SERVER[“REQUEST_METHOD”] == “POST”) { if (empty($_POST[“name”])) { $nameErr = “Name is required”; } else { $name = test_input($_POST[“name”]); } if (empty($_POST[“email”])) { $emailErr = “Email is required”; } else { $email = test_input($_POST[“email”]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = “Invalid email format”; } } if (empty($_POST[“course”])) { $course = “”; } else { $course = test_input($_POST[“course”]); } if (empty($_POST[“class”])) { $class = “”; } else { $class = test_input($_POST[“class”]); } if (empty($_POST[“gender”])) { $genderErr = “Gender is required”; } else { $gender = test_input($_POST[“gender”]); } if (empty($_POST[“subject”])) { $subjectErr = “You must select one or more subjects”; } else { $subject = $_POST[“subject”]; } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> HTML Form The HTML script that renders an entry form, follows the error trapping code. Various for elements have been employed in the form design. <h2>Absolute Classes Registration Form</h2> <p><span class = “error”>* required field.</span></p> <form method = “POST” action = “<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”> <table> <tr> <td>Name:</td> <td> <input type = “text” name = “name”> <span class = “error”>* <?php echo $nameErr;?></span> </td> </tr> <tr> <td>E-mail: </td> <td> <input type = “text” name = “email”> <span class = “error”>* <?php echo $emailErr;?></span> </td> </tr> <tr> <td>Time:</td> <td> <input type = “text” name = “course”> <span class = “error”><?php echo $websiteErr;?></span> </td> </tr> <tr> <td>Classes:</td> <td><textarea name = “class” rows = “5” cols = “40”></textarea></td> </tr> <tr> <td>Gender:</td> <td> <input type = “radio” name = “gender” value = “female”>Female <input type = “radio” name = “gender” value = “male”>Male <span class = “error”>* <?php echo $genderErr;?></span> </td> </tr> <tr> <td>Select:</td> <td> <select name = “subject[]” size = “4” multiple> <option value = “Android”>C</option> <option value = “Java”>Java</option> <option value = “C#”>C#</option> <option value = “Data Base”>C++</option> <option value = “Hadoop”>PHP</option> <option value = “VB script”>Python</option> </select> </td> </tr> <tr> <td>Agree</td> <td><input type = “checkbox” name = “checked” value = “1”></td> <?php if(!isset($_POST[”checked”])){ ?> <span class = “error”>* <?php echo “You must agree to terms”;?></span> <?php } ?> </tr> <tr> <td> <input type = “submit” name = “submit” value = “Submit”> </td> </tr> </table> </form> Note that the form data is submitted back to the same script, hence the form’s action attribute is set to $_SERVER[“PHP_SELF”] superglobal. This part also contains certain inline PHP code that flashes the error messages besides the respective form control – such as Name Required message just besides the Name text box, if the name field is empty while submitting the form. Display Form Data The third part of the script is again a PHP code that echoes the values of each of the form fields submitted by the user. <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { echo “<h2>Your given values are as :</h2>”; echo (“<p><b>Name</b> : $name</p>”); echo (“<p><b>Email address</b> : $email</p>”); echo (“<p><b>Preffered class time</b> : $course</p>”); echo (“<p><b>Class info</b> : $class </p>”); echo (“<p><b>Gender</b> : $gender</p>”); echo “<p><b>Subjcts Chosen:</b><p>”; if (!empty($subject)) { echo “<ul>”; for($i = 0; $i < count($subject); $i++) { echo “<li>$subject[$i]</u/li>”; } echo “</ul>”; } } ?> Here’s the sample data filled in the form when the script is run from the server’s document root folder − When submitted, the output is rendered as below − Example The complete code of PHP’s handling HTML form is as follows − <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = “”; $name = $email = $gender = $class = $course = $subject = “”; if ($_SERVER[“REQUEST_METHOD”] == “POST”) { if (empty($_POST[“name”])) { $nameErr = “Name is required”; }else { $name = test_input($_POST[“name”]); } if (empty($_POST[“email”])) { $emailErr = “Email is required”; } else { $email = test_input($_POST[“email”]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = “Invalid email format”; } } if (empty($_POST[“course”])) { $course = “”; } else { $course = test_input($_POST[“course”]); } if (empty($_POST[“class”])) { $class = “”; } else { $class = test_input($_POST[“class”]); } if (empty($_POST[“gender”])) { $genderErr = “Gender is required”; } else { $gender = test_input($_POST[“gender”]); } if (empty($_POST[“subject”])) { $subjectErr = “You must select one or more subjects”; } else { $subject = $_POST[“subject”]; } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>Absolute Classes Registration Form</h2> <p><span class = “error”>* required field.</span></p> <form method = “POST” action = “<?php echo htmlspecialchars($_SERVER[“PHP_SELF”]);?>”> <table> <tr> <td>Name:</td> <td> <input type = “text” name = “name”> <span class = “error”>* <?php echo $nameErr;?></span> </td> </tr> <tr> <td>E-mail: </td> <td> <input
PHP – Form Validation
PHP – Form Validation ”; Previous Next The term “Form Validation” refers to the process of ascertaining if the data entered by the user in various form elements is acceptable for further processing. Validation of data before its subsequent processing avoids possible exceptions and runtime errors. Validation can be done both on the client-side and on the server-side. When the client submits the form, the form data is intercepted by the PHP script running on the server. Using various functions available in PHP, the server-side form validation can be done. Client-side Validation The new input controls as per the HTML5 specifications have in-built validation. For example an input element of the type ‘email’, even though is a text field, is customized to accept a string that is according to email address protocol. Validation takes place befor the data is submitted to the server. Same thing is true with other input types such as URL, number, etc. Example Given below is an HTML form with input elements of number type, email type and URL type. If you enter data that is not as per the required format, a suitable error message is flashed as you try to submit the form. <h1>Input Validation</h1> <form> <p><Label for “name”>Enter your name</label> <input type = “text” id=”name” name=”name”></p> <p><label for=”age”>Enter age</label> <input type = “text” id = “age” name=”age”></p> <p><label for=”email”>Enter your email:</label> <input type=”text” id=”email” name=”email”></p> <p><label for=”URL”>Enter your website<label> <input type = “text” id=”URL” name=”url”></p> <input type=”submit”> </form> The number type text field shows up/down counter arrows on the right. Only number is accepted, and can be incremented or decremented. If the data in email field is invalid, you get the error message flashed as below. Similarly, any incorrect format for the URL also flashes the error as shown − Validation Functions The validation on the server-side with PHP comes into picture, either when the form data passes the client-side validation, or there’s no validation on the client side at all. In the HTML form used in the above example, let us remove all special input types and use all text fields of text type. The form is submitted with POST method to hello.php on the server. <form action=”hello.php” method=”POST”> <p><Label for “name”>Enter your name</label> <input type = “text” id=”name” name=”name”></p> <p><label for=”age”>Enter age</label> <input type = “text” id = “age” name=”age”></p> <p><label for=”email”>Enter your email:</label> <input type=”text” id=”email” name=”email”></p> <p><label for=”URL”>Enter your website<label> <input type = “text” id=”URL” name=”url”></p> <input type=”submit”> </form> Form is Empty If the user (may be inadvertently) clicks the submit button, you can ask PHP to display the form again. You need to check if the $_POST array has been initialized with isset() function. If not, the header() function redirects the control back to the form. <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { if (isset($_POST)) { header(“Location: hello.html”, true, 301); exit(); } // form processing if the form is not empty } ?> Example You can also check if any of the fields is empty at the time of submitting the form. <?php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { foreach($_POST as $k=>$v) { if (empty($v)==true) { echo “One or more fields are empty n”; echo “<a href = ”hello.html”>Click here to go back </a>”; exit; } else echo “$k => $v n”; } } ?> Age field is non-numeric In the HTML form the input field for name is of text type, hence it can accept any characters. However, we want it to be numeric. This can be ensured by is_numeric() function <?php if (is_numeric($_POST[“age”])==false) { echo “Age cannot be non-numeric n”; echo “<a href = ”hello.html”>Click here to go back</a>”; } ?> PHP also has is_string() function to check if a filed contains a string or not. Two other functions, trim() and htmlspecialchars() are also useful for form validation. trim() − Removes whitespace from the beginning and end of a string htmlspecialchars() − Converts special characters to HTML entities to prevent cross-site scripting (XSS) attacks. Print Page Previous Next Advertisements ”;
PHP – GET & POST
PHP – GET & POST ”; Previous Next Since PHP is mostly used for web application development, the data sent by the browser client is mainly with the GET and POST types of HTTP request methods. The HTTP protocol also defines other methods for sending the request to the server. They are PUT, DELETE, HEAD and OPTIONS (in addition to GET and POST methods). In this chapter, we shall concentrate on how PHP handles the GET and POST methods. The GET Method The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character. http://www.test.com/index.htm?name1=value1&name2=value2 The GET method produces a long string that appears in your server logs, in the browser”s Location: box. The GET method is restricted to send upto 1024 characters only. Never use GET method if you have password or other sensitive information to be sent to the server. GET can”t be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using QUERY_STRING environment variable. The PHP provides $_GET associative array to access all the sent information using GET method. Try out following example by putting the source code in test.php script. <?php if( $_GET[“name”] || $_GET[“age”] ) { echo “Welcome “. $_GET[”name”]. “<br />”; echo “You are “. $_GET[”age”]. ” years old.”; exit(); } ?> <form action = “<?php <b>$_PHP_SELF</b> ?>” method = “GET”> Name: <input type = “text” name = “name” /> Age: <input type = “text” name = “age” /> <input type = “submit” /> </form> It will produce the following result − The POST Method The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The POST method does not have any restriction on data size to be sent. The POST method can be used to send ASCII as well as binary data. The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. The PHP provides $_POST associative array to access all the sent information using POST method. Try out following example by putting the source code in test.php script. <?php if( $_POST[“name”] || $_POST[“age”] ) { if (preg_match(“/[^A-Za-z”-]/”,$_POST[”name”] )) { die (“invalid name and name should be alpha”); } echo “Welcome “. $_POST[”name”]. “<br />”; echo “You are “. $_POST[”age”]. ” years old.”; exit(); } ?> <form action = “<?php <b>$_PHP_SELF</b> ?>” method = “POST”> Name: <input type = “text” name = “name” /> Age: <input type = “text” name = “age” /> <input type = “submit” /> </form> It will produce the following result − Difference between GET and POST The main difference between the GET and POST methods is that while the request parameters appended to the URL are exposed in the browser’s URL, the POST data is included in the message body, and not revealed in the URL. Hence, the GET method shouldn’t be used to send sensitive data to the server. Secondly, the request data in GET method cannot exceed 2048 characters and can consist of ASCII characters only, while with POST method, there is no limit to the request data which can be in binary also (the default maximum size of POST data is determined by post_max_size setting in php.ini file) PHP provides the following three superglobals to retrieve and process the request parameters − $_GET − an associative array to access all the sent information using GET method. $_POST − an associative array to access all the sent information using POST method. $_REQUEST − an associative array that can be used to get the result from form data sent with both the GET and POST methods. $_GET Array You can pass the request parameters in the form of query string directly appended to the URL. Save the following PHP script in the document root folder (htdocs) as “hello.php” − <?php echo “First name: ” . $_REQUEST[”first_name”] . ” ” . “Last Name: ” . $_REQUEST[”last_name”] . “”; ?> Enter http://localhost/hello.php?first_name=Amar&last_name=Sharma as the URL in a browser window (ensure that the PHP server is running). The $_GET array is populated from the request and the output is displayed as below − First name: Amar Last Name: Sharma You can also populate the $_GET array with the HTML form data if its method attribute is GET. Use the following HTML form to collect the data and send it to “hello.php”. Under the document root, save the following script as “hello.html” − <form action=”hello.php” method=”get”> First Name: <input type=”text” name=”first_name”/> <br/> Last Name: <input type=”text” name=”last_name” /> <input type=”submit” value=”Submit” /> </form> In your browser, enter the URL “http://localhost/hello.html” − You should get the similar output in the browser window. $_POST Array The easiest way to send data to a server with the POST request is specifying the method attribute of HTML form as POST. Assuming that the URL in the browser is “http://localhost/hello.php”, method=POST is set in a HTML form “hello.html” as in the earlier example − <form action=”hello.php” method=”post”> First Name: <input type=”text” name=”first_name”/> <br/> Last Name: <input type=”text” name=”last_name” /> <input type=”submit” value=”Submit” /> </form> The “hello.php” script (in document root folder) retrieves the form data in the $_POST array and renders it as the HTTP response back to the browser − <?php echo “First name: ” . $_POST[”first_name”] . ” ” . “Last Name: ” . $_POST[”last_name”] . “”; ?>
PHP – Passing Functions
PHP – Passing Functions ”; Previous Next To a function in PHP, in addition to scalar types, arrays, and objects, you can also pass a function as one of its arguments. If a function is defined to accept another function as an argument, the passed function will be invoked inside it. PHP’s standard library has certain built-in functions of this type, where one of the arguments to be passed is a function, which may be another built-in function or even a user defined function. array_map The array_map() is one of the built-in functions. The first argument to this function is a callback function. There may be one or more arrays as the other arguments. The callback function is applied to all the elements of arrays. array_map(?callable $callback, array $array, array …$arrays): array The array_map() function returns an array. It contains the result of applying the callback function to the corresponding elements of arrays passed as other arguments. Example In the following example, we have a square() function that computes the square of a number passed to it. This function in turn is used as an argument for array_map() function, along with another array of numbers. Each number is successively passed to the squares() function. The resultant array is a list of squares. <?php function square($number) { return $number * $number; } $arr = [1, 2, 3, 4, 5]; $squares = array_map(”square”, $arr); var_dump($squares); ?> It will produce the following output − array(5) { [0]=> int(1) [1]=> int(4) [2]=> int(9) [3]=> int(16) [4]=> int(25) } call_user_func Another example of passing a function to another function is call_user_func(). As the name suggests, it calls another user defined callback function, and the other arguments are passed to the callback. call_user_func(callable $callback, mixed …$args): mixed Example In the example below, the square() function is invoked repeatedly, passing each number in an array. <?php function square($number) { return $number * $number; } $arr = [1, 2, 3, 4, 5]; foreach($arr as $a) { echo “square of $a:” . call_user_func(“square”, $a). PHP_EOL; } ?> It will produce the following output − square of 1:1 square of 2:4 square of 3:9 square of 4:16 square of 5:25 usort As another example of passing function, we take a look a usort() function. usort(array &$array, callable $callback): true The first parameter is an array. The array is sorted as per the callback function, which is the second parameter. The callback parameter is a comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Example Here is an example. First we have a mysort() function. It compares two numbers and returns “-1”, “0” or “1” if the first number is less than, equal to or greater than second number. The first argument to usort() is the mysort() function, and the second one is an array. To begin with, the first two numbers are passed to mysort(). If it returns 1, they are swapped. Next, the second and third numbers are passed and swapped if the comparison returns 1. The same process repeats so that the array elements are arranged in ascending order. <?php function mysort($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; } $a = array(3, 2, 5, 6, 1); usort($a, “mysort”); foreach ($a as $key => $value) { echo “$key: $valuen”; } ?> It will produce the following output − 0: 1 1: 2 2: 3 3: 5 4: 6 Pass Callback to User-defined Function Apart from the above built-in functions, you can define your own function that accepts one of the arguments as another function. In the example below, we have two functions, square() and cube(), that return the square and cube of a given number. Next, there is myfunction(), whose first argument is used as a variable function and the second argument to myfunction() is passed to it. Thus, myfunction() internally calls square() or cube() to return either square or cube of a given number. Example <?php function myfunction($function, $number) { $result = $function($number); return $result; } function cube($number) { return $number ** 2; } function square($number) { return $number ** 3; } $x = 5; $cube = myfunction(”cube”, $x); $square = myfunction(”square”, $x); echo “Square of $x = $square” . PHP_EOL; echo “Cube of $x = $cube” . PHP_EOL; ?> It will produce the following output − Square of 5 = 125 Cube of 5 = 25 Print Page Previous Next Advertisements ”;
PHP – $_ENV
PHP – $_ENV ”; Previous Next $_ENV is a superglobal variable in PHP. It is an associative array that stores all the environment variables available in the current script. $HTTP_ENV_VARS also contains the same information, but it is not a superglobal, and it has now been deprecated. The environment variables are imported into the global namespace. Most of these variables are provided by the shell under which the PHP parser is running. Hence, the list of environment variables may be different on different platforms. This array ($_ENV) also includes CGI variables in case PHP is running as a server module or a CGI processor. We can use the foreach loop to display all the environment variables available − <?php foreach ($_ENV as $k=>$v) echo $k . ” => ” . $v . “<br>”; ?> On a Windows OS and with XAMPP server, you may get the list of environment variables as follows − Variable Value ALLUSERSPROFILE C:ProgramData APPDATA C:UsersuserAppDataRoaming CommonProgramFiles C:Program FilesCommon Files CommonProgramFiles(x86) C:Program Files (x86)Common Files CommonProgramW6432 C:Program FilesCommon Files COMPUTERNAME GNVBGL3 ComSpec C:WINDOWSsystem32cmd.exe DriverData C:WindowsSystem32DriversDriverData HOMEDRIVE C − HOMEPATH Usersuser LOCALAPPDATA C:UsersuserAppDataLocal LOGONSERVER \GNVBGL3 MOZ_PLUGIN_PATH C:Program Files (x86) Foxit Software Foxit PDF Readerplugins NUMBER_OF_PROCESSORS 8 OneDrive C:UsersuserOneDrive OneDriveConsumer C:UsersuserOneDrive OS Windows_NT Path C:Python311Scripts; C:Python311; C:WINDOWSsystem32; C:WINDOWS; C:WINDOWSSystem32Wbem; C:WINDOWSSystem32WindowsPowerShell v1.0; C:WINDOWSSystem32OpenSSH; C:xamppphp; C:UsersuserAppDataLocalMicrosoft WindowsApps; C:VSCodeMicrosoft VS Codebin PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE; .WSF;.WSH;.MSC;.PY;.PYW PROCESSOR_ARCHITECTURE AMD64 PROCESSOR_IDENTIFIER Intel64 Family 6 Model 140 Stepping 1, GenuineIntel PROCESSOR_LEVEL 6 PROCESSOR_REVISION 8c01 ProgramData C:ProgramData ProgramFiles C:Program Files ProgramFiles(x86) C:Program Files (x86) ProgramW6432 C:Program Files PSModulePath C:Program FilesWindowsPowerShellModules; C:WINDOWSsystem32WindowsPowerShellv1.0 Modules PUBLIC C:UsersPublic SystemDrive C − SystemRoot C:WINDOWS TEMP C:UsersuserAppDataLocalTemp TMP C:UsersuserAppDataLocalTemp USERDOMAIN GNVBGL3 USERDOMAIN_ROAMINGPROFILE GNVBGL3 USERNAME user USERPROFILE C:Usersuser windir C:WINDOWS ZES_ENABLE_SYSMAN 1 __COMPAT_LAYER RunAsAdmin Installer AP_PARENT_PID 10608 You can access the value of individual environment variable too. This code fetches the PATH environment variable − <?php echo “Path: ” . $_ENV[”Path”]; ?> It will produce the following output − Path: C:Python311Scripts;C:Python311;C:WINDOWSsystem32; C:WINDOWS;C:WINDOWSSystem32Wbem; C:WINDOWSSystem32WindowsPowerShellv1.0; C:WINDOWSSystem32OpenSSH;C:xamppphp; C:UsersmlathAppDataLocalMicrosoftWindowsApps; C:VSCodeMicrosoft VS Codebin Note − The $_ENV array may yield empty result, depending on “php.ini” setting “variables_order”. You may have to edit the “php.ini” file and set variables_order=”EGPCS” instead of variables_order=”GPCS” value. The getenv() Function The PHP library provides the getenv() function to retrieve the list of all the environment variables or the value of a specific environment variable. The following script displays the values of all the available environment variables − <?php $arr=getenv(); foreach ($arr as $key=>$val) echo “$key=>$val”; ?> To obtain the value of a specific variable, use its name as the argument for the getenv() function − <?php echo “Path: ” . getenv(“PATH”); ?> The putenv() Function PHP also provides the putenv() function to create a new environment variable. The environment variable will only exist for the duration of the current request. Changing the value of certain environment variables should be avoided. By default, users will only be able to set the environment variables that begin with “PHP_” (e.g. PHP_FOO=BAR). The “safe_mode_protected_env_vars” directive in “php.ini” contains a comma-delimited list of environment variables that the end user won”t be able to change using putenv(). <?php putenv(“PHP_TEMPUSER=GUEST”); echo “Temp user: ” . getenv(“PHP_TEMPUSER”); ?> The browser will display the following output − Temp user: GUEST Print Page Previous Next Advertisements ”;
PHP – Encapsulation
PHP – Encapsulation ”; Previous Next PHP implements encapsulation, one of the important principles of OOP with access control keywords: public, private and protected. Encapsulation refers to the mechanism of keeping the data members or properties of an object away from the reach of the environment outside the class, allowing controlled access only through the methods or functions available in the class. The following diagram illustrates the principle of encapsulation in object-oriented programming methodology. PHP’s keywords list contains the following keywords that determine the accessibility of properties and methods of an object, which is an instance of a class in PHP − Public − Class members are accessible from anywhere, even from outside the scope of the class, but only with the object reference. Private − Class members can be accessed within the class itself. It prevents members from outside class access even with the reference of the class instance. Protected − Members can be accessed within the class and its child class only, nowhere else. These three keywords “public, private and protected” are often called access modifiers. They are also referred as visibility modes, as they decide upto what extent a certain class member is available. Public Members In PHP, the class members (both member variables as well as member functions) are public by default. Example In the following program, the member variables title and price of the object are freely accessible outside the class because they are public by default, if not otherwise specified. <?php class Person { /* Member variables */ var $name; var $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } function getName() { echo “Name: $this->name” . PHP_EOL;; } function getAge() { echo “Age: $this->age” . PHP_EOL;; } } $b1 = new Person(); $b1->getName(); $b1->getAge(); echo “Name : $b1->name Age: $b1->age” . PHP_EOL; ?> It will produce the following output − Name: Ravi Age: 28 Name : Ravi Age: 28 Note that the properties all the class members are public by default, you can explicitly declare them as public if desired. As a result, the instance methods getName() and getAge() can be called from outside the class. Since properties name and age are also public, hence they can also be accessed outside the class, something which is not desired as per the principle of encapsulation. Private Members As mentioned above, the principle of encapsulation requires that the member variables should not be accessible directly. Only the methods should have the access to the data members. Hence, we need to make the member variables private and methods public. Example Let us change the declaration of name and age properties to private and run the following PHP script − <?php class Person { /* Member variables */ private $name; private $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } public function getName() { echo “Name: $this->name” . PHP_EOL;; } public function getAge(){ echo “Age: $this->age” . PHP_EOL;; } } $b1 = new Person(); $b1->getName(); $b1->getAge(); echo “Name : $b1->name Age: $b1->age” . PHP_EOL; ?> It will produce the following output − Name: Ravi Age: 28 PHP Fatal error: Uncaught Error: Cannot access private property Person::$name in person.php:27 The error message tells the reason that a private property cannot be accessed from a public scope. Protected Members The effect of specifying protected access to a class member is effective in case of class inheritance. We know that public members are accessible from anywhere outside the class, and private members are denied access from anywhere outside the class. The protected keyword grants access to an object of the same class and an object of its inherited class, denying it to any other environment. Example Let us inherit the person class and define a student class. We shall change the name property from private to protected. The student class has a new public method getDetails() that prints the values of name and age properties. Person class <?php class Person { /* Member variables */ protected $name; private $age; /*Constructor*/ function __construct(string $param1=”Ravi”, int $param2=28) { $this->name = $param1; $this->age = $param2; } public function getName(){ echo “Name: $this->name” . PHP_EOL;; } public function getAge() { echo “Age: $this->age” . PHP_EOL;; } } Student class class student extends Person { public function getDetails() { echo “My Name: $this->name” . PHP_EOL; echo “My age: $this->age” . PHP_EOL; } } $s1 = new student(); $s1->getDetails(); ?> It will produce the following output − My Name: Ravi PHP Warning: Undefined property: student::$age in person.php on line 28 My age: The following table illustrates the rules of accessibility of class members in PHP − Print Page Previous Next Advertisements ”;
PHP – Static Methods
PHP â Static Methods ”; Previous Next The “static” keyword in PHP is used to define static properties and static methods in a PHP class. It may be noted that the static keyword is also used to define static variable, and static anonymous functions. This chapter discusses static methods in a PHP class. In a class definition, a function declared with a static qualifier becomes its static method. class myclass { public static function myStaticMethod() { // … } You donât need to create the instance of the class to call its static method. The static method is called by the class name though the scope resolution operator. The syntax of a static method call is − myclass::myStaticMethod(); As the static methods are callable without creating an instance of the class, the pseudo-variable $this is not available inside static methods. A static method is allowed to be called by an object, although calling an instance method as a static method raises error. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; } } myclass::mystaticmethod(); $obj = new myclass; $obj->myinstancemethod(); $obj->mystaticmethod(); myclass::myinstancemethod(); ?> It will produce the following output − This is a static method This is an instance method This is a static method PHP Fatal error: Uncaught Error: Non-static method myclass::myinstancemethod() cannot be called statically The “self” Keyword in Static Method If you need to call a static method from inside an instance method defined in the same class, you have to use self keyword referring to the name of the class, followed by the scope resolution operator (such as self::mystaticmethod) <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; echo “calling static method from instance method” . PHP_EOL; self::mystaticmethod(); } } $obj = new myclass; $obj->myinstancemethod(); ?> It will produce the following output − This is an instance method calling static method from instance method This is a static method Using the “parent” Keyword In case of inheritance, a static method defined in a base class may be called by an object of derived class, or from inside an instance method of the derived class, by referring it with the “parent” keyword. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } public function myinstancemethod() { echo “This is an instance method”. PHP_EOL; echo “calling static method from instance method” . PHP_EOL; self::mystaticmethod(); } } class mynewclass extends myclass { public function myfunction() { echo “This an instance method of the derived class” . PHP_EOL; echo “Calling static method of the parent class” . PHP_EOL; parent::mystaticmethod(); } } $obj = new mynewclass; mynewclass::mystaticmethod(); $obj->myfunction(); ?> It will produce the following output − This is a static method This an instance method of the derived class Calling static method of the parent class This is a static method Static Method Inside Another Class It is entirely possible to call the static method from one class in another. You have to qualify its name with its class name followed by the scope resolution operator. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; public static function mystaticmethod() { echo “This is a static method”. PHP_EOL; } } #this is not a derived class class mynewclass { public function myfunction() { echo “This an instance method” . PHP_EOL; echo “Calling static method of the another class” . PHP_EOL; myclass::mystaticmethod(); } } $obj = new mynewclass; $obj->myfunction(); ?> It will produce the following output − This an instance method Calling static method of another class This is a static method Since $this pseudo-variable is not available for a static method, the instance variables of an object cannot be accessed inside a static method. It can process only the static properties of the class. Example Take a look at the following example − <?php class myclass { /* Member variables */ static int $var1 = 0; function __construct() { self::$var1++; echo “object number “. self::$var1 . PHP_EOL; } public static function mystaticmethod() { echo “Number of objects available: ” . self::$var1 . PHP_EOL; } } for ($i=1; $i<=3; $i++) { $obj = new myclass; } myclass::mystaticmethod(); ?> It will produce the following output − object number 1 object number 2 object number 3 Number of objects available: 3 Print Page Previous Next Advertisements ”;