I have to create an API in PHP, which I have never done before. I have a index.php in my root folder which contains a form. A button click activates an AJAX Request to read all entries and a form can be filled out to send data. I will also have DELETE and update.
ajaxcall.js
// GET to retrieve
var req;
req=new XMLHttpRequest();
req.open("GET", 'src/api/v1/posts',true);
req.send();
//post with ajax
$.ajax({
type:"POST",
url: "src/api/v1/posts",
data: test,
ContentType:"application/json",
success:function(){
alert('successfully posted');
},
error:function(){
alert('Could not be posted');
}
});
I have a folder src/api/v1 in there I want the endpoint file api.php which handles the different requests. I now need all the AJAX calls to be resend to api.php which sits inside that v1 folder. I created an .htaccess which is stored in also stored in src/api/v1. I added the following:
.htaccess
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule src/api/v1/(.*)$ src/api/v1/api.php?request=$1 [QSA,NC,L]
Unfortunately I get a 404 not found, it just does not seem to re-write the URL to the api.php so it is looking for /posts which does not exists. What am I doing wrong?
Actually you should store the .htaccess on the root directory, otherwise Apache will not know that there's an .htaccess under /src/api/v1, so apache will look for the directory src/api/v1/posts and as is it's not found a 404 error will be returned.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule src/api/v1/(.*)$ /src/api/v1/api.php?request=$1 [QSA,NC,L]
</IfModule>
Related
I am writing a laravel api and when I try to make delete and post requests I keep getting a method not allowed exception. Where should I be looking to diagnose this problem?
I have read though most of the other posts on this issue and here is what I have tried/looked at.
• Made sure the route syntax was correct
• Made sure it didn't conflict with another route
• Made sure I was using the correct route (ran php artisan route:list to
double check)
• Modified the .htaccess folder (maybe I did this incorrectly) to allow GET, POST, PUT, DELETE
Here is what the route looks like in api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::delete('delete/{id}', 'LoginController#delete');
Route::get('stuff', 'LoginController#index');
Route::get('stuff1/{Username}', 'LoginController#show');
here is the function in the controller
public function delete(Request $request, $id) {
$user = Login::find($id);
$user->delete();
return "204";
}
here is my .htaccess
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
</IfModule>
I can get around this issue by changing Route::delete() to Route::get() and achieve the same functionality but this doesn't seem like standard practice.
You have to set ajax type POST but send a parameter named _method with value delete like this:
$.ajax({
type: "POST",
data:{
_method:"DELETE"
},
url: productRoute,
headers: { 'X-CSRF-TOKEN' : productToken }
});
Or because you use laravel html form helper so it generates _method hidden input automatically so you'd better send all your form inputs such as token and method like this:
function()
{
var formData=$('#yourForm').serialize();
$.ajax({
type: "POST",
url: productRoute,
data:formData
})
});
I started an app based on Angular.js and Silex for the server side.
I would use real URL (without hash) but it's not working.
I have activate pushstate on angular with the following line :
$locationProvider.html5Mode(true);
but I don't know how to configure server. Actually when I try to access to localhost/test angular did nothing but silex said : *No route found for "GET /test" ..
my htaccess is like it :
<IfModule mod_rewrite.c>
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteBase /web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) index.php [L]
Structure of my project is Like it
|--app/
|----app.php
|----controllers/
|-------MainController.php
|--web/
|----index.php
|----js/
|---------app.js
...
Thanks you for your help
edit :
route declaration :
config(['$routeProvider, $locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/test',{
templateUrl : '/cuisine',
controller : 'CookController'
});
}
I am using this on my site, and its working , please give it try. Otherwise i suggest you turn on mod_rewrite logging in apache and look to logs
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ /index.html
Your problem is with RewriteBase. The rewrite base is based on URI folder and you're requesting /test not /web/test, so your rewrite base should be /
I'm just guessing but I think your document root is /path/to/your/project/web (it should be this, only the web directory is meant to be public!) so your .htaccess shouldn't have the RewriteBase on your case.
It's my first upload to a remote server of a Laravel site.
Local I have configured a vhost so my access to my site is like:
site.domain.com //it's pointing htdocs/laravel-proyect/public
I have uploaded my site to my remote server, then:
Change permisions on storage and all its directories
Change permisions to bootstrap
Change configuration of app.php
'url' => 'http://site.domain.com',
Change configuration in database.app with new parameters (as well as in email.php)
Load all tables and data in the data base
Then I try to load my site and get a 500 Internal Server Error
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
It works a little, I have this code in routes.php:
// Begins in the login view
Route::get('/', function()
{
if (!Sentry::check()) {
$data = array();
if (Session::has('email')) {
$data = array('email' => Session::get('email'));
}
return Redirect::route('login', $data);
}
else
return Redirect::route('users');
});
/ ========================================
// LOGIN, LOGOUT AND ACTIVATION SECTION ==========
// // ============================================
// show the login page
Route::get(MyHelpers::textLang('login','routes'), array('as' => 'login', function()
{
if (Sentry::check())return Redirect::route('users');
else {
$rules = User::$rules_login;
// show the login page (app/views/frontend/login.blade.php)
return View::make('frontend.login', compact('rules'));
}
So at first time mo url look like:
site.domain.com/entrar
'entrar', (login in spanish), y set by MyHelpers::textLang('login','routes'), access to my class MyHelpers and to lang files to translate 'login' in to 'entrar', but dont load the template.
Begins to :
Read documentation, making some changes: deleting Multiviews from
.htaccess (deprecated), adding RewriteBase to .htaccess too.
Copy /public content to base dir and change paths in bootstrap/paths and
in the index.php files.
Reinstall in two remote servers to verify is not my provider failing (same error). Talking to my provider, supouse
there are no errors on the server.
I create a new htaccess in the base dir redirecting routes to /public.
Try with php 5.4, 5.5 and 5.6
Actually my .htaccess is:
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
And I have no more ideas and cant find other solutions as related here.
Any idea? Please, I'm getting crazy, on wensday I have to beguin a new proyect and still working with this one.
Thanks
I have to add
RewriteBase /
to the .htaccess
I have a demo laravel application on heroku Simple Blog.My .htaccess file is:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
#other lines for gzip
It seems that there is no issue with your .htaccess file. It may be problem with you code logic. If you are getting no error with same code on localhost, then check your config again. For laravel 4, there is already a similar issue on stackoverflow Laravel 4 Virtual Host and mod rewrite setup
Note that laravel 5 (if you are using it) takes input (database connection and other setting) from .env file.
If you are still getting error then try to send simple response on index page like:
Route::get('/','basic configurations are correct');
and then make it complex step by step. It will help you in finding error.
Answer from #kikerrobles really works.
your final .htaccess file should look like following
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteBase /
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
I have a PHP program written on code igniter that needs your help! Have been trying for 3 weeks!
I have the htaccess mod rewrite to make http://www.sampleurl.com/controllername instead of http://www.sampleurl.com/index.php/controllername
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 /index.php
</IfModule>
I have a controller for Dashboard (currently used for testing the session.)
public function index()
{
$is_logged_in = $this->session->userdata('fb_session');
$data = array(
'fb_data' => $is_logged_in,
);
if (!isset($is_logged_in) || $is_logged_in != true){
redirect('/error');
}
}
Below is the function that suppose to kill the current session and redirect to dashboard page.
$('#logoutbtn').click(function(){
$.ajax({
type:"POST",
url: "/fbcontroller/killsession",
datatype: "json",
success: function(){
alert("Logout");
}
});
});
public function killsession(){
$this->session->sess_destroy();
redirect('/dashboard');
}
Problem 1: as I redirect from function in 1 controller to another, the redirection fails here. Instead of directing to dashboard, the firebug displays 404 error, page not found. And in the response, it displays all the HTML code of /error page. Does it mean that the redirection works? If yes, why wouldn't it display on browser?
Problem 2: session destroyed, but logged in page stays even as I refresh (F5).
For htaccess I suggest:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\?*$ index.php/$1 [L,QSA]
And know that when you kill session CI will create a new 1 on your next Page load (in your case on the redirect) .. Session isn't just for user logins.
Don't forget at app/config/config.php to set
$config["index_page"] = '';
Problem solved
I'm using friendly url and code which is described below. I want to Request php file with ajax post. Does anybody know how to do that?
For example: I have code below:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "ajax/test.php",
data: "data=test",
success:function(data){
alert(data);
},
});
});
When program post data to test.php file then i want to also return data from this file.
Url: http://mysite.com/admin/admin.php?m=users&a=edit&id=12
User Friendly Url: http://mysite.com/admin/users/edit/12
Problem solved
I am confused what you are asking about. I will assume that you just want to return some data from test.php.
if so then assuming your $data variable holds all the data, you can do this
echo json_encode($data);
and that should alret you back the data as you have it in your code
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteBase /directory_path/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1
</ifModule>
That's .htaccess file for user friendly url.
Thanks for help!