Executing C code from php - php

I am trying to compile and run an C file stored locally in my computer using php
i used the following piece of code
$dir = '/home/User/Desktop';
if ( !file_exists($dir) ) {
mkdir ($dir, 0744);
}
file_put_contents ($dir.'/test.c', $code);
$path = "/home/User/Desktop/test.c";
$Command = "gcc $path 2&>1";
exec($Command,$return_val,$error);
i have set all the permissions to the file using chmod and chgrp
but on executing it just echos "Succesful" on my screen but not my $output value
This is the sample C program i typed in my
#include <stdio.h>
int main()
{
printf("Hello world");
return 0;
}
but the following program runs fine when i have executed it using GCC
i am currently using Ubuntu 14.04.2 LTS
i tried using
$Command = "gcc $path 2&>1"; $output = exec($Command); $output = exec(./a.out);
but still i cant get desired output
I tried to use
$output = exec($Command,$return_val,$error);
now when i echo $error it gives me "2"
I tried using system
$last_line = system('gcc $path', $retval);
echo '
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
i get the following output
Last line of the output:
Return value: 4
sh: 1: cannot create 1: Permission denied
gcc: error: 2: No such file or directory
but i given permission to the file using
sudo chmod g+w /home/User/Desktop/test.c
can anyone help me out with this issue?

It's not 2&>1, it's 2>&1.
sh: 1: cannot create 1: Permission denied
gcc: error: 2: No such file or directory
The first error you see here is the shell complaining about not being able to create a file named "1" to redirect stdout.
The second error is gcc complaining about the lack of an input file called "2".

Related

Create a thumbnail from uploaded pdf

