Monday, October 28, 2013

Schedule a PHP Script on Windows Server with Task Scheduler (Windows Cron)

Overview

Without any manual trigger or interaction, if you want to run a specific task at a specific time you can use a scheduled task. On Linux/Unix this is done with cron / crontab; on Windows the equivalent built-in tool is Task Scheduler. This article shows a simple workflow to run a PHP script on a Windows server (WAMP) on a schedule by invoking PHP from a batch file.

Requirements

  • A PHP script that is independently executable (no missing relative include paths). Example: backupcron.php.
  • PHP CLI installed (php.exe) as part of WAMP (or a separate PHP install).
  • Permission to create and run scheduled tasks on the Windows server.

Key points before you begin

  • Use absolute paths in scripts and the batch file.
  • If your PHP script depends on include files, ensure includes use absolute paths or the script sets the correct working directory.
  • Replace the example PHP path below with the path on your machine (the example uses php5.4.3 as an illustration).

Procedure (step-by-step)

  1. Create the PHP action script (example name: backupcron.php). Make sure it is executable from the command line and does not depend on relative include paths unless handled explicitly.

  2. Create a Windows batch file that runs the PHP script. Example name: backup.bat.

    Example batch file content (exact example from the original article):

@echo off
C:\wamp\bin\php\php5.4.3\php.exe -f C:\wamp\www\Test\admin\backupcron.php

Recommended safer variant (handles spaces and logs output):

@echo off
"C:\wamp\bin\php\phpX.Y.Z\php.exe" -f "C:\wamp\www\Test\admin\backupcron.php" >> "C:\wamp\www\Test\admin\backup.log" 2>&1
  • Replace phpX.Y.Z with your installed PHP folder (e.g., php7.4.30 or php8.1.0).
  • The >> and 2>&1 redirect stdout and stderr to a log file for debugging.
  1. Test the batch file from a Command Prompt. Open cmd.exe and run the batch file path explicitly. Fix any immediate PHP or path errors.

  2. Open Task Scheduler: Start → Programs → Accessories → System Tools → Task Scheduler.

Task Scheduler main view

  1. In Task Scheduler, open the Task Scheduler Library to view scheduled jobs.

Task Scheduler library

  1. Click "Create Basic Task" (or "Create Task" for advanced options) from the right panel and follow the wizard:
  • Give the task a name and description.
  • Trigger: choose the schedule (Daily, Weekly, One time, or "When I log on", etc.).

Create Basic Task wizard options

  1. For more control, open the Trigger properties and set repetition options (for example: every hour). Example trigger view:

Trigger properties example

  1. In the Action step choose to "Start a program" and set the program/script to cmd.exe and the arguments to run your batch file. Example used in the original article:
  • Program/script: cmd
  • Add arguments (optional): /c C:\wamp\www\Test\admin\backup.bat

Alternatively you can directly point the Action to the batch file:

  • Program/script: C:\wamp\www\Test\admin\backup.bat

Example action dialogs from the original article:

Action example 1

Action example 2

  1. Common action configuration notes:
  • If using cmd.exe /c, include the full path to your .bat file in the arguments.
  • If you point directly to the .bat file, set the "Start in (optional)" field to the folder containing the batch file so relative paths work.
  • Use quoted paths if any path contains spaces.
  1. Other task options you may need to change (found on the General tab or when creating an advanced Task):
  • Set the user account under which the task runs. If the task needs network access or specific privileges, use an account with the right permissions.
  • Consider selecting "Run whether user is logged on or not" if you need the task to run in the background.
  • If the task requires elevation, check "Run with highest privileges".
  1. Create or copy your batch file to the target location (example path used in the article):
C:\wamp\www\Test\admin\backup.bat
  1. Example batch file content (again):
@echo off
C:\wamp\bin\php\php5.4.3\php.exe -f C:\wamp\www\Test\admin\backupcron.php
  1. backupcron.php is the PHP action script that contains the code to generate the backup file.

  2. After creating the scheduled task, you can run it manually from Task Scheduler (right-click → Run) to validate that it works.

  3. Verify the scheduled executions in Task Scheduler's "History" tab or by checking your output file or the log file if you redirected output in the batch file.

Troubleshooting (common failures and fixes)

  • "Nothing happens" — open a command prompt and run the batch file manually to see errors.
  • PHP path errors — verify the path to php.exe and update the batch file accordingly.
  • Include files missing — make sure your PHP script uses absolute paths or sets chdir(__DIR__) at the top so includes resolve relative to the script folder.
  • Permissions — verify the task's user account has permission to run php.exe and write to output folders. Try "Run whether user is logged on or not" and provide credentials, and/or check "Run with highest privileges" if elevation is required.
  • Paths with spaces — wrap paths in double quotes.
  • No error output — append >> path\to\log.txt 2>&1 to the batch file command to capture stdout/stderr.

Example logging batch file (recommended)

@echo off
"C:\wamp\bin\php\phpX.Y.Z\php.exe" -f "C:\wamp\www\Test\admin\backupcron.php" >> "C:\wamp\www\Test\admin\backup.log" 2>&1

Final checks

  • Test from the command line first.
  • Test running the task manually from Task Scheduler.
  • Check log files and Task Scheduler History for errors.

That's all: follow the steps above to execute specific tasks at specific intervals on Windows using Task Scheduler and a simple .bat wrapper for PHP CLI.

Thursday, October 17, 2013

How to Prevent Backslashes from Being Removed When Inserting Windows File Paths into MySQL

