Category: Web

How to use posted data in the same page

GOAL

To post the input data and display it on the same page with PHP.

Environment

Windows10
XAMPP 7.4.10

Preparation

1. Change the PHP program

Create a new PHP file “index.php” to submit data. You can see the details of this program in “How To Run PHP in XAMPP“.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>test</title>
</head>
<body>
	<form action="posted.php" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>
</html>

2. Set action = “”

The action specifies the file to call. If you won’t move the page, action should be “”.

Method

Method 1. Use $_SERVER[‘REQUEST_METHOD’]

$_SERVER[‘REQUEST_METHOD’] is the variable to store the requested method. It returns the called requested method when the page is requested.

<body>
	<?php
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    	echo "The input data is ".$message;
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

Method 2. Use $_POST directly

<body>
	<?php
	if ($_POST) {
    	echo "The input data is ".$_POST['message'];
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

The result is the same as above.

Method 3. Use isset($_POST[‘message’])

<body>
	<?php
	if ($_POST) {
    	echo "The input data is ".$_POST['message'];
    }
    ?>
	<form action="" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>

The result is the same as above. The strong point of this method is that the existence of each keys of $_POST can be determined.

Access MySQL with PHP in XAMPP

GOAL

Apply to access MariaDB(MySQL) with PHP in XAMPP

Environment

Windows10
XAMPP 7.4.10

At first, install XAMPP (“Installation of XAMPP“) and If you’ll use MariaDB in a production environment, make it secure (“How To Set MySQL Password in XAMPP“). And I create database “photo_sharing” according to “How to Create Database of MariaDB in XAMPP“.

About PDO

PDO, PHP Data Objects, is an extension to access database in PHP.

Reference: PHP Data Objects in PHP manual

(more…)

How to Create Database of MariaDB in XAMPP

GOAL

Today’s goal is create database with MariaDB.

Environment

Windows10
XAMPP 7.4.10

If you don’t have XAMPP, please install it first according to “Installation of XAMPP“. And If you’ll use MariaDB in a production environment, make it secure by setting password according to “How To Set MySQL Password in XAMPP“.

Method

1. Open phpMyAdmin

Start XAMPP Control Panel and run Apache and MariaDB.

Access localhost/phpmyadmin/ or click Admin button of MySQL.

(more…)

How To Set MySQL Password in XAMPP

GOAL

To set MySQL password in XAMPP to make it secure.

Environment

Windows10
XAMPP 7.4.10

If you don’t have XAMPP, please install it first according to “Installation of XAMPP“.

XAMPP security

Please refer to “Is XAMPP production ready?” in Windows Frequently Asked Questions for information. Though it contains some old contents, but it says why default XAMPP shouldn’t be used in a production environment.

Method

1. Run Apache and MySQL

Start XAMPP Control Panel and run Apache and MySQL.

2. Access phpMyAdmin and change password

Access localhost/phpmyadmin with your browser. And click “User accounts”.

Click “Edit privileges” for root@localhost.

Click “Change password”.

Input your password. You can generate highly safe password with Generate button. And click “Go” button.

Close phpMyAdmin.

*An error will occur when accessing phpMyAdmin now because phpMyAdmin doesn’t know the password.

3. Change config.inc.php of phpMyAdmin

Open xampp\phpMyAdmin\config.inc.php and change the value of $cfg[‘Servers’][$i][‘password’].

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';  //input the password here

Save the file and close it.

Confirmation

Open the shell.

And input command “mysql -h localhost -u root -p” and the password you defined.

# mysql -h localhost -u root -p
Enter password:  <input password here>

Confirm that MariaDB is connected.

Input “quit” to quit MySQL.

And confirm that you can access localhost/phpmyadmin.

Next?

How to Create Database of MariaDB in XAMPP

How To Run PHP in XAMPP

I installed XAMPP in Installation of XAMPP. Today, I’ll use XAMPP as a test environment for PHP.

GOAL

To setup XAMPP and start PHP development in XAMPP.

How to start XAMPP

Be sure that the started module is stopped before quitting the control panel.

Method 1 Use xampp/xampp-control.exe

Right-click and run as administrator “xampp/xampp-control.exe” or “XAMPP Control Panel” in start menu.

Click “Start” buttons on the control panel.

If you add modules as a service, the check box is checked.
*You can’t see whether the check box is checked if you run the control panel as a non-administrator.

In this article below, a situation in which all modules are not registered as a service is supposed.

Click “Start” to start Apache and access localhost to confirm that apache is running.

Open browser and input “localhost”
The index page of XAMPP

Method 2 Use batch file

Use batch files in xampp\ directory to start each application individually.

xampp\xampp_start.exe
xampp\xampp_stop.exe
xampp\apache_start.bat
xampp\apache_stop.bat
mysql_start.bat, mercury_start.bat and filezilla_start.bat

Run your php program

The directory “xampp\htdocs” is document root that is assigned to localhost. So you can run your php program by putting the php file here.

Open xampp\htdocs\index.php and you can see the program to redirect users to localhost/dashboard by using header() function.

<?php
	if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
		$uri = 'https://';
	} else {
		$uri = 'http://';
	}
	$uri .= $_SERVER['HTTP_HOST'];
	header('Location: '.$uri.'/dashboard/');
	exit;