I am trying to make a preview from pdf that users must to upload. I am using 1and1 hosting server, so I don´t have total control about what to install, and I don´t know how to install ImageMagick. I followed these steps and I was using this code (that is working in a different project using a VPS):
private function preViewPDF($filename)
{
$img_path = './assets/uploads/previews';
$file_name = explode(".", $filename)[0].".jpg";
$dir = './assets/upload/files/';
$img = new Imagick($dir."/".$filename.'[0]');
$img->setImageFormat('jpg');
$img->writeImage($img_path."/".$file_name);
return "previews/".$id.$type."/".$file_name;
}
After try that and get Imagick Class not Found Exception, I am trying to convert using exec command:
Actual code
private function preViewPDF($filename)
{
$file_name = explode(".", $filename)[0].".jpg";
$dir = getcwd().'/assets/uploads/files/';
if(file_exists($dir."/".$filename))
{
exec("convert ".$dir."/".$filename.'[0]'." ".$dir."/".$file_name, $output, $return_var);
var_dump($output);
echo "<br>";
var_dump($return_var);
}
else echo "no file";
echo "<br>".$dir."/".$filename.'[0]'."<br>";
echo "<br>".$file_name."<br>";
}
The var_dump($output); throws an empty array. And the $return_var is 1... general error :(
If I change the value between [] (the number of the page I want to convert) $output throws:
array(3) {
[0]=> string(0) ""
[1]=> string(70) "Requested FirstPage is greater than the number of pages in the file: 1"
[2]=> string(53) " No pages will be processed (FirstPage > LastPage)."
}
So... any ideas what am I doing wrong?? Thank you.
Extra Data
Only two little things more (maybe obvious). The first, if I emulate the order on a SSL connection it works (I get a image from a pdf). And second, permissions are not the reason (I tried to create and write a file -with fopen and fwrite- and it works).
EDIT
First, an explanation about my actual code:
$file_name = explode(".", $filename)[0].".jpg";
This line is because the extension of $filename is .pdf, so I need remove this part and concatenate the right extension .jpg (from hello.pdf I get hello.jpg).
$dir = getcwd().'/assets/uploads/files/';
This is the folder where the pdf is uploaded and the jpg preview must be saved.
if(file_exists($dir."/".$filename))
I put this line, simply because I though that the uploading of the pdf wasn´t finished and this was the reason that doesn´t work.
exec("convert ".$dir."/".$filename.'[0]'." ".$dir."/".$file_name, $output, $return_var);
This is the line where the command convert is executed... but doesn´t work.
Second thing is a new simple code I just tried:
if(file_exists("./DpRPJTmfSArPRuGZrOddLendfbhgHTrydwukMRvOMuSzVMDuBb.pdf"))
{
exec("convert ./DpRPJTmfSArPRuGZrOddLendfbhgHTrydwukMRvOMuSzVMDuBb.pdf[0] ./DpRPJTmfSArPRuGZrOddLendfbhgHTrydwukMRvOMuSzVMDuBb.jpg", $output, $return_var);
var_dump($output);
echo "<br>";
var_dump($return_var);
}
else echo "no hay fichero";
The $output is empty, and the $return_var is 1.
Forget all the dross and start simple with the file in the same folder as the code to see if Imagemagick is working.
convert input.pdf output.jpg
Also you have so many variables etc. in the Imagemagick code it is hard to read it.
I am also confused by your code and I would create the filename and path outside the convert code and you can echo it to ensure it contains what you expect.
This looks wrong:
$filename.'[0]'
I would try:
$filename[0]
I assume your pdf has more than one page?
Edit
Try this code - it has a different way of displaying any errors and allows you to view the contents of your command if you have lots of variables etc.
$error=array();
echo "<pre>";
$cmd = "./DpRPJTmfSArPRuGZrOddLendfbhgHTrydwukMRvOMuSzVMDuBb.pdf[0] ./DpRPJTmfSArPRuGZrOddLendfbhgHTrydwukMRvOMuSzVMDuBb.jpg";
// You can use this line to see what the $cmd ontains when using a lot of variables
echo $cmd;
exec("$cmd 2>&1", $error);
echo "<br>".print_r($error)."<br>";
echo "</pre>";
I make preview with this:
exec('convert -density 300 -trim "'.$file.'" -resize 600 -quality 85 -colorspace RGB -background white "'.$destination.'" &', $output, $return_var);
Where $file is tue original and $destination is the name of image.
With the & at the end, each image will be named image-0.jpg, image-1.jpg..
$return_var == 0 when all is OK

Hey, I have this php code to call python file but it gives an error when I run the php code on browser..:

php code:
<?php
exec("C:/Python27/python qwer.py 2>&1", $output);
print_r($output);
?>
Python code:
f = open('myfile.txt','w')
f.write('hi there\n')
Error:
Array ( [0] => C:/Python27/python: can't open file 'qwer.py': [Errno 2] No such file or directory )
give the full path for qwer.py like below
<?php
exec("C:/Python27/python c:/scripts/qwer.py 2>&1", $output);
print_r($output);
?>

exec not working or executing crontab script

Basically I have developed a small script that adds a cron job into a file called "crontask" and then I want to execute it so then it becomes a cron job. Here is the script:
<?php
$filename = "../../tmp/crontask.txt";
$output = shell_exec('crontab -l');
$something = file_put_contents($filename, $output.'* * * * * NEW_CRON'.PHP_EOL);
$cngDir = chdir('../../tmp/');
echo exec('crontab ' . getcwd() . '/crontask.txt');
//var_dump($exe);
?>
Everything is ok, the path is the same and if I copy and paste the path that prints out IT will carry out the cronjob but in PHP it won't???
Everything works, apart from the exec function, it doesn't execute it. Any ideas?
In terminal, if I do:
string(25) "crontab /tmp/crontask.txt"
it will execute it.
Try the following things:
Call to the command using the full command path. Sometimes $PATH is not set in the script environment and can't find the command if not.
Setup the working dir of the script using http://php.net/manual/en/function.chdir.php
Use the absolute path to access to the file
I've had a similar issue with cron jobs
I looked at your code and got a couple of ideas.
I used absolute paths
Here is my code:
$myFile = "/home/user/tmp/crontab.txt";
$addcron = "
0 0 * * * cronjob1 " . PHP_EOL .
"0 18 * * 1-5 conjob2 " . PHP_EOL .
"0 9 * * * cronjob3 " . PHP_EOL ;
$output = exec('crontab -l > ' . $myFile );
file_put_contents($myFile,$addcron ,FILE_APPEND);
echo exec('crontab ' . $myFile );
echo "<h3>Cron job successfully added!</h3>";enter code here
basically i wrote the list of previous cronjobs to a file and then appended the file with new cronjobs. Then added the new list of cronjobs with the crontab command.
the linux write to file command ' > ' was what did the trick ;)

Running a python file from php does not generate the output file

I have a problem running another file from php. I want my php params to be the output of running a python file that calls another file itself.
Here is my php file:
<?php
if (isset($_POST['submit'])) {
$params = solve();
}
function solve() {
exec("python array.py", $output);
return $output;
}
?>
If array.py is simply:
if __name__ == "__main__":
print 1
print 2
print 3
print 4
I will get 1,2,3,4 for my output, but I as soon as I change array.py to the following file that calls os.system, I don't get anything. So the new array.py is:
import os
def main():
os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4
def output():
f = open("tmp.txt", "r")
myReturn = []
currentline = f.readline()
while currentline:
val = currentline[:-1] #Getting rid of '\n'
val = int(val)
myReturn = myReturn + [val]
currentline = f.readline()
f.close()
return myReturn
if __name__ == "__main__":
main()
o = output()
print o[0]
print o[1]
print o[2]
print o[3]
Also if I just run test.py, the output is the file tmp.txt:
1
2
3
4
So now, when I run my php file, the output tmp.txt is not even created in the directory and as a result I don't get any output from my php either.
I am not sure why this is happening because when I just run array.py myself, I get the desired output, and the tmp file is created.
EDIT:
I forgot to include: import os above.
Change exec to:
exec("python array.py 2>&1", $output)
Or check the web server or php error log. This will return the error output from the python script to your php script (not normally what you want in production).

Getting an errno 2 when running a PHP script

Hope you help me... I've been at this for the past 2 days and have to admit that I'm stumped.
The OS I'm on is Ubuntu 9.10 Karmic.
I successfully installed and tested Mapserver. For my class project, I have a php script that I am using to create a layer see below....
The error I get when run the script on a cmd line prompt:
Warning: [MapServer Error]: msProcessProjection(): no system list, errno: 2
in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 16
Warning: Failed to open map file static.map in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 16
Fatal error: Call to a member function owsdispatch() on a non-object in /var/www/mapserverdocs/ms4w/apps/world/mapscripts/staticwms.php on line 18
PHP SCRIPT:
<?php
if (!extension_loaded("MapScript")) dl("php_mapscript");
$request = ms_newowsrequestobj();
foreach ($_GET as $k=>$v) {
$request->setParameter($k, $v);
}
$request->setParameter("VeRsIoN","1.0.0");
ms_ioinstallstdouttobuffer();
$oMap = ms_newMapobj("static.map");
$oMap->owsdispatch($request);
$contenttype = ms_iostripstdoutbuffercontenttype();
if ($contenttype == 'image/png') {
header('Content-type: image/png');
ms_iogetStdoutBufferBytes();
} else {
$buffer = ms_iogetstdoutbufferstring();
echo $buffer;
}
ms_ioresethandlers();
?>
I made the directory and files world wide rwx just to make sure it was not a permissions issue
Any help would be greatly appreciated!!
Thanks
Chris
As meagar said, the issue is probably that this line:
$oMap = ms_newMapobj("static.map");
is unable to find "static.map". The current working directory of PHP is very often not what you'd expect it to be. Try making the path be relative to the current script. If static.map is in the same directory as static.map, try this code:
$mapPath = dirname(__FILE__).'/static.map';
$oMap = ms_newMapobj($mapPath);
$oMap->owsdispatch($request);
if static.map is at, let's say, /var/www/mapserverdocs/ms4w/apps/world/mapfiles/static.map, then try:
$mapPath = dirname(__FILE__).'/../static.map';
$oMap = ms_newMapobj($mapPath);
$oMap->owsdispatch($request);
Notice the */../*static.map. dirname(__FILE__) will return the name of the directory of the PHP file you place that code in.

Categories