I'm making a short URL service using Slimphp to take care of my routing. I can define any route just fine but if I want to react to /<code here> instead of that taking me to the index page of the project.
This is my code:
<?php
require 'vendor/autoload.php';
use ShortUrls\ShortUrls;
error_reporting(E_ALL);
ini_set('display_errors', true);
$app = new \Slim\Slim();(array(
"view" => new \Slim\Views\Smarty()
));
$view = $app->view();
$view->parserDirectory = dirname(__FILE__) . 'vendor/smarty/smarty/libs';
$view->parserCompileDirectory = dirname(__FILE__) . '/compiled';
$view->parserCacheDirectory = dirname(__FILE__) . '/cache';
$view->setTemplatesDirectory(dirname(__FILE__) . '/lib/templates/');
\ShortUrls\Config::init_config();
$app->get('/', function ($hash) {
try {
} catch (ResourceNotFoundException $e) {
echo '404';
}
$short = new ShortUrls();
if ($hash) {
if ($short_url = $short->get_url_by_hash(($hash))) {
print '<pre>';
print_r($short_url);
print '</prE>';
}
} else {
$short->create_short_url("http://www.locovsworld.com");
// $app->render('layout.tpl', array('test' => 'Hello'));
}
global $app;
print_r( $app->request()->params() );
echo 'done';
});
$app->run();
Remember / == index /9082ABC could be a short URL that I have to query from the database and redirect the client to.
I already got the answer its the following ...
$app->get('/(:hash)', function ($hash) {
};
I am sorry to bother you guys :(
Related
I'm completely new to php, and was hoping to get some assistance on understanding this custom script on our server as our full-time dev ended up going on a sudden leave of absence. When visiting our webpage I am getting the error:
{"error":"Bad Request"}
And our dev seems to have created a router.php file that seems to be redirecting all the traffic and thus displaying this error. I'm having a hard time trying to understand where this error is coming from and how I could further troubleshoot it. But here's the code within the router.php
<?php
use util\HttpStatus;
require_once('../vendor/autoload.php');
function module($request)
{
$request = ltrim($request, '/');
$qp = strpos($request, '?');
if ($qp > 0) {
$request = substr($request, 0, $qp);
}
$tokens = explode('/', $request);
return $tokens[0];
}
function __run($request)
{
$modules = [
"dashboard",
"inventory",
"branches",
"promotions",
"feeds",
"websites",
"leads",
"slfleads",
"events",
"media",
"notify",
"callback"
];
$requestedModule = module($request);
if(in_array($requestedModule, $modules)){
file_exists("../services/$requestedModule/_boot.php")
? require ("../services/$requestedModule/_boot.php")
: require ("../$requestedModule/_boot.php");
_boot();
} else {
_blameAndDie();
}
}
function _blameAndDie($reason = null)
{
http_response_code(HttpStatus::BAD_REQUEST);
header("Content-Type: application/json");
echo ($reason === null)
? '{"error":"Bad Request"}'
: '{"error":"Bad Request","reason":"' . $reason . '"}';
die();
}
function _blockAndDie($reason = null)
{
http_response_code(HttpStatus::UNAUTHORIZED);
header("Content-Type: application/json");
echo ($reason === null)
? '{"error":"Forbidden"}'
: '{"error":"Forbidden","reason":"' . $reason . '"}';
die();
}
function _blunderAndDie($reason = null)
{
http_response_code(HttpStatus::INTERNAL_SERVER_ERROR);
header("Content-Type: application/json");
echo ($reason === null)
? '{"error":"Server Error"}'
: '{"error":"Server Error","reason":"' . $reason . '"}';
die();
}
__run($_SERVER['REQUEST_URI']);
?>
Perhaps this is the way it is? but it would be nice to have a splash screen that just says nothing to see here or something because most of the functions are done behind the scene.
app_example.php
trying to combine an example of RR app and Ev together.
trying to use Ev to update a global variable,
which is used in HTTP response.
Ev::run(Ev::RUN_NOWAIT);
does not seem to have any effect.
Ev::run();
works. but Ev is done before the http request is handled.
Would like to have the Ev executed periodically while http request is being handled,
at the same time.
use Spiral\RoadRunner;
use Nyholm\Psr7;
include "vendor/autoload.php";
$worker = RoadRunner\Worker::create();
$psrFactory = new Psr7\Factory\Psr17Factory();
$psr7 = new RoadRunner\Http\PSR7Worker($worker, $psrFactory, $psrFactory, $psrFactory);
$global_variable = 0;
**$w = new EvTimer(2, 1, function ($w) {
global $global_variable;
$global_variable++;
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
Ev::run(Ev::RUN_NOWAIT);
# Ev::run();**
while (true) {
try {
$request = $psr7->waitRequest();
if (!($request instanceof \Psr\Http\Message\ServerRequestInterface)) { // Termination request received
break;
}
} catch (Exception $ex) {
$psr7->respond(new Psr7\Response(400)); // Bad Request
continue;
}
try {
// Application code logic
$psr7->respond(new Psr7\Response(200, [], 'Hello RoadRunner!' . $global_variable));
} catch (Exception $ex) {
$psr7->respond(new Psr7\Response(500, [], 'Something Went Wrong!'));
}
}
<?php
use React\EventLoop\Loop;
require __DIR__ . '/vendor/autoload.php';
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
return React\Http\Message\Response::plaintext(
"Hello World!\n"
);
});
$socket = new React\Socket\SocketServer('127.0.0.1:8080');
$http->listen($socket);
echo "Server running at http://127.0.0.1:8080" . PHP_EOL;
Loop::addPeriodicTimer(5, function () {
$memory = memory_get_usage() / 1024;
$formatted = number_format($memory, 3).'K';
echo "Current memory usage: {$formatted}\n";
# here is my own little logic to get data from db
# to update global variables
});
I have a this folder structure:
+ inc
++ functions.php
++ vendor
+ private
++ carddav
+++ check.php
my check.php looks like this and works:
<?php
require '../../inc/functions.php';
// CardDAV API
require '../../inc/vendor/autoload.php';
use MStilkerich\CardDavClient\{Account, AddressbookCollection, Config};
use Psr\Log\{AbstractLogger, NullLogger, LogLevel};
use Sabre\VObject\Component\VCard;
class StdoutLogger extends AbstractLogger {
public function log($level, $message, array $context = array()) {
if ($level !== LogLevel::DEBUG) {
$ctx = empty($context) ? "" : json_encode($context);
echo ">>> ".$message . $ctx . "<br />";
}
}
}
Config::init(new StdoutLogger());
$account = new Account(URL, USERNAME, PASSWORD);
$abook = new AddressbookCollection(URL, $account);
$vcard = new VCard();
?>
But now I would like to outsource this part into my functions.php:
functions.php
<?
// CardDAV API
require 'vendor/autoload.php';
use MStilkerich\CardDavClient\{Account, AddressbookCollection, Config};
use Psr\Log\{AbstractLogger, NullLogger, LogLevel};
use Sabre\VObject\Component\VCard;
class StdoutLogger extends AbstractLogger {
public function log($level, $message, array $context = array()) {
if ($level !== LogLevel::DEBUG) {
$ctx = empty($context) ? "" : json_encode($context);
echo ">>> ".$message . $ctx . "<br />";
}
}
}
Config::init(new StdoutLogger());
$account = new Account(URL, USERNAME, PASSWORD);
$abook = new AddressbookCollection(URL, $account);
?>
check.php
<?php
require '../../inc/functions.php';
$vcard = new VCard();
?>
But now I get this error when I open the check.php:
Fatal error: Uncaught Error: Class 'VCard' not found in check.php:26
Where is my mistake?
Tank you !
Imports using use statement work on a per file basis. I.e. classes need to be imported in the file where they're used. In your case remove Sabre\VObject\Component\VCard import from functions.php and move it to check.php where VCard class is actually used.
the path also correct but i still don't know why it shows class not found as a fatal error
<?php
ini_set('display_errors', 1);
require_once('../core/Http/Response.php');
use core\Http;
if(class_exists("Response")){
echo "ok";
}
else {
echo "doesn't exist";
}
$r = new Response();
$r->header('test');
?>
normal call in php file,
<?php
ini_set('display_errors', 1);
require_once('../core/Http/Response.php');
use Core\Http\Response;
if(class_exists( 'Core\Http\Response' )){
$r = new Response(); // -OR- $r = new Core\Http\Response();
}else{
die('class doesn\'t exist');
}
$r->header('test');
?>
If you want to call in any controller, call like following
<?php
// Start of the file
ini_set('display_errors', 1);
require_once('../core/Http/Response.php');
use Core\Http\Response;
// your class
class Test extends Test_Controller {
public function test(){
if(class_exists( 'Core\Http\Response' )){
$r = new Response(); // -OR- $r = new Core\Http\Response();
}else{
die('class doesn\'t exist');
}
$r->header('test');
}
}
?>
<?php
ini_set('display_errors', 1);
require_once dirname(__DIR__) . '/Core/Http/Response.php';
use \Core\Http\Response;
$test = new Response("test response");
echo $test ;
?>
session_start();
date_default_timezone_set('GMT');
require 'Slim/Slim.php';
use Slim\Slim;
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
require_once 'item.php';
this is code excerpt from index.php and stuck on the said error when it called item.php. Here the contains of the file
$app->put('/getItem', authorize(), 'getItem');
function getItem() {
$sql = "SELECT * FROM item";
$app = Slim::getInstance();
try {
$db = getConnection();
$stmt = $db->query($sql);
$item = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
$response = $app->response();
$response->header('Content-Type', 'application/json');
// Include support for JSONP requests
if (!isset($_GET['callback'])) {
echo json_encode($item);
} else {
echo $_GET['callback'] . '(' . json_encode($item) . ');';
}
} catch(PDOException $e) {
$error = array("error"=> array("text"=>$e->getMessage()));
echo json_encode($error);
}
}
i hit the error on this $app = Slim::getInstance();
What is wrong with my approach?
The Slim class' full name (including namespace) is \Slim\Slim so you'll need to use that, eg
$app = \Slim\Slim::getInstance();
Alternatively, you can import the Slim symbol using the use statement at the top of your item.php script.
use Slim\Slim;
You can use this code for Slim Framework3:
<?php
require "vendor/autoload.php";
use \Slim\App;
$app = new App();
$app->get("/",function(){
echo "Hello World";
});
$app->get("/test",function(){
echo "Hello World";
});
$app->run();
?>