Question

How to Check if a String Starts With a Prefix in PHP

Question

I want to check whether a string starts with http in PHP. What is the correct way to do this?

$string1 = 'google.com';
$string2 = 'http://www.google.com';

For example, google.com should return false, while http://www.google.com should return true.

Short Answer

By the end of this page, you will understand how to check whether a string starts with a given prefix in PHP. You will learn modern and older approaches, how they work, when to use them, and which common mistakes to avoid.

Concept

In programming, checking whether a string starts with a specific sequence of characters is called a prefix check.

In your example, the prefix is http. A prefix check answers questions like:

  • Does this URL start with http?
  • Does this file path start with /api/?
  • Does this username start with admin_?

This matters because many programs behave differently depending on the beginning of a string. For example:

  • URLs may need different handling if they already include a protocol.
  • API routes may be grouped by a prefix.
  • Commands may be recognized by a keyword at the start.

In PHP, the clearest modern way to do this is with str_starts_with().

str_starts_with($string, $prefix)

It returns:

  • true if $string begins with $prefix
  • false otherwise

If you are working in older PHP versions that do not support str_starts_with(), developers often use strpos() or substr() as alternatives.

Mental Model

Think of a string like a line of text on paper.

Checking whether it starts with something is like asking:

"Do the first few letters match this exact label?"

If the string is http://www.google.com, then the first 4 characters are http, so the answer is yes.

If the string is google.com, the first 4 characters are goog, so the answer is no.

You are not searching the whole string. You are only inspecting the beginning.

Take Quiz

Syntax and Examples

Modern PHP approach

If your PHP version supports it, use str_starts_with():

$string1 = 'google.com';
$string2 = 'http://www.google.com';

var_dump(str_starts_with($string1, 'http')); // false
var_dump(str_starts_with($string2, 'http')); // true

Why this is good

  • Easy to read
  • Clearly expresses intent
  • Avoids common strpos() mistakes

Older PHP approach with strpos()

$string1 = 'google.com';
$string2 = 'http://www.google.com';

var_dump(strpos($string1, 'http') === 0); // false
var_dump(strpos($string2, 'http') === 0); // true

Why === 0 matters

strpos() returns:

  • 0 if the match starts at the beginning
  • another number if found later
  • false if not found

So you must use strict comparison:

strpos($string, 'http') === 0

Another older approach with substr()

$string1 = 'google.com';
$string2 = 'http://www.google.com';

var_dump(substr($string1, 0, 4) === 'http'); // false
var_dump(substr($string2, 0, 4) === 'http'); // true

This works by taking the first 4 characters and comparing them directly.

Step by Step Execution

Consider this example:

$string = 'http://www.google.com';
$result = str_starts_with($string, 'http');
var_dump($result);

Step by step:

  1. $string is set to 'http://www.google.com'.
  2. str_starts_with($string, 'http') checks the beginning of the string.
  3. PHP compares the first characters of $string with 'http'.
  4. The first 4 characters are exactly http.
  5. The function returns true.
  6. var_dump($result) prints:
bool(true)

Now compare with this:

$string = 'google.com';
$result = str_starts_with($string, 'http');
var_dump($result);

Step by step:

  1. $string is 'google.com'.
  2. PHP checks whether the string begins with 'http'.
  3. The first characters are goog, not http.
  4. The function returns false.
  5. Output:
bool(false)

Real World Use Cases

Checking whether a string starts with a prefix appears in many real programs.

URLs

Make sure a URL already has a protocol before adding one:

$url = 'google.com';

if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
    $url = 'https://' . $url;
}

API routes

Check whether a route belongs to an API section:

$route = '/api/users';

if (str_starts_with($route, '/api/')) {
    echo 'API route';
}

File paths

Detect a specific folder prefix:

$path = '/uploads/images/photo.jpg';

if (str_starts_with($path, '/uploads/')) {
    echo 'User upload';
}

Command parsing

Recognize commands in text input:

$message = '/help show commands';

if (str_starts_with($message, '/help')) {
    echo 'Show help information';
}
Take Quiz

Real Codebase Usage

In real PHP codebases, prefix checks often appear in validation, normalization, routing, and defensive programming.

Input normalization

Developers often normalize user input before saving or using it:

function normalizeUrl(string $url): string
{
    if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
        return 'https://' . $url;
    }

    return $url;
}

This uses an early return style: if the condition is met, return the modified value immediately.

Guard clauses

A prefix check can quickly reject invalid data:

function isApiPath(string $path): bool
{
    if (!str_starts_with($path, '/api/')) {
        return false;
    }

    return true;
}

This is a simple guard clause.

Configuration-based prefixes

In larger apps, prefixes are often stored in variables or config files:

$prefix = '/admin/';
$path = '/admin/dashboard';

