got stuck - uploading via Curl an data-binary option - php

first i've to say, that i'm totally new to cURL. But I've just code some lines with curl and PHP to Upload some XML files.
The following Code is working very good. (just looked around and build up a simple working solution)
Now i've got the issue to use the curl --Data-Binary option instead of the -F (Form) option.
The following Code is in the php-File (curlupload.php):
<?php
#$authcode = htmlspecialchars($_POST["acode"]);
if ($authcode == "1234"){
echo "AuthCode ok\n";
$upstatus = "1";
$uploadpath = "files/";
$filedata = $_FILES['file']['tmp_name'];
$target_file = $uploadpath . basename($_FILES["file"]["name"]);
#echo "Acode:" . $authcode . "\n";
#echo "filedata= ".$filedata."\n";
echo "target_file= ".$target_file."\n";
#echo "1 upstatus= ".$upstatus."\n";
if (strpos($target_file, ".xml") == true) {
$upstatus = "1";
echo "2 upstatus= ".$upstatus."\n";
if (file_exists($target_file)) {
echo "Sorry, file already exists.\n";
$upstatus = "0";
}
#echo "4 upstatus= ".$upstatus."\n";
if ($upstatus == "1") {
if ($filedata != '')
copy($filedata,$target_file);
echo "\n-----\n";
echo "success\n";
}
}else{
$upstatus = "0";
#echo "3 upstatus= ".$upstatus."\n";
echo "Filenamecheck Failed.\n";
}
if ($upstatus == "0") {
echo "Sorry, your file was not uploaded.\n";
}
}else{
echo "NO.";
}
?>
my cURL command for uploading a file is the following:
curl -v -F 'file=#/root/testfile01.xml' -F 'acode=1234' http://webserver/upload2/curlupload.php
Now i'm going to use the -d and --data-binary option like this:
curl --data-binary "file=#testfile02.xml" --data "acode=1234" http://webserver/upload2/curluploadtest.php
with the 2nd above command i receive the following messages:
AuthCode ok
target_file= files/
Filenamecheck Failed.
Sorry, your file was not uploaded.
so, the variables got no input - Can somebody please tell me, what i've got to change in the PHP file, so, that the databinary option used by curl is going to work?
Thanks a lot for your helping toughts!

Related

download file to my server with php with a url without file name

I can download a csv file via a fixed url. The url just doesn't have a file name.
When I open the url in a browser, the file export.csv is generated and after about 10 sec the download starts.
Now I want to download this export csv file directly to my own server,
I have the code below, but it doesn't work in my case.
Can you help me? my thanks are big
<?php
$url =
'https://www.example.com/product-export/link123456789';
$file_name = basename($url);
if (file_put_contents($file_name, file_get_contents($url)))
{
echo "File downloaded successfully";
}
else
{
echo "File downloading failed.";
}
?>
As the generated output filename is always export.csv, we may use the following to specify the filename:
$file_name = dirname(__FILE__) . "/export.csv";
(make sure the directory is write-permitted so that the php can save the file "export.csv")
Hence, the code will be:
<?php
$url = 'http://www.createchhk.com/SOanswers/export1a.csv';
//$file_name = basename($url);
$file_name = dirname(__FILE__) . "/export.csv";
if (file_put_contents($file_name, file_get_contents($url))) {
echo "File downloaded successfully";
} else {
echo "File downloading failed.";
}
?>
For your cronjob, it will be something like :
1 1 * * * php /path_to_the_php/test.php

Redirection not working with various methods

I've the following PHP script launching on click of a submit form button :
<?php
//header('Location: video_download.html');
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["logo"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$new_name = 'logo'.'.'.$imageFileType;
$target_file = $target_dir . $new_name;
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["logo"]["tmp_name"]);
if($check == false) {
echo "File is not an image.\n";
$uploadOk = 0;
}
}
// Check file size
if ($_FILES["logo"]["size"] > 5000000) {
echo "Sorry, your file is too large.\n";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "png") {
echo "Sorry, only PNG files are allowed.\n";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.\n";
if (file_exists("config.txt")) {
unlink("config.txt");
}
if (file_exists("upload/logo.png")) {
unlink("upload/logo.png");
}
// if everything is ok, try to upload file & create config.txt
} else {
if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
$template = $_POST['template'] . "\n";
$club = $_POST['club'] . "\n";
$stats = $_POST['stats'];
if (file_exists("config.txt")) {
unlink("config.txt");
}
file_put_contents("config.txt", $template . $club . $stats);
echo '<meta http-equiv="Refresh" content="0; url=video_download.html">';
shell_exec("./blender_lite/bin/blender -b -P blender.py");
exit();
} else {
echo "There was an error uploading your file.\n";
exit();
}
}
?>
I want it to redirect the browser to another html page after executing all script's content. I've tried two different approach : the header (commented in the above code) and echoing an html meta tag with a redirection.
Both doesn't work for unknown reasons and I can't find it (already passed many hours trying to find other methods and resolve the issue without success, so I guess it's kind of a specific issue with a part of my php script). Any help is welcome, thanks :)
You would use the header function.
header("Location: http://www.website.com/page.php");
exit();
Replace the part of your code where you echo the meta refresh with the header location command and place it at the end of your logic. This will only redirect when everything else is complete then.
Example:
if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
$template = $_POST['template'] . "\n";
$club = $_POST['club'] . "\n";
$stats = $_POST['stats'];
if (file_exists("config.txt")) {
unlink("config.txt");
}
file_put_contents("config.txt", $template . $club . $stats);
shell_exec("./blender_lite/bin/blender -b -P blender.py");
header('Location: video_download.html'); // <-- put redirect here
exit();
} else {
echo "There was an error uploading your file.\n";
exit();
}
Found out that the redirection worked fine as I did on my first post. The issue was that PHP waits for the shell_exec to be over. Thus, since I was launching a blender rendering with shell_exec, it was taking several minutes to end so I thought the redirection was not working.
Using exec('bash -c "exec nohup setsid ./blender_lite/bin/blender -b -P blender.py > /dev/null 2>&1 &"');
instead of shell_exec("./blender_lite/bin/blender -b -P blender.py");
so the PHP script doesn't wait for the command to end is the solution, the redirection is now immediate.