?>

1. Create “test” directory in xampp\htdocs.

2. Create PHP files

Create 2 PHP files in the “test” directory, index.php to post input data and posted.php to get and display the input data.

xampp\htdocs\test\index.php

Use POST method to send the message.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>test</title>
</head>
<body>
	<form action="posted.php" method="POST">
		<label>Input message:</label>
		<input type="text" name="message" /> <input type="submit" value="Submit!" />
	</form>
</body>
</html>

xampp\htdocs\test\posted.php

Get the posted data by using $_POST[<name>].

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>posted</title>
</head>
<body>
	<p>Message "<?php echo $_POST["message"] ?> " is posted!</p>
</form>
</body>
</html>

3. Change the redirect destination URL in xampp\htdocs\index.php

xampp\htdocs\index.php

<?php
	if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
		$uri = 'https://';
	} else {
		$uri = 'http://';
	}
	$uri .= $_SERVER['HTTP_HOST'];
	header('Location: '.$uri.'/test/');  // Change here!
	exit;
?>

4. Access localhost

Access localhost and the page is redirected to localhost/test/. Input any message you like and press submit button.

The posted page will be displayed and you can see the message you input.

“Apache Service detected with wrong path” in XAMPP

I had some trouble with Apache in XAMPP.

Problem

When I start xampp-control.exe, the message “Apache Service detected with wrong path” is displayed in XAMPP Control Panel.

Environment

Windows10
XAMPP 7.4.10

Cause of the message

Apache Service has already registered and it doesn’t match the Apache of xampp.

Open Windows Administrative Tools > Services.

Open the properties window of Apache2.4 and see the “Path to executable”. It should be changed to the path to the xampp Apache.

*If you’d like to know about “Windows Service” more, check the article “What is Windows Service?“.

Solution

1. Change the register data

Press Windows key + R and Open “regedit”.

Open Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and open Apache2.4

Right-click ImagePath and Modify the Data.

Change the value data and click OK button.

2. Restart XAMPP Control Panel

Restart XAMPP Control Panel. The error disappeared.

Error with xampp-control.ini in quitting XAMPP

Problem

When I quit XAMPP, an error “Control Panel, an Error: Cannot create file “…\xampp\xampp-control.ini” occured.

And the message “Application Error (Not Responding)” displayed.

Environment

Windows10
XAMPP 7.4.10

What is xampp-control.ini?

If you’d like to know what XAMPP is, please refer the article “Installation of XAMPP“. xampp-control.ini is the configuration settings of XAMPP. It contains variables and values as below.

[Common]
Edition=
Editor=notepad.exe
Browser=
Debug=0
Debuglevel=0
TomcatVisible=1
Language=English
[EnableModules]
Apache=1
MySQL=1
FileZilla=1
Mercury=1
Tomcat=1

What is the meaning of error message?

The error message says “the access to xampp-control.ini was denied” and “the access violation occurred in the module xampp-control.exe”.

Cause of the error

Current user is unauthorized to the file “xampp-control.ini”.

Solution

Change the current user to the administrator

Run “xampp-control.exe” as a administrator. This is the best way.

Appendix

Another Solution: Change permission of xampp-control.ini

Right-click “xampp-control.ini” and open property.

Open Security tab and click “Edit” button to change the permission. Add current user and change its permission from “Read” to “Modify”. Refer ‘“Windows cannot access the specified device, path, or file” error when you try to install, update or start a program or file‘ for details.

Warning: Be careful that this may cause security vulnerability. In my case, I run this application in only local environment.

Installation of XAMPP

Let’s develop your site with XAMPP.

GOAL

Today’s goal is to understand what XAMPP is and how to install it. This article doesn’t contain how to use XAMPP or PHP.

Environment

Windows10
XAMPP 7.4.10

What is XAMPP?

XAMPP is a free development environment for PHP. It contains the set of basic free software for web development, such as Apache, MariaDB as a SQL server, PHP, Perl, phpMyAdmin and OpenSSL.

You can see what software is included in XAMPP in the official site.

