error 404: while deploying slim framework rest API on plesk shared hosting - slim

I need help, while deploying slim framework on plesk shared hosting below mentioned issue is coming up.
actually it is working fine at local wamp server.
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
here is my code.
index.php:
require '../vendor/autoload.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400');
$config = ['settings' => [
'addContentLengthHeader' => true,
'displayErrorDetails' => true
]];
$app = new \Slim\App($config);
require '../src/routes/hostUser.php';
require '../src/routes/user.php';
$app->run();
hostUser.php:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\Message;
include_once 'Database.php';
var_dump($app);
$app->get('/loadprofile', function (Request $request, Response $response) {
$user_email = $_GET['emailid'];
$userid = $_GET['usertypeid'];
$database = new Database();
$db = $database->getConnection();
try {
$stmt = $db->prepare("SELECT * FROM user_details WHERE userid='".$userid."' AND email='".$user_email."'");
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
return json_encode($res);
$db = null;
} catch(PDOException $e){
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
The control reached till var_dump($app) but it is not executing loadprofile service.
enter image description here

Related

Zf2 - How to create request to external API with file upload

I have a Zf2 application that communicates with another Zf2 application through RestAPI calls.
I'm able to communicate between one to another using following code and exchange parameters:
//Prepare request
$request = new Request();
$request->getHeaders()->addHeaders(array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
));
$request->setUri($p_url);
$request->setMethod('POST');
$request->setPost(new Parameters($p_params));
$client = new Client();
//Send request
$client->resetParameters();
$response = $client->dispatch($request);
$data = json_decode($response->getBody(), true);
Now, I would like to do the same thing but with a multipart call: Json + files.
How can I do that?
I have tried several solutions from using setFileUpload method of client to writing headers parameters with content-type (multipart/form-data), content-disposition, ... without success.
Along my tests, I used Wireshark to check the request contents. Depending on the solution I tried, I fail in situation with "missing boundary" or HTTP error 405.
Thanks for your help.
Best
Finally, I found a solution
$this->_client->setUri($p_url);
$this->_client->setMethod('POST');
//Prepare for upload
$this->_client->setFileUpload($p_file, 'file');
//Set parameters along with file
$this->_client->setParameterPost($p_params);
//Send request
try {
$response = $this->_client->send();
} catch ( \Exception $ex ) {
}

Fatal error: require_once(): Failed opening required ... Novice programmer, appreciate any guidance

I'm a novice in server-side programming so any advice is appreciated.
I have some PHP files uploaded on a virtual server (000webhost.com) and I'm having trouble with locating a file I'm requiring in another PHP file. The register.php is attempting to "require_once" the update_user_info.php
Here's the code for register.php (Which I've taken from a tutorial and adjusted it with my variables):
<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'../update_user_info.php');
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST ['password']) && isset($_POST['branch']) && isset($_POST['gender'])) {
// receiving the post params
$username = $_POST['username'];
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$branch = $_POST['branch'];
$gender = $_POST['gender'];
// check if user is already existed with the same email
if ($db->CheckExistingUser($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->StoreUserInfo($username, $name, $email, $password, $branch, $gender);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["branch"] = $user["branch"];
$response["user"]["gender"] = $user["gender"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter (username, name, email or password) is missing!";
echo json_encode($response);
}
?>
And here's a screenshot of the error that's occurring when attempting to visit the link containing the register.php:
Screenshot of the error
What I've tried so far:
1- tried to use require_once __DIR__."/../filename.php"; and lots more of the same, basically tinkering the statement with different language constructs and constants.
2-Read tutorials on the correct way to use require once but their cases is almost always very different. Either they are using WAMP/XAMPP -meaning they have a local path not a virtual one- So no luck there.
3- tried to change .htaccess file, as someone said in a post that it solved his problem.
4- I'm certain that both files are uploaded to the same directory. Yet it says "No such file".
Does anyone have an idea of where the error could be stemming from? Thanks in advance!

How to send form data in slim framework v3 in PUT routing

I am very new in slim framework and i am using slim V3 i have done post route and it works fine but when i try to update record with put method it will works with Content-type = application/x-www-form-urlencoded and update my record with success
when i try to send file into slim api with POSTMAN Chrome Extension it will not sending file with form data request.
Here is my code
$app->put('/message/{message_id}', function ($request, $response, $args)
{
$imagePath = '';
$data = $request->getParsedBody();
$files = $request->getUploadedFiles();
$file = $files['file'];
if ($file->getError() == UPLOAD_ERR_OK ) {
$filename = $file->getClientFilename();
$file->moveTo('assets/images/'.$filename);
$imagePath = 'assets/images/'.$filename;
}
$message = Message::find($args['message_id']);
$message->body = $data['message'];
$message->user_id = $data['user_id'];
$message->image_url = $imagePath;
$message->save();
if ($message->id) {
return $response->withStatus(200)->withJson([
'message_id' => $message->id,
'message_uri' => '/message/'.$message->id,
]);
}else{
return $response->withStatus(400)->withJson(['message'=>'something went wrong!']);
}
});
When you want to upload a file with postman you need to remove or disable the Content-Type inside the header.

Guzzle returning a 404 on a valid URL

I'm using Guzzle with CurlAuthPlugin to authenticate. When I run the code, I get
Client error response\ [status code] 404\ [reason phrase] Not Found\ [url] https:\/\/api.buto.tv\/v2\/video\/tag\/v2\/video\/tag\/
The code I'm using is:
$client = new Client(<URL>);
// Add the auth plugin to the client object
$authPlugin = new CurlAuthPlugin(<APIKEY>, 'x');
$client->addSubscriber($authPlugin);
$response = $client->get('v2/video/tag/')->send();
But the URL is perfectly valid a I can paste that in to a browser and it works fine
I've also tried:
$client = new Client('https://api.buto.tv');
$request = $client->get('v2/video/tag/');
$request->setAuth('user', 'pass');
$response = $request->send();
But I get the same error. I have output the URL it's requesting with echo $request->getUrl(); and if I copy and paste the URL in to a browser, the URL is fine
I think you may be missing a slash '/' after api.buto.tv, so the url is resolving to 'https://api.buto.tvv2/video/tag/' instead of 'https://api.buto.tv/v2/video/tag/'.
$client = new Client('https://api.buto.tv/');
$request = $client->get('v2/video/tag/');

cURL throws an exception at Facebook API SDK

I'm trying to post an image as the user from my Facebook application.
Currently, this feature is still under development, and when I'm trying to test it using WAMP server on localhost, one of the cURL functions in the Facebook API SDK class, throws an exception error:
{"error_code":60,"error":{"message":"SSL certificate problem, verify
that the CA cert is OK. Details:\nerror:14090086:SSL
routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify
failed","type":"CurlException"}}null0.90752005577087
145684992172054|e259ec293812a5276a61d3181c395077
I have checked, and I have the correct settings at php.ini both at the Apache and PHP directories.
I tried to run this Both on Easy PHP with PHP 5.4 and on WAMP with PHP 5.3. (cURL extension enabled).
I have open SSL installed on both of the local servers.
I understand that you can solve this by changing the configuration of the CURL_opt, but modifying a Facebook base class, and compromising the security of my application (middle man attack), is really a last resort for me.
Thanks in advance for any help!.
My code:
test.php:
<?php
session_start();
require 'FB_auth.php';
require 'includes.php';
require 'functions_fb.php';
$start = (float) array_sum(explode(' ',microtime()));
//echo json_encode(photoToFacebook(299, 402, 134));
// echo json_encode(photoToFacebook(724, 402, 165));
// postToFacebook($db, 402, 134);
$end = (float) array_sum(explode(' ',microtime()));
$duration = ($end-$start);
echo $duration;
echo "<br/>" . $facebook->getAccessToken();
?>
functions_fb.php
<?php
function photoToFacebook($hr_id, $user_id, $job_id){
global $db, $FEED_PATH, $JOB_IMAGES_FOLDER , $facebook;
$path = $_SERVER['DOCUMENT_ROOT'] . "/";
$JOB_IMAGES_FOLDER = "images/job_images/";
$company = $db->getCompany($hr_id);
// perapre the job photo.
$photo = $db->getJobPhoto($job_id);
if (empty($photo)){
$photo = $db->getLogo($hr_id);
}
else{
$photo = $JOB_IMAGES_FOLDER . $photo;
}
try{
// At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
// Get album id if exists.
$album_uid = $db->getAlbumId($user_id);
$fb_user_id = $db->getFBUserId($user_id);
if (empty($album_uid)){
// Create an album
$album_details = array(
'message'=> 'Check out my company\'s job opportunities',
'name'=> "Job opportunities at {$company}"
);
$create_album = $facebook->api("/{$fb_user_id}/albums", 'post', $album_details);
echo json_encode($create_album);
$album_uid = $create_album["id"];
$db->saveAlbumId($user_id, $create_album["id"]);
}
$job_title = $db->getJobTitle($job_id);
$link = Bitly::make_bitly_url($FEED_PATH . "show_job.php?jid={$job_id}&th_uid={$user_id}&tp=1&pc=1", BITLY_APP_USERNAME,BITLY_APP_KEY,'json');
$photo_details = array(
'message'=> $job_title . "!\n" . $company . " is looking for you.\nOpen the link for details and apply.\n" . $link
);
$path .= $photo;
$photo_details['image'] = '#' . $path; //realpath($file);
// echo $album_uid;
$upload_photo = $facebook->api("{$fb_user_id}/photos", 'post', $photo_details);
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($upload_photo));
// $db->updateAutoPostJob($job_id, $user_id);
return $upload_photo;
}
catch (FacebookApiException $e) {
echo "error:" . json_encode($e->getResult());
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($e->getResult()));
// AtavMail::SendRichedMail(null , "", "Error on auto process - posting photo to FB", "Where - Job Id: {$job_id} , User Id: {$user_id}", json_encode($e->getResult()));
}
}
?>
I solved this by adding the following line into the base_facebook.php file:
public static $CURL_OPTS = array(
//
//
//
CURLOPT_SSL_VERIFYPEER => false,
);
Please notice that this is an development - environment solution only, and using this on your actual application can cause a security risk.
Please take the time to review the fullp proper solution on this link:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Setting SSL verification to false defeats the purpose of SSL.
A proper solution is to set the CA certs for CURL.
Solution 1 (Changes to PHP.ini):
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Open your php.ini
Set the curl.ca_info options to point to the location of the cacert.pem
Example: curl.ca_info="C:\xampp\cacert.pem"
Restart Apache
Solution 2 (Set options before each CURL call)
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Write the following code:
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "pathto\cacert.pem");
Source: http://tumblr.wehavefaces.net/post/52114563111/environment-windows-xampp-curl-library