Is file_get_contents multi line? - php

Does file_get_contents maintain line breaks? I thought it did but I have tried this:
if($conn){
$tsql = file_get_contents('scripts/CreateTables/SLR05_MATCH_CREATETABLES.sql');
$row = sqlsrv_query($conn, $tsql);
print_r(sqlsrv_errors());
}
The errors I get is that SQL Server complains that there is incorrect syntax. I get the same errors when I run the SQL Script without any line breaks, which suggests file_get_contents removes them?
When I run the script normally (open the file in SQL Server Management Studio) and execute it, it works perfectly.
So is there something that I can use that maintains line breaks etc? Or is there another problem here in using queries from a file with the SQL Server PHP Driver from Microsoft?
Thanks all for any help

file_get_contents() does preserve the file. Perhaps your file contains the wrong "type" of line-breaks? Linux -vs- Windows style?
Also, I'm not familiar with sqlsrv_query() ... can that be used to run multiple queries (as a script might), or only single queries, one at a time?

Related

bash script not executing mysql command with values passed as variables

I am modifying a set of bash scripts that process video files and reports the processing steps to a mysql database (here is the original code in question).
The function that does the database reporting is called from the main processing script and looks like this in the original:
_report_to_db(){
if [ "${REPORT_TO_DB}" = "Y" ] ; then
echo "INSERT IGNORE INTO tableA (objectIdentifierValue,object_LastTouched) VALUES ('${MEDIA_ID}',NOW()) ON DUPLICATE KEY UPDATE object_LastTouched = NOW()" | mysql --login-path="${LOGIN_PROFILE}" "${DB_NAME}" 2> /dev/null
_db_error_check
fi
}
Since the scripts are meant to be run directly from the command line, when you run them that way it works fine. But I'm running them via php from a web interface and there's some shenanigans going on with the quoting/escaping of whitespace and/or variables.
For instance, the script breaks on the whitespace after ...| mysql and it thinks I'm trying to run mysql as root without a password and totally ignores the --login-path and the other stuff I'm piping to it.
When I call mysql from a variable like so:
_report_to_db(){
if [ "${REPORT_TO_DB}" = "Y" ] ; then
SQL_ARRAY=(INSERT IGNORE INTO tableA (columnA,lastTouched) VALUES ("${SOME_PASSED_VALUE}",NOW()) ON DUPLICATE KEY UPDATE object_LastTouched = NOW();)
MYSQL_COMMAND_ARRAY=(mysql --login-path="${LOGIN_PROFILE}" -e "${SQL_ARRAY[#]}" "${DB_NAME}")
echo "$(${MYSQL_COMMAND_ARRAY[#]})"
_db_error_check
fi
}
... I am able to log into mysql correctly but the SQL query is ignored (when it echos the result you get the standard MySQL --help output.
So far I have tried all kinds of variations on quoting, escaping, referencing the query as a separate string variable, as an array (as you see here).
What is also not helpful is that the original _db_error_check() function only checks the value of the pipe exit status. So if the pipe is ok, but there's a problem further down the path, it fails silently.
_db_error_check(){
if [ "$?" != "0" ] ; then
# reports an error if the pipe exit value ≠ 0
else
# everything is ok! even if there was a mysql error
fi
}
This is not a file or database permissions issue (already triple checked that). Are there quotes or some other stupid thing that I am missing?? Thanks! Oh, I am running OSX El Capitan.
UPDATE
Lol, I was going to post the PHP that calls the script and then I remembered that the PHP is actually calling a Pyhton script that does some other processing too, and that is what calls the bash script. Here it all is:
PHP
$command = escapeshellcmd("/usr/local/bin/python3 /Users/user/path/to/ingest.py " . $user . " 2>&1");
while (# ob_end_flush());
$proc = popen($command, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
# flush();
}
echo '</pre>';
PYTHON
for item in os.listdir(ingestDir):
if not item.startswith("."):
filePath = os.path.abspath(ingestDir+"/"+item)
fileNameForMediaID = os.path.splitext(item)[0]
try:
ingest = subprocess.Popen(['/usr/local/bin/ingestfile','-e','-u',user,'-I',filePath,'-m',fileNameForMediaID])
ingest.wait()
os.remove(filePath)
except IOError as err:
print("OS error: {0}".format(err))
UPDATE 2
I think this might actually be a weird quirk of my installation (go figure). Using mysql --login-path=myDbUser [etc...] from a shell on my host machine I keep getting the error ERROR 1045 (28000): Access denied for user 'ADMIN'#'localhost' (using password: NO) where the client user is ADMIN and I am trying to login as myDbUser.
I actually uninstalled and reinstalled mysql (via Homebrew) and still have the same results. Using a different machine (running Sierra, but the same mysql version) I can run the above shell command successfully and log into mysql as the target user.
Also on the host machine, I can sudo -u _www zsh and run the command as the Apache user (which is the user running the whole show) without a problem. SO WHY IS IT NOT RUNNING CORRECTLY EITHER IN THE SCRIPT OR EVEN RUN FROM SHELL AS MY MAIN CLIENT USER???
Any ideas? $PATH is identical in all cases mentioned above. Same ~/.mylogin.cnf setups. Is there anything else stupid obvious I missed?
You need to use indirect expansion here:
echo "$(${MYSQL_COMMAND_ARRAY[#]})"
the man says:
If the first character of parameter is an exclamation point (!), and
parameter is not a nameref, it introduces a level of variable
indirection. Bash uses the value of the variable formed from the rest
of parameter as the name of the variable; this variable is then
expanded and that value is used in the rest of the substitution,
rather than the value of parameter itself. This is known as indirect
expansion. If parameter is a nameref, this expands to the name of the
variable referenced by parameter instead of performing the complete
indirect expansion. The exceptions to this are the expansions of
${!prefix*} and ${!name[#]} described below. The exclamation point
must immediately follow the left brace in order to introduce
indirection.
${!name[#]}
${!name[*]}
If name is an array variable, expands to the list of array indices
(keys) assigned in name. If name is not an array, expands to 0 if name
is set and null otherwise. When ‘#’ is used and the expansion appears
within double quotes, each key expands to a separate word.
PS: If I may put forward a piece of my personal opinion, having a chain of php -> python -> bash is the worst coding style one can ever met, you may want to rewrite it into single langue so it will be easier to track down further issues at least.

PHP PDO Incorrect syntax near GO, MSSQL & sql_srv [duplicate]

This question already has answers here:
Incorrect syntax near 'GO'
(9 answers)
Closed 6 years ago.
I am having trouble executing a long MSSQL script using PHP and PDO.
It contains some batch statements separated by GO. The script runs if its executed in Management Studio.
I have ensured line endings are not causing the issue.
I have also tried to enable beginTransaction() before the request is executed. Which returns the following error: SQLSTATE[IMSSP]: This function is not implemented by this driver.
I'm using IIS8 and PHP 5.4.16 and the pdo_sqlsrv driver
First part of the script:
USE foo;
IF object_id(N'ToBit', N'FN') IS NOT NULL
DROP Function dbo.ToBit
GO
CREATE FUNCTION dbo.ToBit(
#InputString varchar(250)
)
RETURNS BIT
AS BEGIN
DECLARE #OutputBit BIT
SET #OutputBit = CASE
WHEN (#InputString = 'yes') THEN 1
WHEN (#InputString = 'true') THEN 1
WHEN (#InputString = '1') THEN 1
ELSE 0
END
RETURN #OutputBit
END
Is it down to the driver? I can't see why GO would require beginTransaction() being called? Other than that I'm out of ideas.
Update: I think I might have found an answer here. Will update if I find a soloutio.
Incorrect syntax near 'GO'
Have found an answer here by Jon Galloway
GO isnt valid T-SQL, its a command used by SQLCMD and other utilities, and parsed before execution.
It looks like there are a few options.
1) Execute the script using OSQL / command line
2) Split the script at each GO separator, then run them in sequence
3) If using .NET you can look at using SQL Server Management Objects:
Server.ConnectionContext.ExecuteNonQuery()
This parsers T-SQL statements and "gets" the GO statement as a batch separator.

Issue with the command exec on php

I've an issue while using exec on php, maybe I didn't understand how it works.
The problem is: I wanna execute a binary file named 'test.exe'. That program takes data from an input file 'input.xml' and create an new file 'output.xml' with some modification on those data.
The below command line works perfectly on windows cmd :
>cd C:\Test
>test.exe C:\XML\example.xml C:\XML\example.out.xml
But a php script like this :
exec('C://Test//test.exe C://XML//example.xml C://XML//example.out.xml');
Doesn't work like suspected;
Each time I get beside the empty generated file example.out.xml another file named gmon.out.
I don't know what kind of file it is. Is it possible that this file will be the source of my problem?
Any idea?
You're using the wrong slash, you should be using a double backslash (one to be printed, and another to escape it). Using // will be literally translated to // so PHP will try to find C://Test//test.exe and fail.
The corrected syntax would be either
exec('C:\\Test\\test.exe C:\\XML\\example.xml C:\\XML\\example.out.xml');
or
exec('C:/Test/test.exe C:/XML/example.xml C:/XML/example.out.xml');

Permissions issues when using python through PHP

I need to have my Python program open a file, use some of the data in it, and spit out a different file. I'm having several issues, and was hoping if someone could definitively tell me if they are permissions based and if so, how to fix them. My Python program works through the terminal.
Here are some areas I've identified where it doesn't work:
import matplotlib.pyplot
infile = open('/correct_pathway/textfile1.txt','r')
outfile = open('/correct_pathway/textfile2.txt','w')
It is having troubles on all of these separately. I didn't know there could be permissions issues while importing a module, but there are. Also the files are globally read/writable that it is trying to open.
EDIT: Sorry, that was unintentionally vague and had a typo in the code that was not actually there. The PHP code as written on the webpage is as follows (it works if I call in a much simpler python program, so there is no problem I can think of here):
<?php $command= '/usr/bin/python /correct_pathway/program.py';
$temp = exec($command, $output);
print_r($temp); ?>
The code is supposed to open the infile, read a number off of it, and then write that number to the outfile as well as print off a different number. The printed number should be displayed on the webpage. This all works fine through the terminal, just not on the webpage.
Thanks in advance!
To define how a file should be opened, i.e. read or write, the syntax is to surround the r or w with quotes. So your above code should look like the following.
import matplotlib.pyplot
infile = open('/correct_pathway/textfile1.txt','r')
outfile = open('/correct_pathway/textfile2.txt','w')
see if you can access the files with the quotes added.

phptelnet vs phpseclib

I am trying to connect a unix server from php and execute .exe (C language). Earlier I used phptelnet for this purpose, but now I need to shift to phpseclib due to security issues. I had 100% success rate when I use phptelnet. I could run some of the external programs like 'C' programs with arguments as input in php script. In phptelnet I use
$telnet->DoCommand('cd public_html');
$telnet->DoCommand('cd abc');
$telnet->DoCommand('demo.exe');
$telnet->DoCommand("$inputs", $result);
echo $result;
This works perfect. But now I am using phpseclib. I could connect to the unix server via ssh and execute programs in which the inputs are hard coded in the program. I am using
echo $ssh->exec('./demo.exe');
Now the problem is how to provide inputs to the program. How can I use exec() to accept arguments as inputs. For example, demo.exe is a program to add two numbers. so can I say
echo $ssh->exec("./demo.exe, '10 20'");
Also how can I use exec() to execute multiple lnes of code in a single execution. I am a bit confused. Any inputs on this are greatly appreciated.
Thanks in advance.
Where you have multiple options to commands you'd use:
$ssh->exec("./demo.exe '10' '20'");
Leave out the comma, and enclose individual parameters each. Or convert a list with $opts = implode(" ", array_map("escapeshellarg", $opts)).
If you are using a SSH1 connection, you can only execute one command at a time. If you are connecting to a Windows server (which this looks like), then you can't have two commands on a line.
Only for a BSD/Linux server you could use:
$ssh->exec("cmd1 ; cmd2");

Categories