how to get body of erquest with method PATCH using PHP? - php

I built an API to update table a table in SQL,
I tried get with $_PATCH but doesn't work!
<?php include_once('data.php') ?>
$method= $_SERVER['REQUEST_METHOD'];
if ($method=='PATCH')
{
if(isset($_POST['id']) && isset($_POST['nom']) && isset($_POST['prenom']) ){
$id = $_POST['id'];
$nom = $_POST['nom'];
$prenom = $_POST['prenom'];
if (!empty($id) && !empty($nom) && !empty($prenom)) {
$sql = 'UPDATE formateur SET nom=? , prenom=? where id=?';
$sqlState = $pdo->prepare($sql);
$inserted = $sqlState->execute([$nom,$prenom,$id]);
if($inserted ){
echo 'gooood';
}else{
http_response_code(400);
}
}else{
http_response_code(400);
}
}else{
http_response_code(400);
}
}else{
http_response_code(400);
}
?>
But I couldn't get the body of request with PATCH method!?
any help would be really appreciate!

Related

Angular Post api with php sends query successfuly but doesnt reach .subscribe code

Angular Post api with php sends query successfuly to the data base but doesnt reach .subscribe code after that :
Here is my code in my comp:
postdata(data:any)
{
this.DataService.Userregister(data).subscribe(data=>{console.log('success');})
};
and here is php code :
<?php
include_once("db_connection.php");
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
$request =json_decode($postdata);
$email = trim($request->email);
$password = trim($request->passw);
$username =trim($request->name);
$fname =trim($request->fname);
$sql = "INSERT INTO users (Email,Passw,u_name,fname)
VALUES ('$email','$password','$username', '$fname') ";
if( $conn->query($sql)===TRUE)
{
$res = "Success";
echo json_encode($res);
}
else{
$res = "Faild";
echo json_encode($res);
}
}
?>

why i cant get the json from this scrip in php using alamofire?

i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}

POST data to php api

I am new to PHP and SQL coding and have been trying to POST data to my database, but when using Postman to check responses I get my else response and I really don't know why because my POST data is exactly what is needed.
Here is a screenshot
Thank you very much for helping me out!
As per request here is the code
<?php
require("../database_android.php");
if(isset($_POST["package_name"]) && $_POST["package_name"] != "") {
$package_name = mysql_real_escape_string($_POST["package_name"]);
} else {
echo "package_name missing";
return;
}
if(isset($_POST["app_name"]) && $_POST["app_name"] != "") {
$app_name = mysql_real_escape_string($_POST["app_name"]);
} else {
echo "app_name missing";
return;
}
if(isset($_POST["activity"]) && $_POST["activity"] != "") {
$activity = mysql_real_escape_string($_POST["activity"]);
} else {
echo "activity missing";
return;
}
if(isset($_POST["activity_name"]) && $_POST["activity_name"] != "") {
$activity_name = mysql_real_escape_string($_POST["activity_name"]);
} else {
echo "activity_name missing";
return;
}
if(isset($_POST["component_info"]) && $_POST["component_info"] != "") {
$component_info = mysql_real_escape_string($_POST["component_info"]);
} else {
echo "component_info missing";
return;
}
$application_id = already_exists_application($package_name);
if($application_id < 0) {
mysql_query("INSERT INTO androidactivities_application (package_name, app_name) VALUES ('". $package_name ."', '". $app_name ."')");
$application_id = already_exists_application($package_name);
}
$componentinfo_id = already_exists_componentinfo($application_id, $component_info);
if($componentinfo_id < 0 && $application_id > 0) {
mysql_query("INSERT INTO androidactivities_componentinfo (application_id, activity, activity_name, component_info) VALUES ('". $application_id ."', '". $activity ."', '". $activity_name ."', '". $component_info ."')");
echo "successful";
} else {
echo "exists";
}
?>
<?php
function already_exists_application($package_name) {
$result = mysql_query("SELECT * from androidactivities_application WHERE package_name = '".$package_name."'");
if($row = mysql_fetch_object($result)) {
return $row -> application_id;
}
else {
return -1;
}
}
function already_exists_componentinfo($application_id, $component_info) {
$result = mysql_query("SELECT * from androidactivities_componentinfo WHERE application_id = '".$application_id."' AND component_info = '".$component_info."'");
if($row = mysql_fetch_object($result)) {
return $row -> componeninfo_id;
}
else {
return -1;
}
}
?>
Please post your data in Body tag as form data in postman. the way you are sending it gose like this ApiURL?param1=value1&param2=value2
see this image : https://pasteboard.co/JJt9RB4.png

Condition to Skip Input field if Empty

I'm trying to set a condition wherein if the 'filefield' is empty, it will skip the insert in DB as it is only an option and just proceed in inserting of 'name' and 'description' in the DB, which will never be empty.
<?php
include("connection.php");
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
if ($name == '' || $description == '' )
{
$error = 'ERROR: Please fill required fields!';
renderForm($name, $description);
}
else
{
if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{
echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}
$path=md5(microtime()).'.'.$ext;
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>
I'm not sure how to proceed with the condition. Any help is highly appreciated.
First, close off all of your logic, including if(move_uploaded_file), so that the $query is competely outside of any conditionals. Then it's just a matters of checking whether the filefield was filled out or not. If it's not empty, your $query insert all three fields. If it is, your $query only inserts $name and $description.
This can be seen in the following (heavily cut-down) code:
/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}
/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);

How to verify any email with php

I am working with a form. Where user enters their email, I can validate the email through regex. But what I need is like this. After searching, I found a solution here. The as it checks the MX record of the email. But still it does not work for me fine, because when I gave a rough email like : ahhhhhhhhhhhhhhhhh#yahoo.com my form accepted it, and when I gave the same email on the other website, it rejected the email. It might be the problem with my logic I don't know, below is my code where I am verifying the email.
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL)) {
echo "email_prb";
} else{
$sl = "SELECT * FROM fb_data WHERE useremail = '$_email' OR fbappid = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO fb_data VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
Kindly Use mysqli or Pdo.. your code is vulnerable to sql injection, try to add mysql escape. but i have rewritten your PHP below without changing query.
Filter validate email will check for the correct email format, so you dont need checking for #. but if you filter the #example.com you need a custom filter for that.
<?php
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if((!domain_exists($_email)) && (!filter_var($_email, FILTER_VALIDATE_EMAIL))) {
echo "email_prb";
} else{
$sl = "SELECT * FROM `fb_data` WHERE `useremail` = '$_email' OR `fbappid` = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO `fb_data` VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
?>
on this part of your code
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL))
change the "OR" to ||. Like this
if(!domain_exists($_email) || !filter_var($_email, FILTER_VALIDATE_EMAIL))

Categories