PHP mail inside function with if/else statements - php

Trying to get my script to send me an email if the file uploads successfully. Here is my part of the script that saves the file to the server as username.site.zip:
if ($this->file->save($uploadDirectory . $_SESSION['myusername'] . '.site.' . $ext)){
return array('success'=>true);}
else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
I'm not quite sure how to add in the mail function so that if it's success=>true then it sends mail('email#domain.com','subject','body');
Any help would be great.

<?php
if ($this->file->save($uploadDirectory . $_SESSION['myusername'] . '.site.' . $ext)){
$message = "The file was successfully uploaded.";
mail('email#domain.com', 'My Subject', $message);
return array('success'=>true);
} else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
?>
You had it. Not sure what you still needed.

Insert your mail command right before the return of the success=>true array like this:
if ($this->file->save($uploadDirectory . $_SESSION['myusername'] . '.site.' . $ext)){
mail('email#domain.com','subject','body');
return array('success'=>true);}
else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
Maybe encapsulate it in a try-catch block, but this should work right out of the box.

Related

PHP using phpseclib - exec(ls...) command doesn't find a file that was just created and exists on the disk

Using phpseclib from my PHP application, I am running a perl .pl script which creates a file on the remote server's drive/folder in one of the exec() commands. This works fine and the file exists. The next exec() does an 'ls' command to retrieve the full filename which contains a date/time stamp on the end of the file name that is unknown. When it runs, it doesn't find the file when it is there and I can see it when doing a manual 'ls' on the Linux system. I believe it might be a timing issue, so I also included a sleep 15 in between creation and doing the 'ls' command, but this did not resolve the issue. And if I run the program again, creating a 2nd file, then the 'ls' returns the filename for the first file I generated. I didn't see an fclose in the documentation, but did see it in some other posts here that might lead me to believe this might also be the issue. Has anyone else experienced this issue and how did you resolve? Thanks.
Updated: Code snippet added....
$ssh2->login(LINUX_USER,LINUX_PASS);
$connected = $ssh2->isAuthenticated();
if ($connected) {
//$_SESSION['feedback'] .= "Connection and authentication successful to " . LINUX_SVR . ".<br>";
$cmd_string = "/usr/bin/perl-report.pl " . LINUX_ENV . " " . $parm1 . " " . $parm2;
$error = $ssh2->exec($cmd_string);
if ($error) {
$_SESSION['feedback'] .= "Unable to execute command to create the Report - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$_SESSION['feedback'] .= "Report successfully created for ID " . $parm2 . ".<br>";
//get the full name of the file created
$cmd_string = "sleep 15";
$ssh2->exec($cmd_string);
$cmd_string = "ls /root/Report-" . $parm1 . "-" . $parm2 . "-" . $date . "*";
$error = $ssh2->exec($cmd_string);
if (empty($error)) {
$_SESSION['feedback'] .= "Unable to execute command to obtain report name - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$filename = $ssh2->exec($cmd_string);
$filename = substr($filename, 6, strlen($filename));
$_SESSION['feedback'].= "The file name created is " . $filename . "<br>";
//verify that the filename is valid
if (substr($filename,0,7)=="Report-") {
//mail the attachment to the emailaddr
$cmd_string = "echo 'Requested Report attached.' | mail -s '" . $filename . "' -a '/root/" . $filename . "' " . $emailaddr . "\n";
$error = $ssh2->exec($cmd_string);
if ($error) {
$_SESSION['feedback'] .= "Unable to successfully email the requested report - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
} else {
$_SESSION['feedback'] .= "Report successfully emailed to " . $emailaddr . ". Process complete.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
}
} else {
$_SESSION['feedback'] .= "Unable to email attachment as filename is invalid - contact Operations with this error.<br>";
$_SESSION['feedback'] .= $ssh2->getLog();
}
}
}
} else {
$_SESSION['feedback'] .= "Connection and authentication failed to " . LINUX_SVR . ".<br>";
}
//disconnect when done
$ssh2->reset();
$ssh2->disconnect();
}

PHP to AWS S3 multipart upload always fails

