How to search and remove specific position from array object? [duplicate] - php

This question already has answers here:
How to filter a two dimensional array by value
(6 answers)
Closed 16 days ago.
I would like to search something in array of objects and remove the array position. For example, follow the array:
$audits = [{"old_values":[],"new_values":[],"event":"updated","auditable_id":"440","auditable_type":"App\\Models\\User","user_id":"433","user_type":"App\\Models\\User","url":"http:\/\/protocolo-online2\/logout?","ip_address":"127.0.0.1","user_agent":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/102.0.0.0 Safari\/537.36","tags":"","created_at":"2023-02-01 09:55:00","login":"mailson.suporte"},{"old_values":{"ultimo_login":"2023-02-01 09:32:16"},"new_values":{"ultimo_login":"2023-02-01 09:55:10"},"event":"updated","auditable_id":"440","auditable_type":"App\\Models\\User","user_id":"440","user_type":"App\\Models\\User","url":"http:\/\/protocolo-online2\/login?","ip_address":"127.0.0.1","user_agent":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/102.0.0.0 Safari\/537.36","tags":"","created_at":"2023-02-01 09:55:10","login":"mailson.suporte"}]
I tried to do this code:
if (($k = array_search(440, array_column(json_decode($audits, true), 'user_id'))) !== false) {
unset($audits[$k]);
}
But this way is not working!
I can do using foreach, this way:
foreach ($audits as $index => $audit) {
if($audit->user_id == 440){
unset($audits[$index]);
}
}
However if the array is start to grow up, I think that foreach is not a good method for this case.
Someone can help me?

I've had to write the array in php to make it work. But I think this example might be helpful.
This should return only the rows without the auditable_id's value to be equal to 440.
$audits = [
[
"old_values" => [],
"new_values" => [],
"event" => "updated",
"auditable_id" => "450",
"auditable_type" => "App\\Models\\User",
"user_id" => "433",
"user_type" => "App\\Models\\User",
"url" => "http://protocolo-online2/logout?",
"ip_address" => "127.0.0.1",
"user_agent" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
"tags" => "",
"created_at" => "2023-02-01 09:55:00",
"login" => "mailson.suporte"
],
[
"old_values" => [
"ultimo_login" => "2023-02-01 09:32:16"
],
"new_values" => [
"ultimo_login" => "2023-02-01 09:55:10"
],
"event" => "updated",
"auditable_id" => "440",
"auditable_type" => "App\\Models\\User",
"user_id" => "440",
"user_type" => "App\\Models\\User",
"url" => "http://protocolo-online2/login?",
"ip_address" => "127.0.0.1",
"user_agent" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
"tags" => "",
"created_at" => "2023-02-01 09:55:10",
"login" => "mailson.suporte"
]
];
$audits = array_filter($audits, function ($audit) {
return $audit['auditable_id'] != '440';
});

Related

request IP in Laravel application not correct

