Getting Blank record for this code - php

Look at this code, i am getting empty record in database.
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
this line not giving first name but it gives blank value not the value that i am trying to insert into the database.
whats wrong in this code?
create.php
<?php
include_once('confi.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$firstname=isset($_POST['firstname'])?mysql_real_escape_string($_POST['firstname']):"";
$lastname=isset($_POST['lastname'])?mysql_real_escape_string($_POST['lastname']):"";
$email=isset($_POST['email'])?mysql_real_escape_string($_POST['email']):"";
$password=isset($_POST['password'])?mysql_real_escape_string($_POST['password']):"";
$status=0;
$query = "INSERT INTO users (firstname,lastname,email,password,status) VALUES ('$firstname','$lastname','$email','$password','$status')";
$insert = mysql_query($query);
if($insert)
{
$data=array("result"=>1,"message"=>"successfully added!");
}
else
{
$data=array("result"=>0,"message"=>"Error!");
}
}
else
{
$data=array("result"=>0,"message"=>"Request Method is Wrong!");
}
mysql_close($conn);
/* JSON Response */
header('Content-type: application/json');
echo json_encode($data);
?>
confi.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('tuts_rest', $conn);
?>

Add the following lines in your php file and remove header access you have already added
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, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

Related

Simple Rest API Account creation

I am trying to build Simple Rest api for my php website but i am having issue on creating the account
create.php
<?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 'data.php';
$database = new Database();
$db = $database->getConnection();
$item = new emmanuel_api($db);
$item->user_name = $_GET['user_name'];
$item->user_pass = $_GET['user_pass'];
$item->user_email = $_GET['user_email'];
$item->full_name = $_GET['full_name'];
if($item->createUsers()){
echo 'Account created successfully.';
} else{
echo 'Account could not be created.';
}
?>
I think i am getting error on my Create.php please help me to resolve this issue
Also how i can convert this user_pass into MD5
Thanks

Origin http://localhost:xxxx is not allowed by Access-Control-Allow-Origin

I'm trying to fetch some data from my mySQL DB stored on 000webhost, and Ionic show me that error message:
I've read that I need to enable CORS policy, but don't understand on where I should.
That's the fetch_data.php code:
<?php
require 'config.php';
$query = "SELECT lat, lng FROM gps WHERE id = (SELECT MAX(ID) FROM gps)";
$result = mysqli_query($con, $query);
if($result === FALSE) {
printf("Error: %s\n", mysqli_error($con));
}
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array(“lat”=>$row[0],“lng”=>$row[1]));
}
echo json_encode(array($response));
?>
add to index.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');

non information inserted in my database from my flutter app but the app run well

I've a problem in may flutter app that i made a PHP code to insert a user in my 00webhost database ,the app run well and return: {seccess register,1 }b
ut non information inserted in my data base any help please
the PHP code is:
<?php
include "db.php";
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$name=$_POST['name'];
$email=$_POST['email'];
$pass=sha1($_POST['password']);
try {
if (isset($name,$email,$pass)) {
$req=$db->prepare("INSERT INTO users values(null,?,?,?)");
$req->execute(array($nme,$email,$pass));
if($req){
$secces=1;
$msg="seccess register";
}else{
$secces=0;
$msg="error register";
}
}else{
$secces=0;
$msg="error Empty Data";
}
} catch (\Throwable $th) {
$msg ="error: ".$th ->getMessage();
}
echo json_encode([
"result"=>[
$msg,
$secces
]
]);
?>
now in the code below it always show me this:{data: [email alredy excist, 0]}
but there are nothing in the table user in my database:
<?php
include "db.php";
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$name=$_POST['name'];
$email=$_POST['email'];
$pass=sha1($_POST['password']);
try {
if (isset($name,$email,$pass)) {
$req=$db->prepare("SELECT * from users where email=?");
$req->execute(array($email));
$exist = $req->rowCount();
if($exist=0){
$req=$db->prepare("INSERT INTO users values(null,?,?,?)");
$req->execute(array($nme,$email,$pass));
if($req){
$secces=1;
$msg="seccess register";
}else{
$secces=0;
$msg="error register";
}
}else{
$secces=0;
$msg="email alredy excist";
}
}else{
$secces=0;
$msg="error Empty Data";
}
} catch (\Throwable $th) {
$msg ="error: ".$th ->getMessage();
}
echo json_encode([
"result"=>[
$msg,
$secces
]
])
?>
?>

How to delete record from table using Angular http.delete with PHP backend?

I am trying to delete a record from the database table using Angular on frontend and PHP on the backend. I am passing the id through URL and trying to get it back with $_GET['id'] but it doesn't work (no error in console).
PHP API:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: DELETE");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
require_once("includes/initialize.php");
$db = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbdatabase) or die('Could not connect to database');
$data = json_decode(file_get_contents("php://input"));
$id;
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
// update the ECD
if(ECD::deleteECD($id)){
echo '{';
echo '"message": "The center was deleted."';
echo '}';
}
// if unable to update the ECD, tell the user
else{
echo '{';
echo '"message": "Unable to delete the center."';
echo '}';
}
And Angular http.delete:
deleteCenter (id: number): Observable<{}> {
const url = `${this.D_ROOT_URL}${id}`;
return this.http.delete(url);
}
I tested the URL to make sure it's passing the correct URL.
The delete() method returns a cold observable, which means that the HTTP request is not sent until someone subscribes to the observable. You should write this:
return this.http.delete(url).subscribe();

$_SESSION exists, but is empty. Why?

I have logged mu user (in login.php) and start session, before redirect to another page (accueil.php)/
In login.php : My Session exists, my cookies exists.
In accueil.php : My Session exists, my cookies doesn't exists.
==> I started my Session at the top of my second page./
==> I tried different way to use Location in vain :
header('Location: http://localhost/monsite/accueil.php');/
OR
header('Location: accueil.php');
==>Anyway : it returns "undefined index username".
I don't understand. Have you any ideas please?!
Here is my code :
Login.php :
$username = $_GET['username'];
$password = $_GET['password'];
$sql = $connection->query("SELECT username, password FROM login WHERE username = '$username' && `password`= '$password';");
while ($result = $sql->fetch()){
$data = array('username' => $result['username'],
'password' => $result['password']);
}
try{
if($data['username'] !== $username && $data['password'] !== $password ) {
throw new Exception('Login incorrect', 500);
}
else{
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
setcookie('maSession', $_SESSION['username'], time()+3600 , '/');
header('Location: http://localhost/monsite/accueil.php');
}
}
catch(Exception $e){
header("HTTP/1.1 500 Internal Server Error");
echo 'error: '.$e->getMessage();
}
Accueil.php :
``
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
if(isset($_SESSION)) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
->var_dump($_SESSION) : returns empty array.
->$_SESSION['username'] : returns undefined index undername.
Thank you !
Try
<?php
//Check session if not already started, then start it.
if(session_id() == '')
{
session_start();
}
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
include_once('accueil.php');
require_once('db.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$connection = new PDO("mysql:host=$HOST;dbname=$DBNAME", $USER, $PASS);
// Check session 'username' it was not empty
if(!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
echo $username;
}
else{
echo 'no session';
}
}
?>

Categories