Read all lines on file uploaded

I know this subject already exist but in my case is a little more difficult.
I'm reading .EDI files (current succeed) on PHP, the process:
1.- I upload a .edi file from a html form.
2.- I send those attributes from the form to read on my php code.
I got the code like this:
if(isset($_FILES['ufile']['name'])){
$tmpName = $_FILES['ufile']['tmp_name'];
$newName = "" . $_FILES['ufile']['name'];
if(!is_uploaded_file($tmpName) ||
!move_uploaded_file($tmpName, $newName)){
echo "<table><tr><td><strong>Failed to read file ".$_FILES['ufile']['name']."</strong></td></tr></table>";
} else {
echo "<br>";
//coloca o conteudo do arquivo para a variavel $arquivo
$ponteiro = fopen ($_FILES['ufile']['name'],"r");
$arquivo = '';
while (!feof ($ponteiro)) {
$arquivo = $arquivo.fgets($ponteiro,4096);
}
fclose ($ponteiro);
if (unlink($_FILES['ufile']['name']) != 1) echo "Erro ao deletar arquivo!";
$padrao = fnc_resgata_padrao($arquivo);
if ($padrao == "COARRI"){
$a = fnc_processa_coarri(trim($arquivo));
prc_mostra_coarri($a);
}
elseif ($padrao == "CODECO") {
$a = fnc_processa_codeco(trim($arquivo));
prc_mostra_codeco($a);
}
else {
echo "<table><tr><td><strong>Invalid file</strong></td></tr></table>";
}
}
} else {
echo "You need to select a file. Please try again.";
}
The problem is, in this way only read the first line of the .EDI file and not all lines. I'm trying to understand that i must print an array but i don't know how to do it because my $a has the values i'm interested.
If the post is hard to understand, please let me know.
update 1
I just deleted some lines of the code, nothing important.

HTMLDOC does not execute from PHP