in laravel when I want get visitor IP from request()->getClientIp() it always show my server IP and offcurse it not correct, I read about this problem I think it's related to cloudflare and
laravel TrustProxies but I don't know what should I do.
how can I get real visitor IP address?
here is my $_Server dump
array:42 [
"REDIRECT_STATUS" => "200"
"HTTP_X_FORWARDED_HOST" => "dpaper.ir"
"HTTP_X_FORWARDED_PROTO" => "https"
"HTTP_X_FORWARDED_PORT" => "443"
"HTTP_X_FORWARDED_FOR" => "::ffff:46.225.69.114"
"HTTP_COOKIE" => "_ga=GA1.2.199690116.1583749582; _gid=GA1.2.452860032.1584212542; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6ImhYWmc5OW4zTktlakRhWDRYTmpGNmc9P"
"HTTP_ACCEPT_LANGUAGE" => "en-US,en;q=0.9,fa;q=0.8,th;q=0.7"
"HTTP_ACCEPT_ENCODING" => "gzip, deflate, br"
"HTTP_SEC_FETCH_USER" => "?1"
"HTTP_SEC_FETCH_MODE" => "navigate"
"HTTP_SEC_FETCH_SITE" => "none"
"HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"
"HTTP_USER_AGENT" => "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
"HTTP_UPGRADE_INSECURE_REQUESTS" => "1"
"HTTP_CONNECTION" => "keep-alive"
"HTTP_HOST" => "dpaper.ir"
"PATH" => "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
"SERVER_SIGNATURE" => "<address>Apache/2.4.25 (Debian) Server at dpaper.ir Port 80</address>"
"SERVER_SOFTWARE" => "Apache/2.4.25 (Debian)"
"SERVER_NAME" => "dpaper.ir"
"SERVER_ADDR" => "10.11.172.198"
"SERVER_PORT" => "80"
"REMOTE_ADDR" => "10.11.81.123"
"DOCUMENT_ROOT" => "/var/www/html/public"
"REQUEST_SCHEME" => "http"
"CONTEXT_PREFIX" => ""
"CONTEXT_DOCUMENT_ROOT" => "/var/www/html/public"
"SERVER_ADMIN" => "webmaster#localhost"
"SCRIPT_FILENAME" => "/var/www/html/public/index.php"
"REMOTE_PORT" => "35058"
"REDIRECT_URL" => "/testi"
"GATEWAY_INTERFACE" => "CGI/1.1"
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_METHOD" => "GET"
"QUERY_STRING" => ""
"REQUEST_URI" => "/testi"
"SCRIPT_NAME" => "/index.php"
"PHP_SELF" => "/index.php"
"REQUEST_TIME_FLOAT" => 1584720819.106
"REQUEST_TIME" => 1584720819
"argv" => []
"argc" => 0
]
I found a solution for this problem, for fix the problem you should put * in TrustProxies Middleware
like this:
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array|string
*/
protected $proxies = '*';
/**
* The headers that should be used to detect proxies.
*
* #var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

PHP To Receive POST Data from Gravity Form when it includes a file upload

I have created a form in Wordpress using gravity forms, which includes a file upload field. On completion of the form I am using a webhook, setup within Gravity forms elite plugin, to pass the form fields into a PHP script which then uploads the data into an external system via API.
The issue is that when I complete the form without a file uploaded it works great, all of the fields are passed into PHP variables and script runs. However when the form does include a file upload field the script fails with no output to the error log.
I have re-created the problem with a much more simple form and script to confirm that this is the issue, my test form contains two fields a field upload and single line text field. My simple test script looks like this:
<?php
$output = var_export($_POST, true);
error_log($output);
?>
When the form is submitted with no file attached the log file shows the following variables outputted:
[01-Feb-2018 21:44:36 Europe/London] array (
'id' => '1166',
'form_id' => '17',
'date_created' => '2018-02-01 21:44:34',
'is_starred' => '0',
'is_read' => '0',
'ip' => '82.**.**.246',
'source_url' => 'http://****.******.co.uk/?gf_page=preview&id=17',
'currency' => 'USD',
'created_by' => '1',
'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'status' => 'active',
1 => 'Test No Photo',
2 => '',
)
Note: The source url and IP have been masked the actual log contains the correct IP and URL.
However, as soon as I include a file upload in the form and then send this to the script nothing is outputted to the log at all and the script does not appear to run.
It's worth noting that the request does work with Requestbin. Here is the output from there including data which comes from the upload field:
is_starred: 0
id: 1163
1: Test with Photo
user_agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
created_by: 1
source_url: http://***.****.co.uk/?gf_page=preview&id=17
ip: 82.**.***.246
form_id: 17
status: active
currency: USD
2: http://****.***.co.uk/wp-content/uploads/gravity_forms/17-b570285e8ba734ff4ab3956428bd8eb9/2018/02/Child26.jpg
is_read: 0
date_created: 2018-02-01 20:48:20
The raw body is:
id=1163&form_id=17&date_created=2018-02-01+20%3A48%3A20&is_starred=0&is_read=0&ip=82.**.***.246&source_url=http%3A%2F%2F***.***.co.uk%2F%3Fgf_page%3Dpreview%26id%3D17&currency=USD&created_by=1&user_agent=Mozilla%2F5.0+%28Windows+NT+10.0%3B+Win64%3B+x64%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F63.0.3239.132+Safari%2F537.36&status=active&1=Test+with+Photo&2=http%3A%2F%2Fwww.********.co.uk%2Fwp-content%2Fuploads%2Fgravity_forms%2F17-b570285e8ba734ff4ab3956428bd8eb9%2F2018%2F02%2FChild26.jpg
Again I have removed the actual domain name but the rest of the request is as shown in Request Bin.
So can anyone please help me work out why the file upload value in the post data above would cause PHP to grind to a complete stop without an error message? Is there anything I can do to access this variable from the array in PHP in the same way Request Bin does?
Do I have to somehow decode the value before I can use it in a script/output it to the log? As a side note in my actual script I don't dump all the variables to a log this is just to show it in it's most simple example, in my main script they are selected one by one and assigned to variables using var = $_POST["1"] etc.
Edit:
I have enabled the logging option in Gravity Forms, it confirms the POST data content sent is:
[body] => Array
(
[id] => 1167
[form_id] => 17
[date_created] => 2018-02-01 22:31:42
[is_starred] => 0
[is_read] => 0
[ip] => 82.**.***.246
[source_url] => http://***.***.co.uk/?gf_page=preview&id=17
[post_id] =>
[currency] => USD
[payment_status] =>
[payment_date] =>
[transaction_id] =>
[payment_amount] =>
[payment_method] =>
[is_fulfilled] =>
[created_by] => 1
[transaction_type] =>
[user_agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
[status] => active
[1] => Test No Photo
[2] => http://***.***.co.uk/wp-content/uploads/gravity_forms/17-b570285e8ba734ff4ab3956428bd8eb9/2018/02/miniserver-image.jpg
)
Is there anything about variable 2 which would cause my PHP script to crash when it dumps the POST data to a log file? (I've removed the domain and IP in the code above.)
Thanks
You can not use $_POST directly to get the payloads of webhook, use something like this:
if($json = json_decode(file_get_contents("php://input"), true)) {
print_r($json);
$data = $json;
} else {
print_r($_POST);
$data = $_POST;
}
error_log(print_r($data,true));

Certain Session Variables are not carrying over

I am currently coding a project in which requires the user to login to the website before being able to view any information. I am currently tracking when a user is logged in or not by using a Session Variable named "usernamelogged". I believe I have all my formatting correct as well.
After logging in you're brought to the main page, in which I have set up (temporarily) to print_r() the session array. Im also using a class to help prevent session hijacking.
Login Page Relevant PHP:
<?php
include dirname(__FILE__).'/includes.php';//INCLUDES FILE
if ($count == 1) {// IF USERNAME AND PASSWORD ARE GOOD
SessionManager::sessionStart('LoginDetails', 10800, '/', 'localhost', true, $username);
$_SESSION['usernamelogged'] = $username;//Declare Session
header("location: members.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
?>
Here is where the problem occurs. Down below I have it print_r() the array, in which comes up with the following details:
Array ( [IPaddress] => Censored IP [userAgent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36 )
However you will notice that there is no "usernamelogged" in that array like there should be.
Here is the php from the page you receive after logging in:
<?php
include dirname(__FILE__).'/includes.php';
SessionManager::sessionStart('LoginDetails', 0, '/', 'localhost', true, $_SESSION['usernamelogged']);
print_r ($_SESSION);// TEMP
echo $_SESSION['usernamelogged'];
$checkses = $sql->prepare("SELECT * FROM staff WHERE username=:user");
$checkses->bindParam(':user', $_SESSION['usernamelogged']);
$checkses->execute();
$count = $checkses->rowCount();
if (!$count == 1) {
echo "Error, you're not logged in";
print_r($count);//TEMP
//header("location: login.php");
die();
}
include dirname(__FILE__).'/header.php';
?>
Finally, the class I am using for session hijacking:
class SessionManager
{
static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null, $username)
{
// Set the cookie name
session_name($name . '_Session');
// Set SSL level
$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
// Set session cookie options
session_set_cookie_params($limit, $path, $domain, $https, true);
session_start();
$_SESSION['usernamelogged'] = $username;
// Make sure the session hasn't expired, and destroy it if it has
if(self::validateSession())
{
// Check to see if the session is new or a hijacking attempt
if(!self::preventHijacking())
{
// Reset session data and regenerate id
$_SESSION = array();
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
self::regenerateSession();
// Give a 5% chance of the session id changing on any request
}elseif(rand(1, 100) <= 5){
self::regenerateSession();
}
}else{
$_SESSION = array();
session_destroy();
session_start();
}
}
static protected function preventHijacking()
{
if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
return false;
if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
return false;
if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
return false;
return true;
}
static function regenerateSession()
{
// If this session is obsolete it means there already is a new id
if(isset($_SESSION['OBSOLETE'])){
if($_SESSION['OBSOLETE'] == true){
return;
}
}
// Set current session to expire in 10 seconds
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 10;
// Create new session without destroying the old one
session_regenerate_id(false);
// Grab current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Set session ID to the new one, and start it back up again
session_id($newSession);
session_start();
// Now we unset the obsolete and expiration values for the session we want to keep
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
static protected function validateSession()
{
if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
return false;
if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
return false;
return true;
}
}
Other Details:
I cut out the HTML and CSS and only gave the PHP.
I don't have any form of output before my session_start();
PHP Version 5.4.40 and Apache 2.4.12
There are no more details that I can think of.
Im happy to answer any questions I can, THANKS for reading and helping!
Edit:
As requested,
The print out of $_SERVER:
Array ( [UNIQUE_ID] => VWvIW2uWJsoAACKtzW8AAAAC [HTTPS] => on [SSL_TLS_SNI] => *Censored* [HTTP_HOST] => *Censored* [HTTP_CONNECTION] => Keep-Alive [HTTP_ACCEPT_ENCODING] => gzip [HTTP_CF_IPCOUNTRY] => US [HTTP_X_FORWARDED_FOR] => *CENSORED* [HTTP_CF_RAY] => 1ef79bdf5d900418-ORD [HTTP_X_FORWARDED_PROTO] => https [HTTP_CF_VISITOR] => {"scheme":"https"} [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36 [HTTP_DNT] => 1 [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8,es;q=0.6 [HTTP_COOKIE] => __cfduid=d616d6faa0ec4dd338e855665846ad2da1432945387 [HTTP_CF_CONNECTING_IP] => *CENSORED* [PATH] => /bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin [LD_LIBRARY_PATH] => /usr/local/apache/lib [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.4.12 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 PHP/5.4.40 [SERVER_NAME] => bbwatch.co.uk [SERVER_ADDR] => *CENSORED* [SERVER_PORT] => 443 [REMOTE_ADDR] => *CENSORED* [DOCUMENT_ROOT] => /home/bbwatchc/public_html [REQUEST_SCHEME] => https [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => /home/bbwatchc/public_html [SERVER_ADMIN] => webmaster#*Censored* [SCRIPT_FILENAME] => /home/***/public_html/members.php [REMOTE_PORT] => 35348 [REMOTE_USER] => *CENSORED* [AUTH_TYPE] => Basic [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /members.php [SCRIPT_NAME] => /members.php [PHP_SELF] => /members.php [PHP_AUTH_USER] => *CENSORED* [PHP_AUTH_PW] => *CENSORED* [REQUEST_TIME_FLOAT] => 1433127003.37 [REQUEST_TIME] => 1433127003 [argv] => Array ( ) [argc] => 0 )
Also, the printout of $_SESSION:
Array ( [IPaddress] => *CENSORED* [userAgent] => Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36 ) Error, you're not logged in0