if (str_starts_with($path, $prefix)) {
    echo 'Admin area';
}

Validation before processing

Developers commonly validate data before expensive work:

function handleUrl(string $url): void
{
    if (!str_starts_with($url, 'http://') && !str_starts_with($url, 'https://')) {
        throw new InvalidArgumentException('URL must start with http:// or https://');
    }

    // Continue processing
}

Common Mistakes

1. Using strpos() without strict comparison

Broken code:

if (strpos($string, 'http')) {
    echo 'Starts with http';
}

Why it fails:

  • If http is found at position 0, strpos() returns 0
  • 0 is treated as false in a loose condition
  • So the code incorrectly behaves as if there is no match

Correct version:

if (strpos($string, 'http') === 0) {
    echo 'Starts with http';
}

2. Confusing “starts with” and “contains”

Broken idea:

if (strpos($string, 'http') !== false) {
    echo 'Starts with http';
}

This checks whether http exists anywhere, not just at the start.

3. Forgetting case sensitivity

String checks are case-sensitive:

$string = 'HTTP://example.com';
var_dump(str_starts_with($string, 'http')); // false

If you need a case-insensitive check, normalize the case first:

var_dump(str_starts_with(strtolower($string), 'http')); // true

4. Hardcoding the wrong prefix length with substr()

Broken code:

substr($string, 0, 5) === 'http'

This compares 5 characters with a 4-character string. Be careful with lengths.

Correct version:

substr($string, 0, 4) === 'http'

5. Checking only http:// and forgetting https://

If you are validating URLs, you often need both:

if (
    str_starts_with($url, 'http://') ||
    str_starts_with($url, 'https://')
) {
    echo 'Valid protocol prefix';
}

Comparisons

ApproachExampleBest forNotes
str_starts_with()str_starts_with($s, 'http')Modern PHPClearest and safest option
strpos()strpos($s, 'http') === 0Older PHPMust use === 0
substr()substr($s, 0, 4) === 'http'Simple fixed-length checksWorks, but less expressive

starts with vs contains

Check typeMeaningExample
Starts withMatch must be at the beginningstr_starts_with($s, 'http')
ContainsMatch can appear anywherestrpos($s, 'http') !== false

http vs http:// vs https://

PrefixMatchesExample
httpBoth http:// and https:// start with http? No, https:// starts with httpsUse carefully
http://Only HTTP URLsExact protocol check
https://Only HTTPS URLsExact secure protocol check

If you want to allow both HTTP and HTTPS, check both prefixes explicitly.

Take Quiz

Cheat Sheet

Quick reference

Modern PHP

str_starts_with($string, $prefix)

Example

str_starts_with('http://example.com', 'http'); // true
str_starts_with('google.com', 'http');         // false

Older PHP with strpos()

strpos($string, 'http') === 0

Older PHP with substr()

substr($string, 0, 4) === 'http'

Rules

  • Use str_starts_with() if available.
  • Use === 0 with strpos().
  • Prefix checks are case-sensitive.
  • contains is not the same as starts with.
  • For URLs, check http:// and https:// separately when needed.

Case-insensitive version

str_starts_with(strtolower($string), 'http')

Common URL check

if (
    str_starts_with($url, 'http://') ||
    str_starts_with($url, 'https://')
) {
    // URL already has a protocol
}

FAQ

How do I check if a string starts with http in PHP?

Use:

str_starts_with($string, 'http')

If you are using an older PHP version, use:

strpos($string, 'http') === 0

Why does strpos() sometimes fail in an if statement?

Because strpos() returns 0 when the match is at the beginning, and 0 is treated as false in a loose condition. Use === 0.

Is str_starts_with() case-sensitive in PHP?

Yes. str_starts_with('HTTP://site.com', 'http') returns false.

How do I do a case-insensitive starts-with check in PHP?

Convert the string to lowercase first:

str_starts_with(strtolower($string), 'http')

How do I check for both http:// and https://?

Use two checks:

str_starts_with($url, 'http://') || str_starts_with($url, 'https://')

Can I use substr() to check the start of a string?

Yes:

substr($string, 0, 4) === 'http'

It works, but str_starts_with() is usually clearer.

What is the difference between starts-with and contains?

Starts-with means the text must be at the beginning. Contains means it can appear anywhere in the string.

Take Quiz

Mini Project

Description

Build a small PHP helper that ensures a website URL has a protocol. This demonstrates how prefix checks are used in practical input cleaning before saving data or making requests.

Goal

Create a function that adds https:// to a URL if it does not already start with http:// or https://.

Requirements

  • Write a PHP function that accepts a URL string.
  • Return the original URL if it already starts with http:// or https://.
  • Add https:// if the URL has no protocol.
  • Test the function with at least three example URLs.
Take Quiz

Keep learning

Related questions

View more