How To Get a User’s IP Address With PHP

Featured Imgs 03

In PHP, there are several methods to retrieve a user’s IP address. We will explore two of those ways in this article.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!

 

The most reliable way to get a user’s IP address in PHP is to use the $_SERVER superglobal variable.

The $_SERVER superglobal variable contains information about the server environment, including the user’s IP address. Here’s an example:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
echo $ip;
?>

The $_SERVER['REMOTE_ADDR'] element returns the IP address of the client (i.e., the user’s device) that is making the request to the server. This method works well for most cases, but there are a few situations where it may not return the correct IP address, such as when the user is behind a proxy server or using a VPN.

To handle these cases, it is recommended to use the following code to get the user’s IP address:

<?php
function get_client_ip() {
    $ip = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip = get_client_ip();
echo $ip;
?>

In this code, we first check if the $_SERVER['HTTP_CLIENT_IP'] element is set. If it is, we use its value as the user’s IP address. If not, we then check if the $_SERVER['HTTP_X_FORWARDED_FOR'] element is set. If it is, we use its value as the user’s IP address. If neither of these elements is set, we use the $_SERVER['REMOTE_ADDR'] element as the user’s IP address.

This method provides a more robust solution for retrieving the user’s IP address, as it takes into account the possibility that the user may be behind a proxy server or using a VPN.

Learn more here.

Stay Logged in to WordPress

Category Image 091

I work from home so can afford to leave tabs open for each of my WordPress sites. That way I can jump on anytime and update or add new content very quickly. The problem I kept running into is that WordPress automatically logs out users after 48 hours. Which means I have to log back in every day even when it’s not necessary. So I needed a way to stay logged in to WordPress indefinitely. Fortunately WordPress is very flexible and easy to customize, and the login duration can be changed via several different methods.

Here are three easy ways to stay logged in to WordPress for a longer period of time.

Three ways to do it..

Check the box

The easiest way to increase the expiration date/time for logins, is to simply check the “Remember Me” checkbox when logging in to WordPress. That will increase the expiration to 14 days, or whenever the browser is closed. After that time, the session cookie expires and you’ll need to log in once again.

This is useful if 14 days is enough time for your workflow.

One downside is that it requires an extra click to check the box. Fine I guess if you’re logging in manually. But if you’re using a password manager or other auto-login app, the extra checkbox step requires action on your part, thus adding friction and slowing things down.

Another downside is that 14 days is not always enough. For my own workflow, I prefer to minimize as many needless steps as possible. So I prefer the next method of extending the login duration, using a slice of custom code..

Add custom code

For more flexibility and less friction, you can add the following code snippet to stay logged in to WordPress for however long is necessary, even indefinitely if it makes sense to do so. This is the preferred technique for my own websites.

Important: Be mindful of any other users who may be logging in on public machines. Only extend the login duration if you know 100% that it’s safe and secure.

Here is the magic code to stay logged in to the WordPress Admin Area. You can add this code via your theme functions file, or add via simple custom plugin. Here is a guide that explains how to do both.

function shapeSpace_stay_logged_in($expires) {
	
	return 172800; // default 48 hours
	
}
add_filter('auth_cookie_expiration', 'shapeSpace_stay_logged_in');

As written, this code hooks into auth_cookie_expiration and filters the expiration duration (in seconds). By default the duration is 48 hours. You can change that to anything that works best.

To stay logged in forever, change the interval to some very large number, like 3153600000 to stay logged in for 100 years ;) To help with converting time to seconds, you can use a free time conversion calculator.

Thanks to Alex Mills (Viper007Bond) for sharing this code at Stack Exchange.

Update! Thanks to Scott Fennell for pointing out that WordPress provides a set of time constants that we can use instead of typing out seconds like animals:

MINUTE_IN_SECONDS
HOUR_IN_SECONDS
DAY_IN_SECONDS
WEEK_IN_SECONDS
MONTH_IN_SECONDS
YEAR_IN_SECONDS