I am trying to create a PDF from an HTML file from a PHP page (Apache, LAMP) Wierd thing is, when I execute the script from the command line, it works and creates the PDF as expected. However when I browse to the page in my browser, it does nothing. I'm thinking it's a permissions issue somewhere, but I'm stumped! Here's the code. (NOTE the ls command DOES produce output in the browser so it's not just an issue of PHP not being allowed to execute shell commands)
<?php
$htmlName = ("output2/alex" . time() . ".html");
$pdfName = ("output2/alex" . time() . ".pdf");
$html = "<html><body><h1>Hello, World!</h1></body></html>";
$fileHandle = fopen($htmlName, "w+");
fwrite($fileHandle, $html);
fclose($fileHandle);
$command= "htmldoc -t pdf --browserwidth 1000 --embedfonts --header ... --footer t./ --headfootsize 5.0 --fontsize 9 --bodyfont Arial --size letter --top 4 --bottom 25 --left 28 --right 30 --jpeg --webpage $options '$htmlName' -f '$pdfName'";
echo "OUTPUT: \r\n";
$X=passthru($command);
echo "TESTING LS:";
$y=passthru("ls -al");
if(file_exists($htmlName) && file_exists($pdfName)) {
echo "Success.";
} else {
echo "Sorry, it did not create a PDF";
}
?>
When I execute the script from the command line it produces the expected output, and creates a PDF file like it's supposed to:
> php alextest.php
Zend OPcache requires Zend Engine API version 220131226.
The Zend Engine API version 220100525 which is installed, is outdated.
OUTPUT:
PAGES: 1
BYTES: 75403
TESTING LS:total 2036
drwxr-xr-x 9 ----- and so on...
When I browse the page in Chrome, it outputs only the LS command.
help!?
You might try using a full path as your php file my be executing in a different directory than it is saved in depending on how it is loaded. (IE via include, require, or .htaccess or directly by apache.)
IE
$htmlName = ("/home/alex/html/output2/alex" . time() . ".html");
$pdfName = ("/home/alex/html/output2/output2/alex" . time() . ".pdf");
I agree with the comments that using a package like http://dompdf.github.io/ or https://tcpdf.org/ would be best though.
I've seen the same issue, and for the life of me I simply couldn't find the answer to why it wouldn't do it from a web based call, but never a problem from the command line. So, instead of fighting my way to a solution on that front, I created a Perl proxy to allow me to parse PDFs from the command line making it useful for virtually any given purpose. For, with Perl, I've never had a problem parsing PDFs, and I've been doing it for decades now.
So, here's what you do. PHP Code:
exec("/usr/local/bin/perl5 -s /path/to/perl/executable/parse-pdf-from-html-document.pl -source=markup-file.html",$output);
foreach ($output as $aline) {
#- WAS SUCCESSFUL
if (strstr($aline,'Successful!') == TRUE) {
#- no feedback, win silently
}
#- NOT SUCCESSFUL
else {
echo $aline . "\n";
}
}
With $output holding the results of running exec.
Now let's look at the Perl code for parse-pdf-from-html-document.pl:
#!/usr/local/bin/perl5 -s
#- $document coming from commandline variable, via caller: PHP script
$myDocumentLocale = "/path/to/markup/document/".$document;
if (-e $myDocumentLocale) {
$documentHTML = $myDocumentLocale;
$documentPDF = $documentHTML;
$documentPDF =~ s/\.html/\.pdf/gi;
$myDocumentHTML = `cat $myDocumentLocale`;
$badPDF = 0;
$myPDFDocumentLocale = $myDocumentLocale;
$myPDFDocumentLocale =~ s/\.html/\.pdf/gi;
$badPDF = &parsePDF($myDocumentLocale, $myPDFDocumentLocale);
if ($badPDF == 0) {
print "Successful!";
}
else {
print "Error: No PDF Created.";
}
exit;
}
else {
print "Error: No document found.";
exit;
}
sub parsePDF {
my ($Ihtml, $Ipdf) = #_;
$wasBad = 0;
#- create PDF
$ENV{HTMLDOC_NOCGI} = 1;
$commandline="/usr/local/bin/htmldoc -t pdf13 --pagemode document --header ... --footer ... --left 1cm --size Letter --webpage -f $Ipdf $Ihtml";
select(STDOUT);
$| = 1;
#print "Content-Type: application/pdf\n\n";
system($commandline);
if (-e $Ipdf) {
$wasBad = 0;
}
else {
$wasBad = 1;
}
return $wasBad;
}
exit;

Issue in secure file upload script using command line AV

I have a secure file upload function that's part of my website
and I'm using an antivirus to help me checking the file a user trying to upload.
This is my uploadprocess.php file
$target_tmp = "D:\avscan\u\\";
$file = basename( $_FILES['uploaded_file']['name']) ;
if($file != "")
$_SESSION['file'] = $file;
$target = 'C:\xampp\htdocs\ssd\Uploads\\';
$file_path = $target_tmp.$file;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
$safe_path = escapeshellarg($file_path);
$command = 'scancl'. $safe_path. ' --stdout';
$out = '';
$int = -1;
$output = exec($command, $out, $int);
echo "The output is" .$output;
echo $int;
exit(0);
//Checking for Virus.
if ($int == 0) {
$target = $target.$file;
//echo $target; exit(0);
copy($file_path, $target);
$uploaded = "The file ". $_SESSION['file']. "has been uploaded";
$clean = 'File is Clean.';
$_SESSION['status'] = $clean;
$_SESSION['upload'] = $uploaded;
header("location: ../upload.php");
exit(0);
}
// File is a virus.
else {
$mal = 'Contains Malware';
$deny_up = "Unable to Upload Your File!";
$_SESSION['status'] = $mal;
$_SESSION['upload'] = $deny_up;
header("location: ../upload.php");
exit(0);
}
}
else
{
echo "SORRY, There was a Problem Uploading Your File."; exit(0);
$err_upload = "SORRY, There was a Problem Uploading Your File.";
$_SESSION['err'] = err_upload;
header("location: ../upload.php");
exit(0);
}
It prints me value of 1 for the $int for all files (malicious and non ones) This is my second try with a different AV now I'm using Avira and before I was using clamscan
can someone share me some hints, and tell me what's going on
PS the system is installed on XAMPP if that makes any difference
Can you be more specific about what's not working here? In theory what you doing seems fine at least for ClamAV since it has these return codes (from man clamscan):
RETURN CODES
0 : No virus found.
1 : Virus(es) found.
2 : Some error(s) occured.
Maybe it want to log the output of the exec call, if you are not getting the exit code you expect the reason should be in the output (like missing a command line flag).

Categories