Trying to upload a 7G file to S3 using the PHP SDK v2 (PHP 5.5 not available). File uploads less than 5G work great, but multipart uploads have never worked. They always end with no message or error at all, just before the upload should complete.
I have full S3 access. Have tried a bunch of different things to no avail.
Code is nothing special:
$uploader = UploadBuilder::newInstance()
->setBucket($bucket_nm)
->setKey($key)
->setMinPartSize(100 * 1024 * 1024)
->setConcurrency(1)
->setSource($src_path)
->setClient($s3)
->build();
try {
$uploader->getEventDispatcher()->addListener(
'multipart_upload.after_part_upload',
function($event) {
$msg = $event['state']->count() . ' parts uploaded.';
echo "$msg<br />";
WriteToLog($msg);
}
);
$uploader->upload();
$msg = 'Upload complete.';
} catch (MultipartUploadException $e) {
$uploader->abort();
$msg = 'Upload failed. ' . $e->getMessage() . '.';
}
echo "$msg<br />";
WriteToLog($msg);
You need to place apply these try catch in place of your for abort or upload process
// Perform the upload. Abort the upload if something goes wrong
try {
$uploader->upload();
echo "Upload complete.\n";
} catch (MultipartUploadException $e) {
$uploader->abort();
echo "Upload failed.\n";
}

Replace uploaded document on confirm not working

My Requirement is as follows:
When user uploads a file i should check for "File already Exists", if file exists i must show confirm box if 'OK' i have to replace and if cancel the reverse.
This is my following code
if (file_exists($path . $documentName)) {
$msg = $documentName . " already exists. ";
?>
<script type="text/javascript">
var res = confirm('File already exists Do you want to replace?');
if (res == false) {
<?php
$msg = 'File Upload cancelled';
?>
} else {
<?php
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " File Replaced Successfully";
$successURL = $document_path . $documentName;
}
else
$msg = $documentName . "Upload Failed";
?>
}
</script>";
<?
}
My problem is even if i give cancel the file is getting replaced.
just let me know where I'm wrong or Is there any other approach?
Please help me to close this issue
Note:jquery Not allowed.
Your problem is that you mix javascript and PHP. The PHP-Code will be run on the server and generates the HTML-document. At this point, the file gets replaced already.
Then, this document (with the javascript-code inside) will then be send to the user and there the javascript-code is run. And in that moment, the user gets to see the confirmaion-dialog, even though the file already was replaced!
Take a look at the source-code that your php-code is generating and you will see what I mean.
A solution would be to add a checkbox to confirm overwriting files. Then after hitting the upload-/submit-button, your php-script would check if this box was checked and either replace the file or not.
#Gogul, honestly, this is not the right way to go. Better that you handle the file submission with an AJAX request which receives a response back from your server (either uploaded successfully, or file exists) which you handle appropriately. If presenting the user an option to replace the file, again handle that action with AJAX.
You can do AJAX request in raw JavaScript (jQuery not required) - see here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You are mixing server side code with client side javascript. The solving of your problem is more complicated if you don't want the user to reupload the document:
Store the file in a temporary location under random filename. Output a yes/no form to the user, including the random filename and original filename.
If the user answers yes, move from temporary location to $path, else remove the file from temporary location.
Guys i came with with this following solution
upload
uploaddocument.php
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_FILES["document"]["name"]);
if (file_exists($path . $documentName)) {
move_uploaded_file($_FILES["document"]["tmp_name"], "F:\\Content\\enews_files\\temp\\" . $documentName);
$msg = $documentName . " already exists. <a href='confirm.php?confirm=1&filename=" . $documentName . "&language=" . $lang . "'>Replace</a>||<a href='confirm.php?confirm=0&filename=" . $documentName . "'>Cancel</a>";
} else {
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " Upload Success";
$successURL = $document_path . $lang . '/' . $documentName;
}
else
$msg = $documentName . " Upload Failed";
}
confirm.php
include("config_enews.php");
$lang = $_GET['language'];
$path = "F:\\Content\\enews_files\\" . $lang . "\\";
//$path = "D:\\test\\test\\" . $lang . "\\";
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_GET["filename"]);
if ($_GET['confirm'] == 1) {
//echo sys_get_temp_dir();die;
if (copy("F:\\Content\\enews_files\\temp\\" . $_GET["filename"], $path . $documentName)) {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=success&fname=$documentName&lang=$lang");
} else {
echo $res = move_uploaded_file($_GET["tempname"], $path . $documentName);
echo $msg = $documentName . " Upload Failed";
header("Location: uploaddocument.php?message=failed&fname=$documentName");
}
} else {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=cancelled&fname=$documentName");
}
I got this spark from #Marek. If any one has better solution kindly provide.
I don't have enough reputations to vote your answers sorry.
Thank you so much for all your support.