So we can do like 3 * HOUR_IN_SECONDS to specify a time interval of 3 hours.

Bonus: Check the “Remember” box by default

Bonus tip! To automatically check the “Remember Me” box on the WP Login Page, add the following code via theme functions or custom plugin.

function shapeSpace_custom_login_checkbox() {
	
	?>
	
	<script>
		document.getElementById('rememberme').checked = true;
		document.getElementById('user_login').focus();
	</script>
	
	<?php
	
}
add_filter('login_footer', 'shapeSpace_custom_login_checkbox');

No changes need made, just add and done. One in place, the remember checkbox will be selected automatically by default.

Install a plugin

If you want to extend the login beyond 14 days, but don’t want to go the custom code route, installing a plugin is the way to go. Currently there seems to be only a couple of capable plugins in the WP Plugin Directory:

Let me know if I’ve missed anything! :)


An In-Depth Guide to PHP 8.1: Enums

Featured Imgs 23

Enums or enumerations are a new feature introduced in PHP 8.1 that contains a defined number of possible values you can use. When creating an app, you often come across scenarios where you have a predetermined list of options to select from, for instance:

  • A blog entry can be published, in the draft, or in review.
  • A player may be a medic, soldier, engineer, 
  • A ticket may be VIP, standing, or seated, 
  • and so on ...


PHP unlink(); No such file or directory

558fe5180e0e8fc922d31c23ef84d240

hello, i have a probelm where i want to update my image in database using unlink(). The error is Warning: unlink(images/481933.jpg): No such file or directory. I try search the solution but nothing can solve my probelm. anyone can help me? thank you in advanced. this is my code:

$upload_dir='images/';

$imgExt=strtolower(pathinfo($images,PATHINFO_EXTENSION));

$valid_extensions=array('jpeg', 'jpg', 'png', 'gif', 'pdf');

$picProfile=rand(1000, 1000000).".".$imgExt;

unlink($upload_dir.$edit_row['prod_img']);

move_uploaded_file($tmp_dir, $upload_dir.$picProfile);

$stmt=$db_conn->prepare('UPDATE product SET prod_name=:prod_name, category=:category, prod_img=:prod_img, unit_price=:price, stock=:stock, min_limit=:min_limit, weight=:weight, description=:description, packaging=:packaging, size=:size, retail_price=:retail, agent_price=:agent WHERE prod_id=:prod_id');

WordPress Should Bump PHP Support on a Transparent and Predictable Schedule

Featured Imgs 08

Juliette Reinders Folmer released a proposal for WordPress to drop old PHP version support on a fixed schedule. She wrote the proposal after Matt Mullenweg, WordPress co-founder and project lead, reached out to discuss solutions. This was after he closed a Trac ticket last week that sought to drop support for PHP 5.6 and bump the minimum version to 7.1 for the next major WordPress release this year.

The proposal lays out a position that many in the WordPress community could get behind. It is a clear-cut, transparent path for the platform’s future PHP support.

Folmer essentially put forward two roadmaps in the proposal. The first roadmap decides at what stage WordPress would drop support for a particular PHP version. The platform would remove support for a PHP minor release that is more than five years old each December. This would coincide with whatever major release of WordPress is upcoming. The following schedule lays out the minimum-supported PHP version each year:

  • December 2020 – PHP 7.1
  • December 2021 – PHP 7.2
  • December 2022 – PHP 7.3
  • December 2023 – PHP 7.4
  • December 2024 – PHP 8.0

The second part of the proposal creates a rolling schedule for backporting security updates to WordPress. Currently, WordPress releases security updates all the way back to the version 3.7 branch. If adopted, Folmer’s recommendation would support only the previous four years of WordPress releases.

Such a change would mean that when WordPress 5.6 is released in December 2020, the WordPress project would be committed to backporting security fixes as far back as WordPress 4.7, released in December 2016.

