Link Copied!

Ready to share with your network.

PHP Script Works in Browser but Not in Cron Job – Real Causes & Fixes

Many PHP scripts work perfectly in the browser but fail silently when run via cron jobs. This guide explains why it happens and how to fix it correctly.

Sunil Nath 13
PHP Script Works in Browser but Not in Cron Job – Real Causes & Fixes

PHP Script Browser Me Chal Raha Hai Par Cron Job Me Nahi? Real Reason & Fix

Ye problem almost har PHP developer face karta hai. Browser me script smooth chalti hai, par jaise hi cron job se run karte ho — kuch output nahi, koi error nahi, bas silence. Iska reason PHP nahi, balki execution environment hota hai.

Is blog me hum step-by-step samjhenge ki PHP cron job fail kyu hoti hai, kaise debug kare, aur production-ready fix kaise likhe.


Sabse Pehle Ye Samjho: Browser vs Cron

Jab tum browser se PHP script run karte ho, wo Apache/Nginx ke through PHP-FPM par chalti hai. Lekin cron job PHP ko CLI mode me run karti hai. Dono ka environment bilkul alag hota hai.

Browser Cron Job
Web server context CLI context
$_SERVER available Mostly empty
Relative paths work Relative paths break

Real Reason #1: Galat PHP Binary

Cron by default wahi PHP use nahi karta jo browser karta hai. Hosting me multiple PHP versions installed hote hain, aur cron galat version use kar leta hai.

            
which php
/usr/bin/php
            
        

Cron job me hamesha full path likho:

            
* * * * * /usr/bin/php /home/user/project/script.php
            
        

Real Reason #2: Relative Paths (Sabse Common Mistake)

Browser me relative paths kaam kar jaate hain, par cron ka working directory random hota hai. Isliye ye code cron me fail ho jata hai:

            
require 'config.php';
            
        

Sahi tareeka:

            
require __DIR__ . '/config.php';
            
        

Real Reason #3: Error Dikhta Hi Nahi

Cron job errors browser jaise screen par nahi dikhata. Agar logging nahi hai, to tum andhere me kaam kar rahe ho.

            
* * * * * /usr/bin/php script.php >> cron.log 2>&1
            
        

Isse pata chalega actual error kya hai.


Production-Ready Checklist

  • Absolute paths use karo
  • PHP CLI version verify karo
  • Har cron job ka log rakho
  • Browser-specific code avoid karo

Final Verdict

PHP cron job fail hone ka matlab ye nahi ki tumhara code kharab hai. Zyada tar cases me problem environment mismatch hoti hai. Jab tum CLI mindset se code likhte ho, cron jobs kabhi fail nahi hoti.

Browser forgiving hota hai, cron job nahi.

Tags: #PHP

Did you enjoy this article?

Share it with your network and help others learn.

Sunil Nath

About the Author

Sunil Nath

Sunil Nath is a full stack developer, API engineer, and tech enthusiast sharing deep insights on modern web architecture.

View Profile

Prompt Copied! 🚀

Your prompt is copied.
Use it in image generation tool Gemini.