Essentially, what I have to do is take a HTTP Post, and save the file on a first server, and then forward the post to a second server which saves the file again and then generates an email with the file as an attachment. Presently, I have it working where I send the post to the second server, and it creates the email and sends it out, so that's not an issue.
However, when I tried adding the first server in there, I cannot get it to send at all, or print out a meaningful result. Here is the code for the send/receive script:
<?php
$uploaddir = '/home/www/myfirstsite.com/3d/';
$uploadname = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . $uploadname;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "OK\n";
} else {
echo "ERROR\n";
}
echo "<br>";
$url = 'http://mysecondsite.com:12345/receive_scan.php';
//I use port 12345 because most of the important ports are being used already.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_FILES);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
$result='Result: '.curl_exec ($ch);
echo $result;
echo curlerrno($ch);
echo curlerror($ch);
curl_close ($ch);
Presently, when I send a HTTP post request, it prints out this:
OK
Result:
The code that I use to send the HTTP post request is this:
<html><body>
<form enctype="multipart/form-data" action="http://myfirstsite.com/receive_scan.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="file" type="file" /><br />
<input type="submit" value="Upload File" />
</form>
The code on the second server that receives, which works with this code above if I just change the site, is this:
<?php
$uploaddir = './scans/';
$uploadname = basename($_FILES['file']['name']);
$uploadfile = $uploaddir . uploadname;
echo "File Received\n";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "OK\n";
} else {
echo "ERROR\n";
}
shell_exec("bash sendmail.bash ".$uploadfile." ".$uploadname);
?>
The sendmail.bash is just a script that usings msmtp to send an email to my email.
The structure of $_FILES and curl post are different -I've hit this problem about 3 years ago, took me about 3 days to resolve:
function arraysToBrackets($array, $prefix, $level=0){
$resarr = array();
foreach ($array as $field => $data){
if (is_array($data)){
$resarr = array_merge($resarr, arraysToBrackets($data,
($prefix?$prefix.'['.$field.']':$field),$level+1));
}else{
if ($level > 0){
$resarr[$prefix.'['.$field.']'] = $data;
}else{
$resarr[$prefix.$field] = $data;
}
}
}
return $resarr;
}
$postThrough = arraysToBrackets($_POST);
if ($_FILES){
foreach ($_FILES as $file => $details){
if (is_array($details['name'])){
foreach ($_FILES[$file]['name'] as $file2 => $details2){
if ($_FILES[$file]['tmp_name'][$file2]){
$postThrough[$file.'['.$file2.']'] = '#'.$_FILES[$file]['tmp_name'][$file2];
}
}
}else{
if ($details['tmp_file']){
$postThrough[$file] = '#'.$details['tmp_file'];
}
}
}
}
Related
i am just transloading multiple files from one server to another, if it comes less then this script work perfect, if its crossing to thousands URL's then requests increase and then server block for accessing files.
Here is script
<?php
// Check if form has been submitted
if(#$_POST['submit']){
ini_set("max_execution_time", 0); // no time-outs!
ignore_user_abort(true); // Continue downloading even after user closes the browser.
// URLS -- One on each line
$URL = $_POST['url'];
// Relative path to Save downloaded images
// Default is "downloads"
// Make sure that it is writable (chmoded correctly)
$folder = $_POST['folder'];
// Check if User has provided a local folder
if (!$folder || !isset($folder)){
// Generate error if left blank by user.
die ("Please specify local folder name");
}
// Split all URLS into an array
$urls = split("\n", $URL);
// Remove Carriage Returns (useful for Windows-based browsers)
$urls = str_replace("\r", "", $urls);
$mh = curl_multi_init();
foreach ($urls as $i => $url) {
$path = pathinfo($url);
$g=$folder . "/" . $path["basename"] ;
// Check if file already exists on local folder.
if(file_exists($g)){
// If exists, delete the file so it always contains the latest update.
unlink($g) or die("Unable to delete existing '$g'!");
}
// Update the user of what's going on
echo "$i) Downloading: from <b>$url</b> to <b>$g</b><br />";
if(!is_file($g)){
$conn[$i]=curl_init($url);
$fp[$i]=fopen ($g, "w");
curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
curl_setopt ($conn[$i], CURLOPT_HEADER ,0);
// curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,1000);
curl_multi_add_handle ($mh,$conn[$i]);
}
}
do {
$n=curl_multi_exec($mh,$active);
}
while ($active);
foreach ($urls as $i => $url) {
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
fclose ($fp[$i]);
}
curl_multi_close($mh);
} // task closed
?>
<br />
<br />
<fieldset>
<legend>
<label for="url">Server to Server Upload Script</label>
</legend>
<form method=POST>
<label for="url">Insert Files URL, One Per Line: </label><br />
<textarea rows=15 cols=75 id="url" name="url"><?= $URL ?></textarea><br />
<label for="folder">Folder Name: </label><input type=text id="folder" name="folder" value="uploads"/>
<input type=submit name="submit" value="Start Uploading Files!" />
</form>
</fieldset>
With this script if i add 5000 URL's it suddenly starts sending request and transloading the files. (Server block it due to huge requests.)
How do i add code once the first file transloaded then the other
request should be sent. ?
I have a form that users can upload files like html, css, php, java, js, txt, javascript and other files which i included
But my problem is how can i prevent xss attack or face deformation after successful upload
Example when user upload files like this
<input type='text'> //This will show input instead of in plain text
body{display:none!important;} // My document body off
So i tried to make this php script, it worked very fine while viewing in my site but when i try to open the file in my notepadd++ i don't like the look can anyone suggest me how i can do this better outside my code or fix mine
<?php
session_start();
if(!class_exists('DBController')){ require_once("../../_inc/dbcontroller.php"); }
if(isset($_FILES['fileuploader'])){
include_once('../fileextension.php');
$test = true;
$FileName = $_FILES['fileuploader']['name'];
$tmp_name = $_FILES['fileuploader']['tmp_name'];
$uploadPath = __DIR__ . '/'.$FileName;
$currentBas = '';
$defaultProjecName = '';
$exetype = pathinfo($FileName, PATHINFO_EXTENSION);
$extension = strtolower($exetype);
if(in_array($extension,$afile)){
$FTypeof = 'file';
}
else if(in_array($extension,$aimg)){
$FTypeof = 'image';
}
else{
$FTypeof = 'unknown';
}
$FDiscripT = 'No available '.($FTypeof == 'unknown') ? '' : $FTypeof.' discription';
//Here i move the selected file in a directory
$moveResult = move_uploaded_file($tmp_name, $uploadPath);
if ($moveResult != true) {
unlink($uploadPath);
}else{
// If file was moved then open file and get the content
if(file_exists($uploadPath)){
$fileUploadname = $uploadPath;
$filechecker = fopen($fileUploadname, "a+");
$mesure = filesize($fileUploadname);
if($mesure == 0){
$sizechecker = 1;
}
else{
$sizechecker = filesize($fileUploadname);
}
$get_content_file = fread($filechecker, $sizechecker);
fclose($filechecker);
//Then here i use htmlentities to encote the file content
if(!empty($get_content_file)){
$sanitize_file = htmlentities($get_content_file);
$sanitize_file_status = true;
}
if($sanitize_file_status == true){
//Now i put the content back the the file
try{
$openForWrite = fopen($uploadPath, 'w');
$recreateNewfile = fwrite($openForWrite, $sanitize_file);
fclose($openForWrite);
if($recreateNewfile){
//Then insert the other information to database
if($test == false){
$makefile_db = new DBController();
$makefile_db->prepare("INSERT INTO jailorgchild(jailowner,jailchildbasname,prodefault,jailchillink,jailchilddate,filediscription,contentType)
VALUES(:jailowner,:jailchildbasname,:SubDif,:jailchillink,:jailchilddate,:FDiscripT,:contentType)");
$makefile_db->bind(':jailchildbasname', $currentBas);
$makefile_db->bind(':SubDif', $defaultProjecName);
$makefile_db->bind(':jailchillink', $FileName);
$makefile_db->bind(':jailowner', $_SESSION['username']);
$makefile_db->bind(':jailchilddate', date('Y-m-d H:i:s'));
$makefile_db->bind(':FDiscripT', $FDiscripT);
$makefile_db->bind(':contentType', $FTypeof);
$makefile_db->execute();
$filewasmake = $makefile_db->rowCount();
$makefile_db->free();
}
echo '<pre>';
echo $sanitize_file;
//echo 'Unclean Content <br/>'. $get_content_file;
}
}catch(PDOException $e){
echo "Error:" . $e->getMessage();
}
}else{
unlink($uploadPath);
}
}
}
}
?>
HTML FORM
<form method="post" action="testuploader.php" enctype="multipart/form-data">
<input type="file" name="fileuploader">
<input type="submit" value="load">
</form>
OUTPUT IN NOTEPAD++
<?php if(isset($_GET['postid'])){ echo '<h5 style="color:
#2f2f2f;">Related Articles</h5><br/>'; <?php } }?>
So if another user download it and the file look like that i don't think is good please i need help
Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
i have a .php file from a videohoster who says that this code is a comandline code which allows me to upload a video to their site and i need to create an interface for a random user that he can upload a video to the videohoster while staying on my website. i thought i simple form like below in html is enought but apparently it doesent work:
front-end, html:
<h2>This form allows you to upload a Video.</h2>
<form action="uploadapi.php" method="post" enctype="multipart/form-data"><br>
<p>Video Name: <input type="text" name="titel" size="50" /></p>
<p>Video Description:<br/><textarea name="text" rows="5" cols="50"> </textarea></p>
<p>Select File, allowed: .mpg </br><input type="file" name="file"></p>
<p><input type="submit" value="Upload"</p>
</form>
the uploadapi.php is supplied by the hoster and so i assume it is correct.
<?php
////////////////////////////////////////////////////////
// for php 5.6+ you need to make some changes in code
// method 1
// add the following line
// curl_setopt($ch, CURLOPT_SAFE_UPLOAD, 0);
//
// method 2
// change
// $post_fields['vfile'] = "#".$file;
// to
// $post_fields['vfile'] = CURLFile($file);
////////////////////////////////////////////////////////
$apiversion = "2.123.20150426";
//REQUIRED Registered Users - You can find your user token in API page.
$user_token = "xxx";
if(count($argv) < 2)
die("Usage: php $argv[0] [VIDEO TO UPLOAD] {SUB FILE}\n");
$file = $argv[1];
if(!file_exists("$file"))
die("ERROR: Can't find '$file'!\n");
$path_parts = pathinfo($file);
$ext = $path_parts['extension'];
$allowed = array("mov");
if (!in_array(strtolower($ext),$allowed))
die("ERROR: Video format not permitted. Formats allowed: .mov!\n");
if(isset($argv[2]))
{
$sub_file = $argv[2];
if(!file_exists("$sub_file"))
die("ERROR: Can't find '$file'!\n");
$path_parts = pathinfo($sub_file);
$ext = $path_parts['extension'];
$allowed = array("srt");
if (!in_array(strtolower($ext),$allowed))
die("ERROR: Subtitle format not permitted. Formats allowed: .srt!\n");
$post_fields['subfile'] = "#".$sub_file;
}
$converter = file_get_contents("http://.../getconv_uploadapi.php? upload_hash=".$user_token);
if($converter=="ERROR")
die("ERROR: Could not choose converter. Aborting... \n");
$post_fields['vfile'] = CURLFile($file);
$post_fields['upload'] = "1";
$post_fields ['token'] = 'xxx';
if(!empty($user_token))
$post_fields['upload_hash'] = $user_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$converter);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
curl_close ($ch);
echo "$result\n";
?>
is my methodology correct (using html form to call the uploadapi.php on my server) or do i need in order to sumit my video to the videohoster via uploadapi.php other programming languages (ajax, javascript etc)?
Provided file is command-line file. It means it won't work on web as expected.
For example, on web you won't have $argv[1] or $argv[2].
You have two options:
you can rewrite uploadapi.php considering that source file is a file that came from your form
or upload your file and call uploadapi.php as a command-line script with arguments using shell_exec or exec, for example.
i thought that i define or fill the variable $argv[1] from the html form since: type="file" name="file"> = $file = $argv[1];?
... ok rewriting upload api is no alternative since it comes from the hoster.
so what i need to do is uploading the uploadapi.php on my server and then keeping my html form like it is? and insted of action=uploadapi.php i need a action=somethingsomething.php which has an exec command to execute uploadapi.php?:
<?php
function somethingsomething($uploadapi) {
exec($uploadapi . " > /dev/null &");
}
?>
I do the image hosting and I have a problem..
I have 3 servers.
First - Site/script
Any two servers for images.
How I Can upload image from "one" server (script) to second and third servers?
<?php
if (isset($_POST['upload']))
{
$blacklist = array('.php', '.phtml', '.php3', '.php4', '.php5');
foreach ($blacklist as $item)
{
if(preg_match('#' . $item . '\$#i', $_FILES['file']['name']))
{
echo "We do not allow uploading PHP files\n";
exit;
}
}
$uploadDir = PROJECT_ROOT . 'upload/'; // 1ST SERVER (THIS SERVER)
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "File uploading failed.\n";
}
}
?>
<form name="upload" method="post" enctype="multipart/form-data">
Select the file to upload: <input type="file" name="file"/>
<input type="submit" name="upload" value="upload"/>
</form>
You could use ftp. PHP has fairly easy way to do this. Check this link.
http://www.php.net/manual/en/book.ftp.php
If you already have HTTP servers runing on the other servers, use cURL. Usage:
Call curl_init
Call curl_setopt
Call curl_exec
The HTTP request can be configured using curl_setopt. Especially of interest are the options CURLOPT_URL, CURLOPT_POST and CURLOPT_POSTFIELDS.
You can use Zend_Http Client to upload the files to other servers per HTTP the same way an HTML Upload Form would do it. You can find all the information you need here in the Section "File Uploads": http://www.zendframework.com/manual/en/zend.http.client.advanced.html
For getting started you should read also this:
http://www.zendframework.com/manual/en/zend.http.client.html
Basically the code you need is:
require_once('Zend/Http/Client.php');
$client = new Zend_Http_Client("http://serverurl/path");
$client->setFileUpload(...);
$client->request();