HTML/php Parser error

I was running through the tutorial on http://net.tutsplus.com/tutorials/php/online-file-storage-with-php/comment-page-2/#comments
and it was working fine until:
if(strlen($message) > 0)
{
$message = '<p class="error">' . $message . '</p>';
}
This line of php is found in index.php. When I few the page in firefox, it looks like the php parser stops at the greater than. Can I escape the character? Do I need to?
EDIT: All the php code:
<?php
//Load the settings
require_once("settings.php");
$message = "";
//Has the user uploaded something?
if(isset($_FILES['file']))
{
$target_path = Settings::$uploadFolder;
$target_path = $target_path . time() . '_' . basename( $_FILES['file']['name']);
//Check the password to verify legal upload
if($_POST['password'] != Settings::$password)
{
$message = "Invalid Password!";
}
else
{
//Try to move the uploaded file into the designated folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
$message = "The file ". basename( $_FILES['file']['name']).
" has been uploaded";
} else{
$message = "There was an error uploading the file, please try again!";
}
}
//Clear the array
unset($_FILES['file']);
}
if(strlen($message) > 0)
{
$message = '<p class="error">' . $message . '</p>';
}
?>
<html> ... </html> //my html code
The > won't cause the PHP parser to stop.
Without seeing the HTML output by the server, it is hard to say for sure, but since the > is the first > in the file it seems likely that the PHP parser never starts and the browser treats everything between the <?php at the start of the file and the strlen($message) > as a tag.
You need to access the PHP through a web server with PHP installed and configured to process that file (which is typically done by giving it a .php file extension).
What about this?
if(!empty($message)){
$message = '<p class="error">'.$message.'</p>';
}
But why don't you directly assign the paragraph tags to the error message instead of first assigning the error message to $message and then the paragraph tags?
there is not any error in the if condition its working fine
the possible problem in the
if(isset($_FILES['file']))
if($_POST['password'] != Settings::$password)
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))
if you are not getting in the if body it mean the problem in
if(isset($_FILES['file']))
because if it fase than $message = "";
Always use Yoda Conditions and write such statements in (the) reverse(d) order (you're normally used to:
if ( 0 !== strlen( $message ) )
{
$message = 'Hello World!';
}
Anyway, you could also simply check for ! empty( $message )

Echo "success" after using ftp_put()

I have a php script that sends large files via FTP. After the file is sent I'm trying to write to the browser "success". I'm also trying to send a query to the database to record that the file was sent. However, any code that I have that comes after the ftp_put does not get executed.
if (ftp_put($conn_id, $upload_filename, $filename, FTP_BINARY))
{
echo "File Sent";
echo $upload_filename." - ".date("d/m/Y H:i:s")." - ".filesize($filename)." bytes<br>" ;
}
else
{
echo "Problem while Uploading $filename\n <br/>". $upload_filename ;
}
If ftp_put is false the echo works. But, if the ftp_put is a success any code I put there will not run.
The file size I am sending is 7,305kb
It is likely that the problem here is that your script is timing out while the file is uploading. Try adding this line before the code above:
set_time_limit(0);
The thing is that ftp_put() blocks any further action until the upload is finished. Try ftp_nb_put() (no blocking) like so:
$upload = ftp_nb_put($conn_id, $upload_filename, $filename, FTP_BINARY);
if($upload == FTP_MOREDATA)
{
echo 'Uploading ' . $upload_filename . ' - ' . date("d/m/Y H:i:s") . ' - ' . filesize($filename) . ' bytes<br />';
while($upload == FTP_MOREDATA)
{
echo '.'; //Output a . to page or do whatever
$upload = ftp_nb_continue($conn_id);
}
}
//Note: While in the while above, it will either end in FTP_FINISHED or FTP_FAILED
if($upload == FTP_FAILED)
{
echo "Problem while Uploading $filename\n <br />". $upload_filename;
}

Categories