Hi, I faced a problem while inserting the file path to mysql database. You can also encounter similar problem when you work with Mysql. So thought of adding this info for your information.

Problem

While inserting a file path to my mysql table, I noticed that the slashes in the path are missed once they added to mysql table. This is because the problem is with the backslashes \, which are often used to escape certain characters. Hence Mysql considers it as a escape character and ignores it.

Why this happens

Backslash () is an escape character in many languages and in SQL string literals. When you send a string containing single backslashes to MySQL without properly escaping them, they may be interpreted as escape sequences or removed. In PHP, functions that prepare SQL statements or construct SQL literals must receive strings with backslashes escaped, otherwise the stored value will not contain the original single backslashes.

Solutions

You can overcome this problem by different methods.

1) Double the backslashes

You can add double slashes instead of single slash in the directory path.

Eg:

Original (how you think of the path):

D:\Projects\Test\SQLBackup

Written with single backslashes (this may be interpreted incorrectly when inserted):

D:\Projects\Test\SQLBackup  <-- in source you must escape each backslash when building the SQL literal

In many contexts (for example in PHP string literals) you must represent each backslash as \\ in the source so that a single \ ends up in the stored value. If you see backslashes missing in the database, doubling them before insertion is one straightforward fix.

2) Use PHP quotemeta()

You can just do:

quotemeta($rawpath)

before the insert statement. This function adds backslashes before characters that are considered special in regular expressions; it can also help prevent removal of backslashes when building SQL literals.

3) Use PHP addslashes()

You can also just do:

addslashes($url)

This will escape single quotes, double quotes, backslashes and NUL bytes by prefixing them with backslashes.

All the above should work. I just tried the first two and they work perfectly fine.

Safer, recommended approach (avoid manual escaping)

While the above methods fix the immediate problem, the safest practice for inserting any user-supplied or variable strings into a database is to use parameterized queries (prepared statements) or escaping functions that are tied to the database connection's character set.

Examples:

  • Using mysqlirealescape_string (if you are using mysqli and not using prepared statements):
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
$escaped = $mysqli->real_escape_string($path);
$sql = "INSERT INTO files (path) VALUES ('" . $escaped . "')";
$mysqli->query($sql);
  • Using a prepared statement (recommended):
$mysqli = new mysqli($host, $user, $pass, $db);
$stmt = $mysqli->prepare("INSERT INTO files (path) VALUES (?)");
$stmt->bind_param('s', $path);
$stmt->execute();

Prepared statements avoid the need to manually escape backslashes for SQL and protect against SQL injection. They are the preferred method for inserting strings such as file paths.

Other notes

  • As an alternative for storing paths, you can consider using forward slashes (/) in paths on many platforms (PHP accepts them on Windows for many filesystem functions) — they avoid the escaping issues of backslashes and are cross-platform-friendly.
  • Ensure your DB connection charset is set (for example, utf8mb4) before calling escaping functions like real_escape_string.

So thought of sharing this info with you all. Happy Coding!!!

Friday, February 15, 2013

Preserve Paragraphs from MySQL in PHP using nl2br()

Greetings of the Day!!!

When I was working with one of the website Designing, I noticed a strange problem. Maybe it's not a problem, but for a developer it looks like one. Many of us can come across such an issue, so I thought of penning down the known solution for it.

The problem

When you store a paragraph of text in a MySQL database (in a TEXT or VARCHAR column) and retrieve it with PHP, the text may display as a single continuous block in the browser with no paragraph breaks. The data itself still contains newline characters, but HTML ignores plain newlines and renders them as a single space.

Why this happens

HTML does not render raw newline characters ("\n" or "\r\n") as line breaks. When the browser receives plain text with newline characters, it collapses whitespace and shows the content as one paragraph.

The simple solution: nl2br()

PHP provides a built-in function nl2br() which converts newline characters to HTML line break elements (
or
). Use it when you want to display text from the database with the original line breaks preserved.

Example:

// Basic usage
echo nl2br($row_jobdetails['job_description']);

That will convert each newline in job_description into a
so the browser shows paragraph-like breaks.

Secure output (important)

If the stored text can contain user input, you should escape HTML to prevent cross-site scripting (XSS) before adding
tags. Combine htmlspecialchars() with nl2br():

// Secure usage: escape HTML, then convert newlines to <br>
echo nl2br(htmlspecialchars($row_jobdetails['job_description'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));

This prints user-entered text safely and preserves visible line breaks.

Alternatives

  • CSS approach: If you prefer not to alter the text on the server side, you can use CSS to preserve line breaks:
<div style="white-space: pre-line;">
  <!-- raw text with newlines will show line breaks here -->
  <?php echo htmlspecialchars($row_jobdetails['job_description'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?>
</div>

The CSS property white-space: pre-line preserves newline characters as line breaks while still wrapping long lines.

  • Storing HTML: If you deliberately store HTML in the database (for example, content entered in a WYSIWYG editor), you may already have

    or
    tags in your content. In that case, do not run htmlspecialchars() when outputting, but ensure input is sanitized on entry.

Notes about column types

Using TEXT or VARCHAR does not change how browsers render newlines. Newlines are a part of the stored string. What matters is how you convert or render those newline characters when generating HTML.

Example recap

// Unsafe if text is user-provided:
echo nl2br($row_jobdetails['job_description']);

// Safer for user-provided text:
echo nl2br(htmlspecialchars($row_jobdetails['job_description'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));

That's it. It does all the trick. Happy Coding!!!