XAMPP is an acronym for cross platform(X), Apache, MariaDB, PHP and Perl.

How to Install XAMPP

1. Download

Access “Download” page in the official site. And download any version of XAMPP you like.

(more…)

How to Build Local Server 2 -Change Root Directory-

GOAL

To change settings of Apache and use your local directory as root directory.

Before changing settings of Apache, install and setup Apache. Refer to “How to Build Local Server 1” for more about installation procedure.

Environment

Windows 10
Apache 2.4.43

Change local server root

1. Set DocumentRoot in httpd.conf.

I created new directory “root” in Apache24 and set it as DocumentRoot.

# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
#DocumentRoot "${SRVROOT}/htdocs"
DocumentRoot "${SRVROOT}/root"

2. Confirm the result

Change Directives

Open httpd.conf. and change <Directory> Directive.

<Directory "${SRVROOT}/loot">
	Options Indexes FollowSymLinks
	AllowOverride None
	Require all granted
</Directory>

<Directory> Directive can control  group of directives.

Directives detail

Options: The Options directive controls which server features are available.
Indexes: If a URL which maps to a directory is requested and there is no DirectoryIndex (e.g., index.html) in that directory, then mod_autoindex will return a formatted listing of the directory.
FollowSymLinks: The server will follow symbolic links in this directory. This is the default setting.
You can see more of Options directive in Options Directive.

AllowOverride: When this directive is set to None, .htaccess files are completely ignored. .htaccess file is the configurations file for non-administrator users.
You can see more of Options directive in AllowOverride Directive.

Require: This directive tests whether an authenticated user is authorized according to a particular authorization provider and the specified restrictions.
all granted: Grant access to all requests.
You can see more of Options directive in Require Directives.

Confirm results

Put index,html and resources into root directory. Access localhost with any browser you like.

How to Build Local Server 1 -Install and Setup Apache-

GOAL

To setup Apache and build local web server with it. In this article, you can only display default page. If you would like to create new directory as a local serer, check “How to Build Local Server 2” after Apache setup.

Environment

Windows 10
Apache 2.4.43

What is Apache?

Apache is open source application for implementation of an HTTP (Web) server. You can build local web server and global web server regardless of whether it is commercial use or not.

Why is the local web server necessary? 

Local web server is used as a virtual environment for development and test before publishing to the live server. You can make local file a test server that only local users can access.

Installation and setup of Apache

Installation

1. Open Download page “Apache HTTP Server project website“.

2. Click Files for Microsoft Windows if you use windows.
* Click “Binaries” if you don’t use windows.
* I don’t know why but I couldn’t click “Source: httpd-2.4.43.tar.bz2”.

3. Select one sit from the list. In my case, I clicked “Apache Lounge”.

4. Install Apache 2.4.43 Win64 or Apache 2.4.43 Win32

Setup

1. Unzip httpd-2.4.43-win64-VS16.zip and open it. You can see the directory named “Apache**”.

2. Put the directory “Apache24” into the directory you want. I put it on document directory.

3. Open Apache24>conf>httpd.conf with your favorite text editor.

Change definition of SRVROOT into the path to “Apache24”

#default
#Define SRVROOT "c:/Apache24"
Define SRVROOT "C:\Users\USER_NAME\Documents\Apache24\conf"

ServerRoot "${SRVROOT}"

Change ServerName

# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
ServerName localhost:80

Start Apache

Use command as below or just double-click httpd.exe.

Open command prompt and change directory into the Apache24¥bin

> cd C:\Users\USER_NAME\Documents\Apache24\bin
> httpd
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using ******. Set the 'ServerName' directive globally to suppress this message

If you got an warning about fire wall, allow the access in private network.

Access localhost

How to run httpd in the background?

You should register httpd as a windows service. Open command prompt as administrator and install httpd.

> cd C:\Users\USER_NAME\Documents\Apache24\bin
>  httpd -k install
Installing the 'Apache2.4' service
The 'Apache2.4' service is successfully installed.
Testing httpd.conf....

Then you can start httpd by command as below.

httpd -k start

You can stop/shutdown by commands as below. It works only when command prompt is run by an user as administrator.

> httpd -k stop
> httpd -k shutdown

Change contents

Put index.html and resources into Apache24\htdocs. I put index.html below.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>My page</title>
  <meta name="description" content="The HTML5 Herald">
  <!--[if lt IE 9]>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
  <![endif]-->
</head>

<body>
  <h1>My Page</h1>
  <p>this is test page!</p>
</body>
</html>

Next Step

Change root directory from Apache24\htdocs into your local directory. Check How to Build Local Server 2 -Change Root Directory- for details.