Php test method post

PHP Form Validation

This and the next chapters show how to use PHP to validate form data.

PHP Form Validation

Think SECURITY when processing PHP forms!

These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!

The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:

The validation rules for the form above are as follows:

Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

First we will look at the plain HTML code for the form:

Text Fields

The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:

Radio Buttons

The gender fields are radio buttons and the HTML code looks like this:

The Form Element

The HTML code of the form looks like this:

When the form is submitted, the form data is sent with method=»post».

What is the $_SERVER[«PHP_SELF»] variable?

The $_SERVER[«PHP_SELF»] is a super global variable that returns the filename of the currently executing script.

So, the $_SERVER[«PHP_SELF»] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.

What is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and >with < and >. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

Big Note on PHP Form Security

The $_SERVER[«PHP_SELF»] variable can be used by hackers!

If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.

Читайте также:  Input with name css

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users.

Assume we have the following form in a page named «test_form.php»:

Now, if a user enters the normal URL in the address bar like «http://www.example.com/test_form.php», the above code will be translated to:

However, consider that a user enters the following URL in the address bar:

In this case, the above code will be translated to:

This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.

Be aware of that any JavaScript code can be added inside the tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER[«PHP_SELF»] Exploits?

$_SERVER[«PHP_SELF»] exploits can be avoided by using the htmlspecialchars() function.

The form code should look like this:

The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output:

The exploit attempt fails, and no harm is done!

Validate Form Data With PHP

The first thing we will do is to pass all variables through PHP’s htmlspecialchars() function.

When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:

— this would not be executed, because it would be saved as HTML escaped code, like this:

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:

  1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
  2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).

Читайте также:  Unicode to utf8 java

We will name the function test_input().

Now, we can check each $_POST variable with the test_input() function, and the script looks like this:

Example

// define variables and set to empty values
$name = $email = $gender = $comment = $website = «»;

if ($_SERVER[«REQUEST_METHOD»] == «POST») $name = test_input($_POST[«name»]);
$email = test_input($_POST[«email»]);
$website = test_input($_POST[«website»]);
$comment = test_input($_POST[«comment»]);
$gender = test_input($_POST[«gender»]);
>

function test_input($data) $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
>
?>

Notice that at the start of the script, we check whether the form has been submitted using $_SERVER[«REQUEST_METHOD»]. If the REQUEST_METHOD is POST, then the form has been submitted — and it should be validated. If it has not been submitted, skip the validation and display a blank form.

However, in the example above, all input fields are optional. The script works fine even if the user does not enter any data.

The next step is to make input fields required and create error messages if needed.

Источник

Testing your API with PHPUnit

Example output from PHPUnit

It’s always a good idea to have tests for your code, and your API is no exception. In addition to normal unit tests, API tests can test the full code stack, and ensure that the data from your database actually reaches the clients in the correct format.

REST uses the standard HTTP status codes to indicate the success of a request, so we must ensure it returns the expected codes, especially in error scenarios.

I recently implemented a simple REST API in PHP for Regex Crossword, so in this article I will show how to write some API tests using PHPUnit 5.0 and Guzzle 6.1. Actually we can test any API written in any language using this, but if you are used to PHP this will be very easy.

Update 2015-11-30: This article and examples have been updated to GuzzleHttp 6.

PHPUnit and Guzzle

First we download PHPUnit which is the testing framework in which we will write our tests. Then we download Guzzle, which is a library that helps us make requests to the API. You can install both using Composer if you like:

$ composer require guzzlehttp/guzzle:^6.1 phpunit/phpunit:^5.0

Testing the API

Let’s assume we have a small REST endpoint called /books which supports GET and POST.

We’ll add our first test file called BooksTest.php :

 require('vendor/autoload.php'); class BooksTest extends PHPUnit_Framework_TestCase  protected $client; protected function setUp()  $this->client = new GuzzleHttp\Client([ 'base_uri' => 'http://mybookstore.com' ]); > public function testGet_ValidInput_BookObject()  $response = $this->client->get('/books', [ 'query' => [ 'bookId' => 'hitchhikers-guide-to-the-galaxy' ] ]); $this->assertEquals(200, $response->getStatusCode()); $data = json_decode($response->getBody(), true); $this->assertArrayHasKey('bookId', $data); $this->assertArrayHasKey('title', $data); $this->assertArrayHasKey('author', $data); $this->assertEquals(42, $data['price']); > > 

There’s a few going on here. First we include Guzzle and PHPUnit. If you installed them using Composer, you just have to require the autoload.php .

Then we create a test class for our /books endpoint called BooksTest . You can name this whatever you like, but I prefer to have tests for each endpoint in separate files/classes.

Using the special setUp() function, we can instantiate a new Guzzle client before each test. This saves us some lines of code if we have more than one test.

The last function testGet_ValidInput_BookObject is our actual test, which verifies that we can GET a single book from our API. We then assert that this book has the properties we are expecting.

Testing POST and DELETE

Let’s add an additional test, to see if we can also create a new book.

public function testPost_NewBook_BookObject()  $bookId = uniqid(); $response = $this->client->post('/books', [ 'json' => [ 'bookId' => $bookId, 'title' => 'My Random Test Book', 'author' => 'Test Author' ] ]); $this->assertEquals(200, $response->getStatusCode()); $data = json_decode($response->getBody(), true); $this->assertEquals($bookId, $data['bookId']); >

Now we have some tests for the «happy path», but we should also check that our API correctly rejects invalid requests like DELETE:

public function testDelete_Error()  $response = $this->client->delete('/books/random-book', [ 'http_errors' => false ]); $this->assertEquals(405, $response->getStatusCode()); >

The option ‘http_errors’ => false makes sure Guzzle don’t throw an exception if our API returns an error code.

Running the tests

Now you should be able to run our tests by starting PHPUnit. If you installed it using Composer, it should be in your vendor folder:

$ php vendor/bin/phpunit BooksTest.php

Remember it’s just as important to test failing/edge cases as testing when things go well. Also you should run these tests against an isolated testing environment if they modify your data.

Источник

Оцените статью