Folmer also proposes backporting PHP upgrade notices from the site health project to the currently-supported older versions of WordPress. This measure would inform users of PHP version issues before they make the jump to a newer version of WordPress.

The overlap of bumping the minimum PHP support into the future and backporting security fixes gives users a potentially huge window of nine years in which they could stay on whatever version of PHP they are currently on. Nine years may seem like a lifetime on the web with its constantly-changing technology, and it was a point of contention from some people in the comments of the post. However, it is a plan of action, something the WordPress community has not had the pleasure of experiencing with regards to PHP support. Developers will undoubtedly argue over the dates and versions, but that is secondary to actually having a predictable timeline.

A fixed version bump schedule is welcome. It puts everyone from developers to end-users to web hosts on the same page. This level of transparency is necessary if we ever intend to move forward without rehashing the same arguments.

The system of waiting around to see when a specific PHP version’s usage stats drop below a certain percentage just muddies things. The result is typically a long-winded argument that does not move the needle. Each side picks its stats. Each side digs its heels in. And each side has plenty of good points to make. Ultimately, everyone wants the same thing — to move the entire project forward and use up-to-date tools. However, they always disagree on how we get there. Eventually, the minimum PHP version gets bumped and the community gears up for the next round. It leaves us in a constant state of tug of war between those who want quicker advancement and those who do not want to leave users behind.

The truth is that no one is ever completely right in these arguments. There is no roadmap to follow. We have no guiding principle other than “this has what’s been done before.”

WordPress needs to set clear expectations.

This is not just a problem with the minimum PHP version — many want a more-detailed roadmap for the entire project. However, minimum PHP support is one problematic area that we could have a solution for, and Folmer has carved out a path. We need only follow it.

WordPress Bumps Minimum PHP Recommendation to 7.2

Featured Imgs 23

Late last week WordPress made major progress towards the goal of getting users to adopt newer versions of PHP. The ServeHappy API has been updated to set the minimum acceptable PHP version to 7.2, while the WordPress downloads page recommends 7.3 or newer.

Sergey Biryukov committed this change on the meta trac after Marius Jensen opened a ticket for it nine days ago. Previously, the ServeHappy dashboard widget was showing the upgrade notice to users of PHP 5.6 or lower.

“After discussing with the core Site Health team and the Hosting Team, it has come up that the most sensible next move is to show the upgrade notice to users of PHP <=7.1 (this means setting ACCEPTABLE_PHP to 7.2),” Jensen said.

“Looking at the numbers, we’re seeing roughly 25% of sites running a WordPress version that includes ServeHappy [that] would then get an upgrade notice.”

This change means that the majority of WordPress sites are using an acceptable version of PHP. Approximately 47% are running WordPress on older versions. Those who are on WordPress 5.2+ (when Site Health was introduced) will see the upgrade notices generated by the ServeHappy API.

WordPress.org stats: PHP versions in use as of June 14, 2020

This update also bumps the lowest branch of PHP which is actively supported to 7.3 and bumps the lowest branch of PHP that is receiving security updates to 7.2.

The Site Health team scheduled the change for last Friday, but Jensen noted that the API call is cached for a week in core. It should start popping up for users throughout this week.

In December 2018, PHP 5.6 and 7.0 reached End of Life (EOL) and stopped receiving security updates. This left approximately 83% of users on unsupported versions of PHP at the end of 2018. Today, with the progress encouraged by the Site Health project, 47% are on unsupported PHP versions. The update put in place last week should help significantly decrease this number before PHP 7.2 reaches EOL in November 2020.

Jenny Wong, who helped coordinate the project as part of the Site Health team, described how they got started and worked successfully across teams with design, Polyglots, and Hosting contributors to make this update possible.

“I remember going to WordCamp San Francisco and sitting down with Andrew Nacin and Mark Jaquith at lunch and asking them why WordPress supported such old versions and what the project was doing about it,” Wong said. “They told me the work that had been going on.