Why session is false in Codeigniter?

After success autorization I get array with a information about user:
$authdata = array(
'logged_in' => true,
'id_user' => $checked['idUsers'],
'time_auth' => time(),
'status' => $checked['UsersStatus'],
'type' => $checked['UsersTypeAccount'],
);
Then set this array to session Codeigniter(array $checked is not empty, there is a UsersStatus and UsersTypeAccount):
$this->session->set_userdata($authdata);
After do redirect at controller profile:
redirect('profile');
This controllers checks a user session on empty/true:
if ($this->session->userdata("session_id") && $this->session->userdata("type") && (($this->session->userdata("status")){
// Return Success
}
If make var_dump() session:
var_dump($this->session->userdata("type")).'<br>'; // false
var_dump($this->session->userdata("status")).'<br>'; die(); // false
I get a false value, why type and status fields is not true in session?
Edition:
Also I have done:
var_dump($this->session->all_userdata()); die();
Response:
array(5) { ["session_id"]=> string(32) "85d9e0aa1f738c551b4ba649c36f977c" ["ip_address"]=> string(12) "46.32.174.82" ["user_agent"]=> string(109) "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36" ["last_activity"]=> int(1416142399) ["user_data"]=> string(0) "" }
So, session is created, but without fields status, type
From tutorial:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Important:
$this->session->set_userdata($authdata);
var_dump($this->session->all_userdata()); die(); // Here I get full session array.
After some a long attempts to resolve this trouble I had decided:
Update Codeigniter to version 2.2
After the code had worked:
Set session:
$this->session->set_userdata($authdata);
Get session:
$type = $this->session->userdata['type'];
$status = $this->session->userdata['status'];
$session_id = $this->session->userdata['session_id'];
It helped me, maybe someone too

Comment not being posted with xml-rpc wp.newComment php

I have a code like this.
<?php
include('IXR_Library.php');
$client = new IXR_Client('http://127.0.0.1/wordpress/xmlrpc.php');
$data = array(
'comment_post_ID' => 1,
'comment_author' => 'test_author',
'comment_author_email' => 'test#gmail.com',
'comment_author_url' => 'http://test.limewebs.com',
'comment_content' => 'Test Content',
'comment_type' => '',
'comment_parent' => 0,
'user_id' => 1,
'comment_author_IP' => '127.0.0.1',
'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
'comment_date' => $time,
'comment_approved' => 1,
);
if (!$client->query('wp.newComment','', 'username','password','12',$data)) {
die('An error occurred - '.$client->getErrorCode().":".$client->getErrorMessage());
}
$result = $client->wp_insert_comment($data);
print_r($result);
?>
In the above code, I get my comment posted to WordPress site, but the content(comment_content) is not getting posted.
Dude, remove all 'comment_' prefix to your array properties. Writing the WpAPI Class I dug deep in the heart of WP's XMLRPC. Parameters are always never in the order an normal person would put them. The names used are not consistent either. It's not a guessing game. Always look at the WP core code when not sure... [or use my Class ;)]
You're using invalid parameters on your request.
Wordpress XML-RPC_wp documentation lists the following parameters has valid for wp.newComment requests:
Parameters
int blog_id
string username
string password
int post_id
struct comment
int comment_parent
string content
string author
string author_url
string author_email
The following code should be enough to post a new comment on wordpress 3.3.5 (XML-RPC_wp api v3.1) via xmlrpc:
<?
include('IXR_Library.php.inc');
$client = new IXR_Client('http://myblog.com/xmlrpc.php');
$time = date("Ymd")."T".date("H:i:s")."Z";
$post_id = "630";
$data = array(
'author' => 'test_author',
'author_email' => 'test_comment#scroogle.org',
'author_url' => 'http://www.scroogle.org',
'content' => 'Comentario Teste scroogle.org',
'date' => $time,
'approved' => 1,
);
if (!$client->query('wp.newComment','', '','',$post_id, $data)) {
die('An error occurred - '.$client->getErrorCode().":".$client->getErrorMessage());
}
$result = $client->wp_insert_comment($data);
print_r($result);
?>
Note: In order to post anonymous comments via xmlrpc you'll need WordPress – Anonymous XMLRPC Comments Plugin

Categories