I'm trying to access session variables in file2.php from file1.php, but I'm getting the following error: undefined variable in file2.php.
How can I fix this?
This is file1.php:
<?php
session_start();
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Origin, Authorization, X-Requested-With, Content-Type, Accept, x-xsrf-token");
include "config.php";
$postjson = json_decode(file_get_contents('php://input'), true);
$today = date('y-m-d H:i:s');
eif(isset($postjson['aks'])=="proses_login"){
$logindata = mysqli_fetch_array(mysqli_query($mysqli, "SELECT * FROM usuario
WHERE nomeUsuario='$postjson[nomeusuario]' AND senha='$postjson[Suasenha]'"));
if(isset($logindata['nomeUsuario'])==$postjson['nomeusuario'] AND ($logindata['senha'])==$postjson['Suasenha']){
$_SESSION['U']=$postjson['nomeusuario'];
$result = json_encode(array('success'=>true, 'msgs'=>'Bem Vindo '.$_SESSION['U']));
}else{
$result = json_encode(array('success'=>false, 'msgs'=>'Nome do Usuario ou Senha incorrecta'));
}
echo $result;
}
?>
and this is file2.php:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
$host = "mysql:host=localhost;dbname=eventosonline";
$usuario = "root";
$senha = "";
$con = new PDO($host, $usuario, $senha);
$sql = $con->prepare("SELECT * FROM usuario WHERE nomeUsuario ='".$_SESSION['U']." ' ");
$sql->execute();
I tried to include file1.php but it didn't work.
Related
i try to build restAPI
when i check my code on postMan i got error that data incomplete
this is my code for create file
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once 'database.php';
include_once 'inquery.php';
$database = new Database();
$db = $database->getConnection();
$product = new Inquery($db);
$jsn = file_get_contents("php://input");
$data = json_decode($jsn);
if(
!empty($data->enqType) &&
!empty($data->title) &&
!empty($data->deptid) &&
!empty($data->enq_body)&&
!empty($data->taskPriority)
){
$t = time();
$product->enqType = $data->enqType;
$product->title = $data->title;
$product->deptid = $data->deptid;
$product->enq_body = $data->enq_body;
$product->taskPriority = $data->taskPriority;
$product->addedDate = $t;
$product->addedBy = 0;
if($product->create()){
http_response_code(201);
echo json_encode(array("message" => "Product was created."));
} else{
http_response_code(503);
echo json_encode(array("message" => "Unable to create product."));
}
}
else{
http_response_code(400);
echo json_encode(array("message" => "Unable to create product. Data is incomplete."));
}?>
this is my json file that contains what i need
{
"title" : "title1",
"enqType" : 1,
"deptid" : 3,
"enq_body" : "some text",
"taskPriority" : 1}
i try all things, i see that this code dosen't accept string
in my checks i recived this errors :
unexpected 's' in the image shared below:
So I'm trying to make an endpoint to access my database with and it works just fine in postman, but when calling the GET request on my website i get a CORS error:
Query for foreign site blocked: The same origin policy does not allow remote resource reading http://IPGOESHERE/cordova/endpoint/log.php?id=-1. (Cause: The CORS query failed).)
I've tried googling but was unable to find anything useful.
My server-sided code is in 2 files which i have included below:
models/Log.php:
class Log {
// database connection and table name
private $conn;
private $table_name = "logging";
// object properties
public $ID;
public $UserID;
public $Handling;
public $Date;
// constructor with $db as database connection
public function __construct($db) {
$this->conn = $db;
}
// read products
function read($id)
{
$query = "SELECT * FROM " . $this->table_name;
if ($id != '-1') {
// select query
$query .= " WHERE logging.ID = ".$id;
}
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
}
log.php
// required headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
header("Content-Type: application/json; charset=UTF-8");
// database connection will be here
include_once '../database.inc';
include_once '../models/Log.php';
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$id = $_GET['id'];
$database = new Database();
$db = $database->getConnection();
$Log = new Log($db);
// query products
$stmt = $Log->read($id);
$num = $stmt->rowCount();
// check if more than 0 record found
if ($num > 0) {
$products_arr = array();
$products_arr["records"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$product_item = array(
"ID" => $ID,
"UserID" => $UserID,
"Handling" => $Handling,
"Date" => $Date,
);
array_push($products_arr["records"], $product_item);
}
// set response code - 200 OK
http_response_code(200);
// show products data in json format
echo json_encode($products_arr);
} else {
// set response code - 404 Not found
http_response_code(404);
// tell the user no products found
echo json_encode(
array("message" => "No log found")
);
}
}
Turns out it was due to php not allowing me to use the class name "Log" renamed everything called log & it now works flawlessly.
I am using the crypto-js library to send some encrypted variables from angular 5 to PHP. Everything is working fine until I added the crypto-aes.php library to my php script.
ngOnInit(){
let user = "am";
let key = "pizza";
let enc = crypto.AES.encrypt(user, key);
//console.log(enc);
let dec = crypto.AES.decrypt(enc, key);
//console.log(dec.toString(crypto.enc.Utf8));
const headerOptions = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
headerOptions.set('Content-Type', 'Access-Control-Allow-Origin')
const params = new HttpParams().set('name', enc)
this.http.post('http://aff.local/test.php', params, {
headers: headerOptions
}).subscribe(
res=>{
console.log(res);
alert(res)
},
error=>{
console.log(error);
}
)
}
And here is my PHP script:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: *');
error_reporting(E_ALL);
include('./cryptojs-aes.php');
ini_set('log_errors', 0);
ini_set('display_errors', 1);
$host = "localhost";
$db = "dentist";
$user = "root";
$pass = "root";
$conn = new PDO("mysql:host={$host};dbname={$db};", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8mb4");
$enc = $_POST['name'];
$key = "pizza";
$dec = cryptoJSAesDecrypt($key, $enc);
echo $dec;
The problem is that the alerted and consoled result is null
we are programming a Restful API to be called from an ionic app. We are sending from angular service with this code:
.service('ServiceName', function($http) {
return {
borrarAlumno: function(par) {
var link = "http://localhost/ws/index.php";
return $http.delete(link, {
id: par.id
})
}
}
})
When we try to read id parameter from php we dont get anything. This is the code we are using:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$input = file_get_contents('php://input');
print_r($_SERVER['REQUEST_METHOD']);
exit();
We have tried with similar code to get parameters with PUT, GET and POST methods and it worked.
Any help would be appreciated.
Edit:
This php is called form another PHP:
class AlumnosAPI
{
public function API()
{
header('Content-Type: application/JSON');
$method = $_SERVER['REQUEST_METHOD'];
switch ($method)
{
case 'GET':
include('get.php');
break;
case 'POST':
include('post.php');
break;
case 'PUT':
include('put.php');
break;
case 'DELETE':
include('delete.php');
break;
default:
echo 'NOT SUPPORTED';
break;
}
}
}
Edit 2: full code of delete.php
if (isset($_SERVER['HTTP_ORIGIN']))
{
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
{
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$valor['borrado'] = 0;
include('conexion.php');
$id = "";
//parse_str(file_get_contents('php://input'), $delete);
$input = file_get_contents('php://input');
print_r($input);
exit();
foreach (array_keys($delete) as $key)
{
$$key = $delete[$key];
}
if ($id != "")
{
//PREPARAMOS LA SENTENCIA SQL
$sql = "DELETE FROM Alumnado WHERE `ID`=?";
$resultado1=$conexion->prepare($sql);
$resultado1->bind_param('i', $id);
$resultado1->execute();
$valor['borrado'] = $resultado1->affected_rows;
}
$datos=json_encode($valor);
echo $datos;
Angular doesn't send a request body for DELETE so you're going to have to read id from the URL.
.service('ServiceName', function($http) {
return {
borrarAlumno: function(par) {
var link = "http://localhost/ws/index.php";
return $http.delete(link, {
params : {id: par.id}
})
}
}
})
get the id via $_GET['id'] instead of file_get_contents('php://input');
I am developing a hybrid application using Ionic Framework. I am using $http Restful web service to POST data into my server and get the response from server. When I test it in browser, it works well and I able to retrieve data from serve. But when I test it in my android device, it does not work at all. The following is my code.
Angularjs Code
$scope.validateBorrower = function(){
employeeNumber = $scope.assetBorrowing.employeeNumber;
employeeName = $scope.assetBorrowing.employeeName;
employeeDeparment = $scope.assetBorrowing.employeeDepartment;
if(employeeNumber == null && employeeName == null){
alert("Please Enter Employee Number or Employee Name");
}else{
$http({
url: "http://131.4.44.69/php3/validateBorrower.php",
method: "POST",
data: {
'employeeNumber': employeeNumber,
'employeeName' : employeeName
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response) {
alert("Valid Employee");
$scope.assetBorrowing.employeeNumber = response[0].employeeNumber;
$scope.assetBorrowing.employeeName = response[0].employeeName;
$scope.assetBorrowing.employeeDepartment = response[0].employeeDepartment;
$scope.borrowbtn = false;
}).error(function(response) {
alert("error");
});
alert(employeeNumber);
}
}
PHP Backend Code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: false");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('P3P: CP="CAO PSA OUR"');
header("Content-Type: application/json; charset=utf-8");
$postdata = file_get_contents("php://input");
$employeeRequest = json_decode($postdata, true);
#$employeeNumber = $employeeRequest['employeeNumber'];
#$employeeName = $employeeRequest['employeeName'];
if(empty($employeeNumber)){
#$employeeName = $employeeRequest['employeeName'];
}else{
#$employeeName = "";
}
$db_host = "localhost";
$db_user = "jack";
$db_password = "1234";
$db_database = "daikin_asset_management";
$conn = new mysqli($db_host, $db_user, $db_password, $db_database);
if($conn->connect_error){
echo "Connection Problem";
}
if(empty($employeeNumber) && empty($employeeName)){
echo "Error";
}else{
$getUserQuery = "SELECT * FROM xpouser WHERE (username='$employeeName') OR (employee_no = '$employeeNumber') ";
$getUserRetval = $conn->query($getUserQuery);
$userRow = mysqli_fetch_array($getUserRetval);
$employeeName = $userRow['username'];
$employeeNumber = $userRow['employee_no'];
$employeeDepartment = $userRow['department'];
$_arr = array();
$array = array(
'employeeNumber' => $employeeNumber,
'employeeName' => $employeeName,
'employeeDepartment' => $employeeDepartment
);
$jsonObjectChannel = json_encode($array);
$jsonObjectChannel = "[" . $jsonObjectChannel . "]";
echo $jsonObjectChannel;
}
?>
I figure it out by myself. Is because of I never add few permissions in my android Manifest file. I have to include this 3 permissions in my android manifest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Next, I have to include cordova-whitelist plugin and add this into my config.xml
<access origin = "http://example.com" />
<allow-navigation href = "*://*.example.com/*" />