“They told me the issues, they took the time took explain it all to me and answer all my questions.”

Wong said she was grateful to be part of that initial discussion in 2014 and to have shared in the journey with dozens of contributors.

“To the polyglots who translated everything we threw at them, to everyone else who gave feedback, argued, fought, discussed and debated, to everyone who has shared ideas and patches, to every person who has listened to me complain, took my wild ideas and made them an reality – Thank you!” Wong said.

Given WordPress’ large share of the market, encouraging adoption of newer versions of PHP will help make the web more secure. Please note that this update means that 7.2 is now the lowest branch of PHP that is considered acceptable for use with WordPress, according to the ServeHappy API. Sites that are running on older versions may continue to work but WordPress will continue strongly urging users to upgrade.

WordPress Birthday, Elementor Milestone, Template Kits, PHP and WP Version Checks 🗞️ June 2020 WordPress News w/ CodeinWP

Category Image 091
Hi everyone! The past weeks freed us from our houses and apartments a little bit. We could go out for long walks and some fresh air, respecting the social distancing rules, of course. I think it makes a difference, being able to change scenery even slightly. With a more optimistic view for the rest of the year, let’s review the latest happenings in WordPress!

How to Check if Post has Taxonomy Term

Category Image 036

Something I did not know about when working with Custom Post Types and Custom Taxonomies. Normally when checking if a regular WP Post belongs to a specific category, we can use the WordPress function in_category(). But that does not work with Custom Post Types. To check if a CPT belongs to a specific term in a Custom Taxonomy, use has_term() instead.

Check if WP Post belongs to specific category

To check if the current post belongs to a specific category, use in_category(). For example in your theme's single.php template, you can do this:

if (in_category(1)) {
	
	// post is in category with ID = 1
	
}

Here we are checking if the post belongs to category with ID = 1. You can change that to any category ID, name or slug, or an array containing multiple values.

Here is an example where mutliple categories are checked:

if (in_category('donuts')) {
	
	// post belongs to "donuts" category
	
} elseif (in_category(array('coffee', 'beer'))) {
	
	// post belongs to either "coffee" or "beer"
	
} else {
	
	// post does not belong to any of the above categories
	
}

Notice the use of an array in the elseif condition. You can specify as many categories as needed using an array of category IDs, names, or slugs.

Check if CPT belongs to specific taxonomy term

Now for the main point of this tutorial. To check if the current post belongs to a specific term in a custom taxonomy. For example, if we have a taxonomy named download_category and want to check if the current post belongs to the term combo, we can do this:

if (has_term('combo', 'download_category')) {
	
	// post belongs to "combo" in "download_category" taxonomy
	
}

When calling has_term(), the first parameter is the name of the term, and the second parameter is the name of the taxonomy.

To check multiple terms, use an array of term IDs, names, or slugs. For example:

if (has_term(array('combo', 'book', 'deal'), 'download_category')) {
	
	// post belongs to "combo", "book", or "deal" in "download_category" taxonomy
	
}

So this example will check if the current post belongs to "combo", "book", or "deal" in the "download_category" taxonomy.

Bonus Tip: Check for *any* taxonomy term

To check if the current post belongs to any term in a given taxonomy, simply leave the first parameter empty/blank. Example:

if (has_term('', 'download_category')) {
	
	// post belongs to a term in the "download_category" taxonomy
	
}

Here we are checking if the current post belongs to any term in the "download_category" taxonomy.

That's the thick and thin of it.

Bottom line is just remember:

  • Check post for category — use in_category()
  • Check post for tax term — use has_term()

Laravel 7 Now Available

Featured Imgs 23

Laravel, which calls itself the "PHP framework for web artisans," has released version 7. Laravel 7 includes better routing speed, a new HTTP client, CORS support and other enhancements. New features include Laravel Airlock, custom Eloquent casts, Blade component tags, and fluent string operations.