To create a file in PHP is easy: file_put_contents('filename', $contents);
To rewrite the URL is a bit more complex. One way is to add a router class to handle your URL requests and rewrite them with .htaccess like so:
router.class.php:
<?
class HttpRequest {
const CONTROLLER_CLASSNAME = 'Index';
protected $controllerkey = 0;
protected $baseUrl;
protected $controllerClassName;
protected $parameters;
public function __construct() {
$this->controllerClassName = self::CONTROLLER_CLASSNAME;
}
public function setBaseUrl($url) {
$this->baseUrl = $url;
return $this;
}
public function setParameters($params) {
$this->parameters = $params;
return $this;
}
public function getParameters() {
if($this->parameters == null) {
$this->parameters = array();
}
return $this->parameters;
}
public function getControllerClassName() {
return $this->controllerClassName;
}
public function getParam($name, $default = null) {
if(isset($this->parameters[$name])) {
return $this->parameters[$name];
}
return $default;
}
public function getRequestUri() {
if(!isset($_SERVER['REQUEST_URI'])) {
return '';
}
$uri = $_SERVER['REQUEST_URI'];
$uri = trim(str_replace($this->baseUrl, '', $uri), '/');
return $uri;
}
public function createRequest() {
$uri = $this->getRequestUri();
$uriParts = explode('/', $uri);
if(!isset($uriParts[$this->controllerkey])) {
return $this;
}
$this->controllerClassName = $this->formatControllerName($uriParts[$this->controllerkey]);
unset($uriParts[$this->controllerkey]);
if(empty($uriParts)) {
return $this;
}
$i = 0;
$keyName = '';
foreach($uriParts as $key => $value) {
if ($i == 0) {
$this->parameters[$value] = '';
$keyName = $value;
$i = 1;
} else {
$this->parameters[$keyName] = $value;
$i = 0;
}
}
if($_POST) {
foreach ($_POST as $postKey => $postData) {
$this->parameters[$postKey] = $postData;
}
}
return $this;
}
protected function formatControllerName($unformatted) {
if (strpos($unformatted, '-') !== false) {
$formattedName = array_map('ucwords', explode('-', $unformatted));
$formattedName = join('', $formattedName);
} else {
$formattedName = ucwords($unformatted);
}
if (is_numeric(substr($formattedName, 0, 1))) {
$part = $part == $this->controllerkey ? 'controller' : 'action';
throw new Exception('Incorrect ' . $part . ' name "' . $formattedName . '".');
}
return ltrim($formattedName, '_');
}
}
?>
.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
To use this:
<?
require_once('router.class.php');
$request = new HttpRequest();
$request->setBaseUrl('http://url.com/');
$request->createRequest();
$value = $request->getParameters();
echo $value['key'];
?>