Trying to run MySQL command line commands from PHP

software development


Hello all,

I have a MySQL command line I am trying to run from a PHP script, but cannot get it to work. (The MySQL command backs up my database, using “mysqldump”)

The MySQL command line works fine from SSH, and generates the file just fine.

My PHP script also seems to be set up okm, using “shell_exec” to run shell commands. When I give it a command line using “ls” it returns results just fine.

But when I replace this ls sample command with my mysqldump command line, I get no results and no file gets created.

So to recap: a command line works fine from SSH, but will not work via shell_exec.

A colleague told me I need to establish the permissions of the PHP script, but not sure about this…

any help is appreciated!


Are you somehow passing the DB password in with the command line? If you’re waiting for it to prompt and trying to send it the password programmatically, that probably won’t work because the password prompt may use a different terminal for security purposes.

I ran into this with a java app that needed to exec a password-requiring program. Since the script essentially runs headless, it doesn’t have an actual terminal to send the password prompt to.



thanks for the reponse, here’s the command I am using:

mysqldump --opt -u username -ppassword -h host db-name > file

(except replace varname with the actual data)

This command works perfect from SSH. But when I try this command from a PHP script using shell_exec, it does not work.

Is there any way to run this command from a PHP script?? thanks!


Are you calling this page directly or are you trying to fire it off as a cron task? When running a shell script via PHP through cron you need to add a special line at the top of the file or it won’t run.

#!/usr/local/bin/php -qIf the PHP script fails when calling it directly, what error are you getting?