/** * @param SlimWebServiceRegistryCategory $category */ public function AddCategory(SlimWebServiceRegistryCategory $category) { foreach ($category->Gets() as $registration) { $this->slim->get($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } foreach ($category->Posts() as $registration) { $this->slim->post($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } foreach ($category->Deletes() as $registration) { $this->slim->delete($registration->Route(), $registration->Callback())->name($registration->RouteName()); $this->SecureRegistration($registration); } $this->categories[] = $category; }
/** * @dataProvider authenticationDataProvider */ public function testRouteAuthentication($requestMethod, $path, $location, $hasIdentity, $identity, $httpStatus) { \Slim\Environment::mock(array('REQUEST_METHOD' => $requestMethod, 'PATH_INFO' => $path)); $this->auth->expects($this->once())->method('hasIdentity')->will($this->returnValue($hasIdentity)); $this->auth->expects($this->once())->method('getIdentity')->will($this->returnValue($identity)); $app = new \Slim\Slim(array('debug' => false)); $app->error(function (\Exception $e) use($app) { // Example of handling Auth Exceptions if ($e instanceof AuthException) { $app->response->setStatus($e->getCode()); $app->response->setBody($e->getMessage()); } }); $app->get('/', function () { }); $app->get('/member', function () { }); $app->delete('/member/photo/:id', function ($id) { }); $app->get('/admin', function () { }); $app->map('/login', function () { })->via('GET', 'POST')->name('login'); $app->add($this->middleware); ob_start(); $app->run(); ob_end_clean(); $this->assertEquals($httpStatus, $app->response->status()); $this->assertEquals($location, $app->response->header('location')); }
} echoRespnse(200, $response); }); /** * Deleting contact. Users can delete only their contacts * method DELETE * url /tasks */ $app->delete('/contacts/:id', 'authenticate', function ($contact_id) use($app) { global $user_id; $db = new DbHandler(); $response = array(); $result = $db->deleteContact($user_id, $contact_id); if ($result) { // contact deleted successfully $response["error"] = false; $response["message"] = "Contact deleted succesfully"; } else { // contact failed to delete $response["error"] = true; $response["message"] = "Contact failed to delete. Please try again!"; } echoRespnse(200, $response); }); /** * Verifying required params posted or not */ function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = array();
ini_set('display_errors', 'On'); $stmt = $mysqli->prepare("INSERT INTO Races (Name,Date,Users_id) Values (?,?,?);"); $stmt->bind_param("ssi", $name, $date, $userid); if ($stmt->execute()) { $new_id = $mysqli->insert_id; $json[] = array("name" => $name, "date" => $date, "id" => $new_id); return $json; } $stmt->close(); }); $app->delete('/races/:id', function ($id) { include 'conn.php'; ini_set('display_errors', 'On'); $stmt = $mysqli->prepare("DELETE FROM Races WHERE id = ?"); $stmt->bind_param("i", $id); if ($stmt->execute()) { $success = 1; } else { $success = 0; } $stmt->close(); }); $app->put('/races/:id', function ($id) use($app) { include 'conn.php'; $body = $app->request()->getBody(); $name = $body["name"]; $date = $body["date"]; ini_set('display_errors', 'On'); $stmt = $mysqli->prepare("UPDATE Races SET Name = ?, Date = ? WHERE id = ?"); $stmt->bind_param("ssi", $name, $date, $id); if ($stmt->execute()) { $success = 1;
echoRespnse(404, $response); } }); /** * Deleting category. Admin can delete only the category. * method DELETE * url /tasks */ $app->delete('/categories/:id', 'authenticate', function ($cat_id) use($app) { $db = new DbHandler(); $response = array(); $result = $db->deleteCategory($cat_id); if ($result) { // category deleted successfully $response["error"] = false; $response["message"] = "Category deleted succesfully"; } else { // category failed to delete $response["error"] = true; $response["message"] = "Category failed to delete. Please try again!"; } echoRespnse(200, $response); }); /** * Create Articles * url - /articles * method - POST * params - category_name, category_description */ $app->post('/categories/:id/articles', 'authenticate', function ($cat_id) use($app) { // check for required params
/** * Test DELETE route */ public function testDeleteRoute() { \Slim\Environment::mock(array('REQUEST_METHOD' => 'DELETE', 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar')); $s = new \Slim\Slim(); $mw1 = function () { echo "foo"; }; $mw2 = function () { echo "bar"; }; $callable = function () { echo "xyz"; }; $route = $s->delete('/bar', $mw1, $mw2, $callable); $s->call(); $this->assertEquals('foobarxyz', $s->response()->body()); $this->assertEquals('/bar', $route->getPattern()); $this->assertSame($callable, $route->getCallable()); }
echo json_encode($oProductMgr->getAllProducts()); }); $oApp->post('/addProduct', function () use($oApp, $oProductMgr) { if (getUserType() != 'admin') { $oApp->halt(500, 'You are not login'); return; } $oProduct = json_decode($oApp->request->getBody()); //ChromePhp::info($oProduct); $nRow = $oProductMgr->addProduct($oProduct); echo json_encode(array("rows" => $nRow)); }); $oApp->delete('/deleteProduct/:id', function ($nId) use($oApp, $oProductMgr) { if (getUserType() != 'admin') { $oApp->halt(500, 'You are not login'); return; } $nRow = $oProductMgr->deleteProduct($nId); echo json_encode(array("rows" => $nRow)); }); $oApp->post('/updateProduct/:id', function ($nId) use($oApp, $oProductMgr) { if (getUserType() != 'admin') { $oApp->halt(500, 'You are not login'); return; } $oProduct = json_decode($oApp->request->getBody()); //ChromePhp::info($oProduct); $nRow = $oProductMgr->updateProduct($oProduct); echo json_encode(array("rows" => $nRow)); }); $oApp->post('/updateFeaturedProducts', function () use($oApp, $oProductMgr) { if (getUserType() != 'admin') {
$app->delete('/powerport/:deviceid', function ($deviceid) use($app, $person) { $pp = new PowerPorts(); $pp->DeviceID = $deviceid; foreach ($app->request->delete() as $prop => $val) { $pp->{$prop} = $val; } function updatedevice($deviceid) { $dev = new Device(); $dev->DeviceID = $deviceid; $dev->GetDevice(); $dev->PowerSupplyCount = $dev->PowerSupplyCount - 1; $dev->UpdateDevice(); } // If this port isn't the last port then we're gonna shuffle ports to keep the ids in orderish $lastport = end($pp->getPorts()); if ($lastport->PortNumber != $pp->PortNumber) { foreach ($lastport as $prop => $value) { if ($prop != "PortNumber") { $pp->{$prop} = $value; } } if ($pp->updatePort()) { if ($lastport->removePort()) { updatedevice($pp->DeviceID); $response['error'] = false; } else { $response['error'] = true; } } else { $response['error'] = true; } } else { // Last available port, just delete it. if ($pp->removePort()) { updatedevice($pp->DeviceID); $response['error'] = false; } else { $response['error'] = true; } } $response['errorcode'] = 200; echoResponse(200, $response); });
// $datosform->post('apellidos') // Preparamos la consulta de insert. $consulta = $db->prepare("insert into soporte_usuarios(idusuario,nombre,apellidos,email) \n\t\t\t\t\tvalues (:idusuario,:nombre,:apellidos,:email)"); $estado = $consulta->execute(array(':idusuario' => $datosform->post('idusuario'), ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email'))); if ($estado) { echo json_encode(array('estado' => true, 'mensaje' => 'Datos insertados correctamente.')); } else { echo json_encode(array('estado' => false, 'mensaje' => 'Error al insertar datos en la tabla.')); } }); // Programamos la ruta de borrado en la API REST (DELETE) $app->delete('/usuarios/:idusuario', function ($idusuario) use($db) { $consulta = $db->prepare("delete from soporte_usuarios where idusuario=:id"); $consulta->execute(array(':id' => $idusuario)); if ($consulta->rowCount() == 1) { echo json_encode(array('estado' => true, 'mensaje' => 'El usuario ' . $idusuario . ' ha sido borrado correctamente.')); } else { echo json_encode(array('estado' => false, 'mensaje' => 'ERROR: ese registro no se ha encontrado en la tabla.')); } }); // Actualización de datos de usuario (PUT) $app->put('/usuarios/:idusuario', function ($idusuario) use($db, $app) { // Para acceder a los datos recibidos del formulario $datosform = $app->request; // Los datos serán accesibles de esta forma: // $datosform->post('apellidos') // Preparamos la consulta de update. $consulta = $db->prepare("update soporte_usuarios set nombre=:nombre, apellidos=:apellidos, email=:email \n\t\t\t\t\t\t\twhere idusuario=:idusuario"); $estado = $consulta->execute(array(':idusuario' => $idusuario, ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email'))); // Si se han modificado datos... if ($consulta->rowCount() == 1) {
// echo json_encode(array('type' => $_REQUEST['type'], 'id' => $_REQUEST['id']), JSON_NUMERIC_CHECK); // CD-Info aus Datenbank holen // Mögliche Typen ($_REQUEST['type']): // - songs // - ... // $ctrlCD->PostCdInfo((object) array( // 'type' => $_REQUEST['type'], // 'id' => $_REQUEST['id'] // )); }); // $app->put('/cd/:id', function ($id) use ($db, $app) { $app->put('/cd/:id', function ($id) use($app) { // update data }); $app->delete('/cd/:id', function ($id) use($db) { // delete data }); // --- Bands ---- /** * (GET) * Liefert ein Array mit Band-Objekten aller Bands zurück */ $app->get('/bands', function () use($app) { // // Band-Controller instanziieren $ctrlBand = new BandController(); // // Alle Bands aus Datenbank holen $ctrlBand->GetBand(); }); /** * (GET) * Informationen (GET) zu einer Band einer Band-ID
$m->setParent(null); if (param_set_entity('Kategorija', $m, 'kategorija')) { if ($m->getId()) { $em->merge($m); } else { $em->persist($m); } $em->flush(); echo json_encode(array('id' => $m->getId())); $app->stop(); } } } $app->halt(400, 'Nisu dostavljeni svi neophodni parametri u zahtjevu. [naslov, tekst, kategorija]'); }); $app->delete('/media/:id/', function ($id) use($em) { }); // ** MEDIATIP ** //$app->get('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {}); //$app->post('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {}); //$app->put('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {}); //$app->delete('/mediatip/:id/', function ($id) use ($twig, $em, $urls, $app) {}); // ** KATEGORIJA ** $app->get('/kategorija/', function () use($em) { $ke = $em->getRepository('Kategorija')->findAll(); $r = array(); foreach ($ke as $k) { $r[] = $k->getSerial(); } echo json_encode($r); }); $app->get('/kategorija/:id/', function ($id) use($twig, $em, $urls, $app) {
$row = $database->single(); $user = $row['settings_value']; $passwd = $row['settings_extra']; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // Authorization: Basic OXR1Y3VTTXUwSjpiTEc3NUJ2bVpM $app->add(new \Slim\Middleware\HttpBasicAuthentication(["users" => [$user => $passwd], "error" => function ($arguments) use($app) { $response["status"] = "error"; $response["message"] = $arguments["message"]; $app->response->write(json_encode($response, JSON_UNESCAPED_SLASHES)); }])); $app->get('/users', 'getUsers'); $app->get('/user/:user_id', 'getUsersId'); $app->put('/update/:user_id', 'updateUser'); $app->post('/insert', 'insertUser'); $app->delete('/delete/:user_id', 'deleteUser'); /* api Keys */ function validateKey($apiKey) { /* function hash_password($password, $salt) { $hash = hash_hmac("md5", $salt, $password); for ($i = 0; $i < 1000; $i++) { $hash = hash_hmac("md5", $hash, $password); } return $hash; } $database = new Database(); $sql="SELECT * FROM settings WHERE settings_desc=:settings_desc"; $database->query($sql); $database->bind(':settings_desc', "apiKey"); $row = $database->single();
} return $r->respond(500, 'ERROR WHILE INSERTING DATA', true); } return $r->respond(404, 'NOT FOUND', true); }); $app->delete('/:package/:name/:id', 'API', 'CHECKTOKEN', 'RATELIMITER', function ($package, $name, $id) use($r) { $tableName = $r->genTableName($package, $name); if (!$r->packageOK($package, 'remove') && $tableName !== 'managepackages') { return $r->respond(400, 'BAD REQUEST', true); } $data = R::findOne($tableName, 'id = ?', array($id)); if ($data) { $existingSyncMeta = R::findOne('syncmeta', 'where row_id = ? and tableName = ?', array($id, $tableName)); if ($existingSyncMeta) { $existingSyncMeta->type = 'remove'; $existingSyncMeta->timestamp = date('Y-m-d H:i:s'); R::store($existingSyncMeta); } if ($r->fireHookIfExists($package, $name, 'beforeRemove', $r->unserialize(array($data->export()))[0])) { R::trash($data); $r->fireHookIfExists($package, $name, 'afterRemove', $r->unserialize(array($data->export()))[0]); return $r->respond(200, 'DELETED'); } return $r->respond(403, 'FORBIDDEN:HOOK', true); } return $r->respond(404, 'NOT FOUND', true); }); /* Handle Options Route */ $app->options('/:any+', 'API', function () use($app, $r) { return $r->respond(200); }); /* default 404 and Error Handler */
$app->configureMode('production', function () use($app) { $app->config(array('debug' => false, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG)); }); $app->group('/users', function () use($app) { global $decode_body; $app->post('', $decode_body, function () { create_user(); }); $app->group('/:username', function () use($app) { global $check_token_exists; global $decode_body; $app->put('', $check_token_exists, $decode_body, function ($username) { change_pwd($username); }); $app->delete('', $check_token_exists, function ($username) { delete_user($username); }); }); }); $app->group('/calendars', function () use($app) { global $check_token_exists; global $decode_body; $app->get('', $check_token_exists, function () { get_calendars(); }); $app->post('', $check_token_exists, $decode_body, function () { create_calendar(); }); $app->group('/:calendar_id', function () use($app) { global $check_token_exists; global $decode_body;
}); // Stop all nodes and clear the system $app->delete('/api/status', function () use($app, $db) { list($user, $tenant, $output) = apiAuthorization($db, $app->getCookie('unetlab_session')); if ($user === False) { $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); return; } if (!in_array($user['role'], array('admin'))) { $app->response->setStatus($GLOBALS['forbidden']['code']); $app->response->setBody(json_encode($GLOBALS['forbidden'])); return; } $cmd = 'sudo /opt/unetlab/wrappers/unl_wrapper -a stopall'; exec($cmd, $o, $rc); if ($rc != 0) { error_log(date('M d H:i:s ') . 'ERROR: ' . $GLOBALS['messages'][60044]); $output['code'] = 400; $output['status'] = 'fail'; $output['message'] = $GLOBALS['messages']['60050']; } else { $output['code'] = 200; $output['status'] = 'success'; $output['message'] = $GLOBALS['messages']['60051']; } $app->response->setStatus($output['code']); $app->response->setBody(json_encode($output)); }); /*************************************************************************** * List Objects
require_once '../includes/dbFacile.php'; require_once '../includes/rewrites.php'; require_once 'includes/functions.inc.php'; require_once '../includes/rrdtool.inc.php'; require 'lib/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); require_once 'includes/api_functions.inc.php'; $app->setName('api'); $app->group('/api', function () use($app) { $app->group('/v0', function () use($app) { $app->get('/bgp', 'authToken', 'list_bgp')->name('list_bgp'); // api/v0/bgp $app->get('/oxidized', 'authToken', 'list_oxidized')->name('list_oxidized'); $app->group('/devices', function () use($app) { $app->delete('/:hostname', 'authToken', 'del_device')->name('del_device'); // api/v0/devices/$hostname $app->get('/:hostname', 'authToken', 'get_device')->name('get_device'); // api/v0/devices/$hostname $app->patch('/:hostname', 'authToken', 'update_device')->name('update_device_field'); $app->get('/:hostname/vlans', 'authToken', 'get_vlans')->name('get_vlans'); // api/v0/devices/$hostname/vlans $app->get('/:hostname/graphs', 'authToken', 'get_graphs')->name('get_graphs'); // api/v0/devices/$hostname/graphs $app->get('/:hostname/ports', 'authToken', 'get_port_graphs')->name('get_port_graphs'); $app->get('/:hostname/port_stack', 'authToken', 'get_port_stack')->name('get_port_stack'); // api/v0/devices/$hostname/ports $app->get('/:hostname/components', 'authToken', 'get_components')->name('get_components'); $app->post('/:hostname/components/:type', 'authToken', 'add_components')->name('add_components'); $app->put('/:hostname/components', 'authToken', 'edit_components')->name('edit_components'); $app->delete('/:hostname/components/:component', 'authToken', 'delete_components')->name('delete_components');
$obj = json_decode($json); $updateSet = ""; foreach ($obj as $key => $value) { $updateSet .= "{$key} = '{$value}', "; } $updateSet = substr_replace($updateSet, "", -2); try { R::exec("UPDATE book SET {$updateSet} WHERE id = '{$id}'"); } catch (RedBeanPHP\RedException\SQL $e) { fail($e); } }); $app->delete('/book/:id', function ($id) use($app) { try { R::exec("DELETE FROM book WHERE id ='{$id}'"); } catch (RedBeanPHP\RedException\SQL $e) { fail($e); } }); $app->get('/mentors', function () use($app) { $mentor = R::findAll('mentor'); success(R::exportAll($mentor)); }); $app->get('/mentors/:id', function ($id) use($app) { $mentor = R::findOne('mentor', "id = '{$id}'"); if (isset($mentor)) { echo json_encode($mentor->export()); } else { fail("no mentor exist, body:{$body}"); } });
require 'Slim/Slim.php'; //if($_POST) //{ // echo "asdfasdf"; // exit; //} \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->get('/hello', 'sayHello'); $app->get('/token', 'alltoken'); $app->get('/debitrequest', 'debitRequest'); $app->get('/topuprequest', 'TopUpRequest'); $app->get('/addagent', 'addAgent'); $app->get('/users/search/:query', 'findByName'); $app->put('/users/:id', 'updateUser'); $app->delete('/users/:id', 'deleteUser'); $app->run(); function sayHello() { global $app; $req = $app->request(); $nameValue = $req->get('name'); $idValue = $req->get('id'); $rel = 'hello ' . $nameValue . ' your student id is ' . $idValue; echo json_encode($rel); } function allToken() { $res = db_query("select * from token_checker"); echo json_encode($res); }
$resolvetime = getTimeString($endtime - $detect_time); } else { $resolvetime = $impacttime; } $undetecttime = getTimeString($detect_time - $starttime); $edit_status = Postmortem::get_event_edit_status($event); $content = 'content/edit'; $curl_client = new CurlClient(); $show_sidebar = false; include 'views/page.php'; }); $app->delete('/events/:id', function ($id) use($app) { header("Content-Type: application/json"); $res = Postmortem::delete_event($id); if ($res["status"] == Postmortem::ERROR) { $app->response->status(500); echo json_encode($res["error"]); } else { $app->response->status(204); } }); $app->get('/events/:id/undelete', function ($id) use($app) { $res = Postmortem::undelete_event($id); if ($res["status"] == Postmortem::ERROR) { $app->response->status(500); $app->response->body($res["error"]); } else { $app->redirect("/events/{$id}"); } }); $app->get('/events/:id/summary', function ($id) use($app) { $event = Postmortem::get_event($id);
<?php chdir(__DIR__ . '/../../../'); ini_set('session.use_cookies', 0); require 'vendor/autoload.php'; \Caco\MiniAR::setDefaultPdo($pdo = new \PDO('sqlite:database/app.sqlite3')); $pdo->exec('PRAGMA foreign_keys = ON'); $app = new \Slim\Slim(); $app->view(new \Caco\Slim\JsonView()); $app->add($auth = new \Caco\Slim\Auth\Basic()); $auth->setRealm('Caco Cloud'); $app->group('/password', function () use($app) { $app->get('/:key/:id', '\\Caco\\Password\\REST:one')->conditions(['id' => '\\d+']); $app->get('/:key', '\\Caco\\Password\\REST:all'); $app->post('/:key', '\\Caco\\Password\\REST:add'); $app->delete('/:key/:id', '\\Caco\\Password\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:key/:id', '\\Caco\\Password\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/bookmark', function () use($app) { $app->get('/:id', '\\Caco\\Bookmark\\REST:one')->conditions(['id' => '\\d+']); $app->get('', '\\Caco\\Bookmark\\REST:all'); $app->post('', '\\Caco\\Bookmark\\REST:add'); $app->delete('/:id', '\\Caco\\Bookmark\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:id', '\\Caco\\Bookmark\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/config', function () use($app) { $app->get('/:key', '\\Caco\\Config\\REST:one'); $app->get('', '\\Caco\\Config\\REST:all'); $app->post('', '\\Caco\\Config\\REST:add'); $app->delete('/:key', '\\Caco\\Config\\REST:delete'); $app->put('/:key', '\\Caco\\Config\\REST:edit');
require '../../libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // User id from db - Global Variable $user_id = NULL; // --------------------------------------------------------------------- // ------ web services ------------------------------------------------- // --------------------------------------------------------------------- // Creating a new material in db $app->post('/materials', 'authenticate', 'createMaterials'); // Listing all materials $app->get('/materials', 'authenticate', 'getAllMaterials'); // Updating all materials included in payload $app->put('/materials', 'authenticate', 'updateMaterials'); // Deleting a set of materials $app->delete('/materials', 'authenticate', 'deleteMaterials'); // --------------------------------------------------------------------- // ------ Auxiliar methods --------------------------------------------- // --------------------------------------------------------------------- // Verifying required params posted or not function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = array(); $request_params = $_REQUEST; // Handling PUT request params if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $app = \Slim\Slim::getInstance(); parse_str($app->request()->getBody(), $request_params); }
$user = User::getAllUser(); }); $app->post('/AddUser', function () { //ajoute un utilisateur $user = User::AddUser($_POST["pseudo"], $_POST["email"], $_POST["password"], $_POST["birthdate"], $_POST["city"], $_POST["budget"]); }); $app->get('/connexion/:pseudo/:password', function ($pseudo, $password) { User::connexion($pseudo, $password); //retourne userID si ok sinon retourne 0 }); $app->put('/modifUser', function () { //modifier utilisateur $user = User::UpdateUser($_POST["pseudo"], $_POST["email"], $_POST["password"], $_POST["birthdate"], $_POST["city"], $_POST["budget"], $_POST["id"]); }); $app->delete('/delUser', function () { //modifier utilisateur $user = User::DeleteUser($_POST["id"]); }); /*-------------------------------------------------- FRIGO --------------------------------------------------*/ $app->get('/getIngredientsFridge/:userId', function ($userId) { Frigo::getIngredientsFridge($userId); //renvoi tous les ingrédients du frigo de l'utilisateur }); $app->get('/getIngredientsFridgeWithFiltre/:userId/:filtre/:donnee', function ($userId, $filtre, $donnee) { Frigo::getIngredientsFridgeWithFiltre($userId, $filtre, $donnee); //renvoi tous les ingrédients du frigo de l'utilisateur avec filtre }); $app->get('/getUserFridge/:frigoId', function ($frigoId) { Frigo::getUserFridge($frigoId); //renvoi l'utilisateur du frigo
<?php require dirname(__DIR__) . '/vendor/autoload.php'; $app = new Slim\Slim(); $view = new Pug\Example\Simple($app); // Request전체를 보고자 할때. $app->get("/status", [$view, 'showStatus']); $app->post("/status", [$view, 'showStatus']); $app->put("/status", [$view, 'showStatus']); $app->delete("/status", [$view, 'showStatus']); // 일반적인 상황의 로그인과 로그아웃 $app->post('/login', [$view, 'normalLogin']); $app->get('/me', [$view, 'normalMe']); // 크로스 도메인의 경우 로그인과 로그아웃 (세션 분리) $app->post('/cors/login', [$view, 'corsLogin']); $app->get('/cors/me', [$view, 'corsMe']); $app->run();
$boolString = $add ? 'true' : 'false'; echo $boolString; }); //Display All Users: $app->get('/user/', function () { global $user, $app; echo json_encode($user->getAllUsers()); //var_dump ($user->getAllUsers()); }); //Display specific user $app->get('/user/:id', function ($id) { global $user, $app; $user = $user->getUser($id); echo $user[0]['user_email']; //echo ( json_encode($user->getUser($id)) ); }); //Delete User $app->delete('/user/:id', function ($id) { global $user, $app; $user->deleteUser($id); }); //Update User $app->put('/user/:id', function ($id) { global $user, $app; //var_dump($app->request->getBody()); $jsonUser = json_decode($app->request->getBody(), true); var_dump($jsonUser); $user->updateUser($jsonUser); }); // $app->run();
require_once '../service/ContraMedidaService.php'; require_once '../model/ContraMedida.php'; require_once '../Slim/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $contraMedidaService = new ContraMedidaService(); $app->get("/", function () { echo "<h1>Hello World</h1>"; }); $app->get("/contraMedida/getall", function () use($app, $contraMedidaService) { echo '{"contraMedidas": ' . json_encode($contraMedidaService->buscarContraMedidas()) . '}'; }); $app->get("/contraMedida/:id", function ($id) use($app, $contraMedidaService) { echo json_encode($contraMedidaService->buscarContraMedida($id)); }); $app->post("/contraMedida/cadastrar", function () use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->cadastrarContraMedida($resultado->nomeContraMedida)); }); $app->put("/contraMedida/atualizar", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->atualizarContraMedida($resultado->idContraMedida, $resultado->nomeContramedida)); }); $app->delete("/contraMedida/remover/:id", function ($id) use($app, $contraMedidaService) { $app->response()->header("Content-Type", "application/json"); $resultado = json_decode($app->request()->getBody()); echo json_encode($contraMedidaService->removerContraMedida($id)); }); $app->run();
$app = \Slim\Slim::getInstance(); $data = json_decode($app->request->getBody(), true); if (array_key_exists('publisher_id', $data) && array_key_exists('recipient_id', $data) && array_key_exists('rating', $data) && array_key_exists('comment', $data)) { if (isset($data['publisher_id']) && isset($data['recipient_id']) && isset($data['rating']) && isset($data['comment'])) { if (empty($data['publisher_id']) || empty($data['recipient_id']) || empty($data['comment']) || !($data['rating'] >= 0 && $data['rating'] <= 5)) { $app->halt(422, json_encode(array('status' => 422, 'error' => 'Empty or Invalid value parameters'))); } } else { $app->halt(422, json_encode(array('status' => 422, 'error' => 'Undefined parameters'))); } } else { $app->halt(422, json_encode(array('status' => 422, 'error' => 'Missing parameters'))); } } // Define routes $app->group('/api', function () use($app) { // Get all ratings $app->get('/', 'getAllRatings'); // Get single by rating id $app->get('/:id/', 'getSingleRatingByID'); // Get all by recipient id $app->get('/recipients/:id', 'getAllRatingsByRecipientID'); // Get all by publisher id $app->get('/publishers/:id', 'getAllRatingsByPublisherID'); // Delete single rating $app->delete('/delete/:id', 'deleteRatingByID'); // Create new rating $app->post('/create', 'reqDataCheck', 'publishNewRating'); }); // Run app $app->run();
// END POST $app->get('/get', function () { $mydata = file_get_contents("test.json"); print $mydata; }); // PUT route $app->put('/put', function () { echo 'This is a PUT route'; }); // PATCH route $app->patch('/patch', function () { echo 'This is a PATCH route'; }); // DELETE route $app->delete('/delete', function () { echo 'This is a DELETE route'; }); /* My APIs */ $app->get('/hello/:name', function ($name) { echo "Hello, " . $name; }); $app->get('/fslist/:foldername', function ($foldername) { $targetpath = "../{$foldername}"; $testexists = file_exists($targetpath); $rootdir = preg_replace('~(\\w)$~', '$1' . DIRECTORY_SEPARATOR, realpath($targetpath)) . "*"; /* foreach(glob($rootdir, GLOB_ONLYDIR) as $dir) { $dir = basename($dir); echo "Directory: $dir <br>"; $imgText = $dir."/icon.png";
<?php require '../libs/Slim/Slim.php'; require 'dbConnect.php'; require 'listsFunctions.php'; require 'itemsFunctions.php'; require 'helperFunctions.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); $app->contentType('application/json'); //PROJECTS $app->get('/projects', 'getProjects'); $app->get('/project/:id', 'getProject'); $app->post('/projects', 'addProject'); $app->put('/project/:id', 'updateProject'); $app->delete('/project/:id', 'deleteProject'); //RUNNERS $app->get('/runners/adults', 'getAllAdultRunners'); $app->get('/runners/halfmarathon', 'getSmRunners'); $app->get('/runners/cross', 'getCrossRunners'); $app->get('/runners/relay4', 'getRelay4Runners'); $app->get('/runners/relay2', 'getRelay2Runners'); $app->get('/runners/companies', 'getCompaniesRunners'); $app->get('/runners/children', 'getChildrenRunners'); $app->get('/runners/all', 'getAllRunners'); $app->get('/runner/:id', 'getRunner'); $app->post('/runners/adults', 'addRunner'); $app->post('/runners/relay2', 'addListOfRunners'); $app->post('/runners/relay4', 'addListOfRunners'); $app->post('/runners/company', 'addListOfRunners'); $app->post('/runners/children', 'addRunner');
$datos = []; foreach ($result as $producto) { array_push($datos, $producto); } echo json_encode($datos); } }); /* * Ruta para borrar productos desde el panel de administración */ $app->delete('/productos', function () use($app) { // conectar con la BD y seleccionar la colección $mongo = new MongoClient(); $database = $mongo->plazamar; $collection = $database->productos; // recoger la query string de la url pasada por backbone $req = $app->request(); $categoria = $req->get('categoria'); // recoger los productos y enviarlos de vuelta a BAckbone $cursor = $collection->remove(array('categoria' => $categoria)); echo json_encode('productos borrados'); }); /* * Ruta para obtener los usuarios de la aplicación desde el panel de administración */ $app->get('/usuarios', function () use($app) { // conectar con la BD y seleccionar la colección $mongo = new MongoClient(); $database = $mongo->plazamar; $collection = $database->usuarios; // recoger la query string de la url pasada por backbone $req = $app->request();
* Updating Person */ $data = $houses->update($info); } echo json_encode(array("status" => (bool) $data, "message" => "data updated successfully")); // echo json_encode($post); }); //Delete method to delete the data into database $app->delete('/person/:id', function ($id) use($app, $db) { /* * Fetching Person for deleting */ $person = $db->person()->where('id', $id); $data = null; if ($person->fetch()) { /* * Deleting Person */ $data = $person->delete(); } $app->response()->header('Content-Type', 'application/json'); echo json_encode($data); }); $app->post("/sendmail", function () use($app, $db) { $post = (array) json_decode($app->request()->getBody()); $email_from = $post['email']; $email_subjectr = "New Complaint"; $email_tor = '*****@*****.**'; $data; $headers3 = 'From:' . $email_from . " " . '<' . $email_from . '>' . "\r\n"; $headers3 .= 'Reply-To: ' . $email_from . "\r\n";